美文网首页
微信小程序 获取openId

微信小程序 获取openId

作者: 淡意的温柔丶 | 来源:发表于2019-11-22 11:48 被阅读0次

步骤

撸码:


  • wxLogin.js 工具类

module.exports={
  getWxUserInfo
}

/**
 *  successCallBack  获取opendId成功回调
 *  failCallBack     获取opendI失败回调
*/
  function getWxUserInfo(successCallBack,failCallBack){
    wx.login({
    success: res => {
      // 发送 res.code 到后台换取 openId, sessionKey
      console.log(res.code)
      if (res.code) {
        console.log(res.code)
        wx.request({
          url: 'https://api.weixin.qq.com/sns/jscode2session', //微信服务器获取appid的网址 
          method: 'post',
          data: {
            js_code: res.code,
            appid:'xxxxxxxxxx', // you appId
            secret:'xxxxxxxxx', //you secret
            grant_type: 'authorization_code'
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded',
          },
          success: function (response) {
            console.log(response.data)
            console.log("openId " + response.data.openid + "    key :" + response.data.session_key);
            successCallBack(response);
          },
          fail:res=>{
            failCallBack(res);
           }
        })
      } else {
        console.log("登录失败");
      }
    },
    fail:res=>{
      failCallBack(res);
    }
  })
}

调用

  var utilwx=require('xxx/wxLogin.js');  //注意路径
  Page({
  data:{
  },
  onLoad:function(options){
},
bindGetUserInfo :function(e){
     var that=this;
 // 查看是否授权
      wx.getSetting({
        success(res) {
          if (res.authSetting['scope.userInfo']) {
            // 已经授权
            utilwx.getWxUserInfo(that.getUserInfoSuccessCallBack, that.getUserInfoFailCallBack);
          }else{
           console.log("未授权");
            }
        }, fail: function(){
          wx.showModal({
            title: '',
            content: '授权个人信息',
            success:function(res){
              if(res.confirm){
                if (res.authSetting["scope.userInfo"]) {////如果用户重新同意了授权登录
                  utilwx.getWxUserInfo(that.getUserInfoSuccessCallBack, that.getUserInfoFailCallBack);
                }
              }
            },fail:function(res){

            }
          })
      }
      })
},
 /**
   * 获取openId成功
   */
  getUserInfoSuccessCallBack: function(res) {
      wx.showToast({
      title: '成功 !',
      icon: 'success'
    })
  },
  /**
   *  获取openId失败
   */
  getUserInfoFailCallBack: function(res) {
    wx.showToast({
      title: '失败!',
      icon:'none'
    })
  },

})

wxml

  <button open-type="getUserInfo" bindtapWx="bindGetUserInfo">获取openId</button>

天坑:

    res.authSetting['scope.userInfo']  并不能调起授权窗口,已弃用。
    只能在wxml 中通过button 的 open-type="getUserInfo" 调起

提示:
这里全在客户端实现获取敏感信息,考虑到安全问题,第二步请求应该放到后台处理

相关文章

网友评论

      本文标题:微信小程序 获取openId

      本文链接:https://www.haomeiwen.com/subject/wgdfwctx.html