獲取openid看了些網上的文章沒獲取到也許是我get到找到了一篇借鑒然后自己也搞出來了
首先要去小程序接口文檔看以下這幾個接口
function wx.setStorageSync(key: string): void
將 data 存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個同步接口。
wx.request({})
function wx.setStorageSync(key: string): void //此接口可以設置openid到緩存中
將 data 存儲在本地緩存中指定的 key 中,會覆蓋掉原來該 key 對應的內容,這是一個同步接口。
現在來上代碼........................
首先創建一個環境單擊按鈕獲取當前用戶的openid
test.wxml
<text>{{openid}}</text> <button type="default" bindtap="open">獲取openid</button>
js點擊事件獲取當前用戶的openid
test.js
Page({
/**
* 頁面的初始數據
*/
data: {
openid:''
},
open:function(){
wx.login({
success:function(res){
var that = this;
var header = {
'content-type':'application/x-www-form-urlencoded',
'token': wx.getStorageSync('token')//讀取cookie 拿到登錄之后異步保存的token值
};
if (res.code) {
console.log(res.code);
wx.request({//getOpenid
url: 'https://api.weixin.qq.com/sns/jscode2session',
data: {
appid: '***************', //AppID
secret: '*******************',//secret密鑰
grant_type: 'authorization_code',
js_code: res.code
},
method: 'GET',
header: header,
success: function (res) {
var openid = res.data.openid; //登錄之后返回的openid
// this.setData({
// openid: res.data.openid
// });
console.log(openid+'我的openid')
wx.setStorageSync('openid', openid) //儲存openid
if (openid != null & openid != undefined) {
wx.getUserInfo({
success: function (res) {
},
fail: function (res) {
//console.info('用戶拒絕授權');
}
});
}else{
console.info('獲取用戶openid失敗');
}
},
fail: function (res) {
console.info('獲取用戶openid失敗');
console.log(error);
}
})
}
}
})
}
})
效果只能在真機調試或者電腦模式下才能看出來,注意預覽是看不出來的
