小程序获取 openid

获取方式参考小程序登录体系

1、小程序端代码
调用登录接口,回调中用 code 换取 openid。

onLaunch(options) {
  wx.login({
    success: function (res) {
      console.log('login',res);
      wx.request({
        url: 'http://localhost:3000/code2Session',
        headers: {
          'Content-Type': 'application/json'
        },
        method: "POST",
        data: {
          code: res.code
        },
        success: function(res) {
          if(res.data.openid){
            sensors.setOpenid(res.data.openid); 
          }
        },
        complete: function() {
          sensors.init();
        }
      })
    },
    fail: function () {
      sensors.init();
    }
  })
}

2、服务端代码
增加与微信接口的交互,获取 openid 返回给小程序端:

// appid 和 appsecret 存储在服务端
var appId = config.appId,
    appSecret = config.appSecret;

router.post('/code2Session', function(req, res) {
  console.log(req.body);
  var param = {
    'appid': appId,
    'secret': appSecret,
    'js_code': req.body.code,
    'grant_type': 'authorization_code'
  }
  var url = 'https://api.weixin.qq.com/sns/jscode2session?' + querystring.stringify(param);
  // console.log(url);
  axios.get(url)
    .then(function(response) {
      console.log('response', response.data);
      res.json(response.data)
    })
    .catch(function(err) {
      console.log(err)
      res.json(err)
    })
    .then(function() {
    })
})
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容