微信小程序获取用户openid和session_key
wxml:
<button bindtap='getOpenIdTap'>获取用户唯一标识openid</button>
<text>openid:{{openid}}\n </text>
<text>session_key:{{session_key}}</text>
js:
const APP_ID = 'wx0843bxxxxxxxf6fc'; //输入小程序appid
const APP_SECRET = '637e11bf3dxxxxxxxxx9f9b1ef5221'; //输入小程序app_secret
var OPEN_ID = '' //储存获取到openid
var SESSION_KEY = '' //储存获取到session_key
Page({
getOpenIdTap: function() {
var that = this;
wx.login({
success: function(data) {
console.log(data);
wx.request({
//获取openid接口
url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + APP_ID + '&secret=' + APP_SECRET + '&js_code=' + data.code + '&grant_type=authorization_code',
data: {},
method: 'GET',
success: function(res) {
console.log(res.data)
OPEN_ID = res.data.openid; //获取到的openid
SESSION_KEY = res.data.session_key; //获取到session_key
that.setData({
openid: OPEN_ID,
session_key: SESSION_KEY
});
}
})
}
})
}
})