微信授权登录流程

943 阅读1分钟

官方文档

1. 注册一个微信测试号

微信公众平台 (qq.com)

注册登录之后

1.1 保存 appID 和 appsecret

1.2 用自己的手机关注该测试号

2. 准备一个后端接口,接收wechat传递的code,返回用户个人信息

比如下面的http://127.0.0.1:8080/api/user/wxlogin,接受一个 code query参数,返回从wechat获取的用户个人信息

const express = require('express')

// `1` 中的`appID`
const appid = "wxd865f996ab9c8661"  
// `1` 中的appsercret                            
const appsecret = "xxxxxx"           
const grant_type = "authorization_code"

const port = 8080
const server = express()

server.get('/api/user/wxlogin', async (req, res) => {
     // 1. 获取wechat传递的`code`参数  
    const code = req.query.code
    //  2. 通过下面的url获取微信用户的个人信息     
    const loginUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code`
    const loginResp = await fetch(loginUrl)
    const loginData = await loginResp.json()
    // 3. 拿到wechat返回的用户的`access_token`和`openid`
    const access_token = loginData['access_token']
    const openid = loginData['openid']
    const scope = loginData['scope']

    // 4. 使用`access_token`和`openid`获取用户的个人信息
    const userInfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
    const userInfoResp = await fetch(userInfoUrl)
    const userinfo = userInfoResp.json()
    // 5. 编解码 `nickname` 为 `utf-8` 编码
    const nickname = encodeNickname(userinfo['nickname'])
    userinfo['nickname'] = nickname
    // 6. 返回用户个人信息
    res.end(`<h1>Success</h1><p>${JSON.stringify(userinfo)}</p>`)
})
server.listen(port, () => {
    console.log(`open server 127.0.0.1/${port}`);
})

function encodeNickname(nickname) {
    const encoder = new TextEncoder('ISO-8859-1')
    const decoder = new TextDecoder('utf-8')
    return decoder.decode(encoder.encode(nickname))
}

3. 在微信测试号管理页面授权该api接口

微信公众平台 (qq.com)

注意ip和端口都需要填写

4. 前端访问下面的url,用户授权登录,返回用户个人信息

`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
  • appid - 1中的appID
  • redirect_uri - 2中api接口
    • 需要使用encodeURIComponent 函数将uri特殊字符转义