openid 小程序 小程序页面

小程序在哪个页面获取openid

小新
136
2020-12-16 17:25:03
栏目: 云计算

小程序在哪个页面获取openid

小程序获取openid的案例:

第一步,获取code,在app.js文件添加以下代码:

//app.js

App({

  onLaunch: function() {

    wx.login({

      success: function(res) {

        if (res.code) {

          //发起网络请求

          wx.request({

            url: 'https://test.com/onLogin',

            data: {

              code: res.code

            }

          })

        } else {

          console.log('获取用户登录态失败!' + res.errMsg)

        }

      }

    });

  }

})

第二步,在登录页面根据code获取openid,代码:

//根据code获取openid等信息

wx.login({

        //获取code

        success: function (res) {

          var code = res.code; //返回code

          console.log(code);

          var appId = '...';

          var secret = '...';

          wx.request({

            url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code',

            data: {},

            header: {

              'content-type': 'json'

            },

            success: function (res) {

              var openid = res.data.openid //返回openid

              console.log('openid为' + openid);

            }

          })

        }

      })

//正常返回的JSON数据包

{

      "openid": "OPENID",

      "session_key": "SESSIONKEY",

      "unionid": "UNIONID"

}

//错误时返回JSON数据包(示例为Code无效)

{

    "errcode": 40029,

    "errmsg": "invalid code"

}

0
看了该问题的人还看了