微信授权登陆是比较常见的一种登陆方式,今天来总结下实现流程

【uni-app】小程序实现微信授权登陆(附流程图)

//封装微信获取用户code,避免嵌套
login() {
    return new Promise((resolve, reject) => {
        uni.login({
            success(res) {
                resolve(res);
            },
            fail(err) {
                reject(err);
            }
        });
    });
}
async init() {
    //调用微信登陆
    let res = await this.login()
    if (res.code && ['login:ok'].includes(res.errMsg)) {
        //后端通过code调用微信API返回openid/unionid/session_key参数, 存储起来,前端无法直接调用微信相关API
        let openIdRes = await getWechatOpenIdByCode({ code: res.code })
        if (openIdRes.success) {
            let { openId, sessionKey } = openIdRes
            this.openId = openId
            this.sessionKey = sessionKey
        }
    } else {
        //异常处理,再次发起请求或者抛出异常
        // .....
    }
},

【uni-app】小程序实现微信授权登陆(附流程图)

//微信授权登陆按钮
<u-button  open-type="getPhoneNumber" @getphonenumber="getphoneNumber">用户授权登陆</u-button>
//JS部分
//用户授权登陆允许后,返回encryptedData, iv参数
getPhoneNumber(e) {
    //拿到参数后进一步去解密....
    // 授权通过后轮询等待获取sessionKey响应成功
    if (['getPhoneNumber:ok'].includes(e?.detail?.errMsg)) {
          this.handlePolling(e)
    }
}
/**
* 轮询查询是否有sessionKey,防止初始化接口响应时间过长拿不到解密入参,用户解密失败
*/
handlePolling(e) {
    this.timer = setInterval(() => {
        if (this.sessionKey) {
            this.decryptDataInfo(e.detail)
            this.timer = null
        }
    }, 300)
},

发表回复