微信服务号 - 用户授权
服务号支持完整的OAuth 2.0网页授权,可静默获取用户OpenID或弹窗授权获取用户详细信息(头像、昵称等)。
授权方式对比
| 方式 | scope | 用户感知 | 获取信息 |
|---|---|---|---|
| 静默授权 | snsapi_base | 无感知,自动跳转 | 仅获取OpenID |
| 弹窗授权 | snsapi_userinfo | 弹出授权确认页 | 获取昵称、头像、性别、地区等 |
完整授权流程
const axios = require('axios')
function getAuthUrl(redirectUri, scope = 'snsapi_userinfo') {
const uri = encodeURIComponent(redirectUri)
return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${uri}&response_type=code&scope=${scope}&state=1#wechat_redirect`
}
async function getOAuthToken(code) {
const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${APP_ID}&secret=${APP_SECRET}&code=${code}&grant_type=authorization_code`
const { data } = await axios.get(url)
return data
}
async function getUserInfo(accessToken, openid) {
const url = `https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${openid}&lang=zh_CN`
const { data } = await axios.get(url)
return data
}
app.get('/oauth/callback', async (req, res) => {
const { code } = req.query
const tokenData = await getOAuthToken(code)
const userInfo = await getUserInfo(tokenData.access_token, tokenData.openid)
req.session.user = {
openid: userInfo.openid,
nickname: userInfo.nickname,
avatar: userInfo.headimgurl
}
res.redirect('/user/center')
})