通过wx.login获取用户唯一凭证openId

文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

总结下整个openid、session_key获取的流程:

注册微信小程序、登录后台在设置中获得appId和secret(密钥)
调用wx.login()接口获取登录凭证js_code
调用wx.request()接口把js_code发送到服务器后台
在服务器后台,已知appId、secret、js_code
然后调用官方提供的http接口,即可返回获取openId、session_key 

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
 

// 登录
wx.login({
  success: res => {
    // ------ 获取凭证 ------
    var code = res.code;
    if (code) {
      // console.log('获取用户登录凭证:' + code);
      // ------ 发送凭证 ------
      wx.request({
        url: '后台通过获取前端传的code返回openid的接口地址',
        data: { code: code },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          if (res.statusCode == 200) {
            // console.log("获取到的openid为:" + res.data)
            // that.globalData.openid = res.data
            wx.setStorageSync('openid', res.data)
          } else {
            console.log(res.errMsg)
          }
        },
      })
    } else {
      console.log('获取用户登录失败:' + res.errMsg);
    }
  }
})
 

涉及到安全问题,最好将openid在后台加密为token后返回前端缓存,不宜在前端保存openid 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值