最近開發微信小程序支付的時候,需要獲取用戶openid
,查了一下相關資料。
根據:微信小程序案例:獲取微信訪問用戶的openid:
//調用微信登錄接口
wx.login({
success: function (loginCode) {
var appid = ''; //填寫微信小程序appid
var secret = ''; //填寫微信小程序secret
//調用request請求api轉換登錄憑證
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session?appid='+appid+'&secret='+secret+'&grant_type=authorization_code&js_code=' + loginCode.code,
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log(res.data.openid) //獲取openid
}
})
}
})
這段代碼在 開啟開發環境不校驗請求域名、TLS版本以及HTTPS證書 的情況下是可行的,但是正式環境下是沒用的。
因為微信小程序開發設置中無法添加https://api.weixin.qq.com
域名。
添加域名
處理辦法:
- 先在微信小程序中調用
wx.login
獲取loginCode.code
- 將
loginCode.code
傳給服務器,由服務器請求'https://api.weixin.qq.com/sns/jscode2session?appid='+appid+'&secret='+secret+'&grant_type=authorization_code&js_code=' + loginCode.code
,來獲取openid。 - 服務器獲取到
openid
后就可以進行進一步處理,例如進行微信支付相關操作。