微信小程序獲取用戶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
});
}
})
}
})
}
})
