美文网首页
微信小程序:获取openid,唯一id

微信小程序:获取openid,唯一id

作者: 司徒新新 | 来源:发表于2020-05-09 16:29 被阅读0次

从官网获取openid

// 先登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log('正在登录.....' + res.code);
        if(res.code){
          console.log(res);
          // 获取唯一id
          wx.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session',//微信服务器获取appid的网址 不用变
            method:'POST',//必须是post方法
            data:{
              js_code:res.code,
              appid:'wxe998c95asdfg1a69',//仅为实例appid
              secret:'435775c26asdfghjkl0d451ebc2c26c1',//仅为实例secret
              grant_type:'authorization_code'
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            success:function(response){
              console.log("登录成功");
              console.log(response.data)
              /***
                * 将openid存入本地缓存
                * 将session_key 存入本地缓存命名为SessionKey
                * 还能获取到sessionKey,如果有需要,可以存起来
                */
              wx.setStorageSync('app_openid', response.data.openid); 
              // wx.setStorageSync('sessionKey', response.data.session_key)
            }
          })
        }else{
          console.log("登陆失败");
        }
      }
    })

使用


wx.getStorage({
  key:'app_openid',//获取key值
  success: function(res) {
    console.log(res)
    let params = {
      wxid: res.data,
    }
    
    /***
     * res.data 就是唯一openid
     * 
     * 做你想做的
     */
  },
})

相关文章

网友评论

      本文标题:微信小程序:获取openid,唯一id

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