又開(kāi)始做微信小程序開(kāi)發(fā),在進(jìn)行Scrum故事估點(diǎn)時(shí)坑了自己一把,因?yàn)閷?duì)該功能了解不足,授權(quán)獲取手機(jī)號(hào)及位置一共給了0.5個(gè)點(diǎn),然后還是我領(lǐng)了這個(gè)故事;授權(quán)位置信息這里不說(shuō),很容易,但手機(jī)號(hào)卻是一個(gè)大坑,原本以為在小程序前端就可以搞定,而事實(shí)上卻涉及到了后臺(tái)openid及session_key獲取及微信數(shù)據(jù)解密等信息,需要提供相關(guān)接口。

這里說(shuō)下授權(quán)獲取手機(jī)號(hào)信息的相關(guān)內(nèi)容:
主要分三步進(jìn)行:
1、使用wx.login登錄獲取token,然后在后臺(tái)通過(guò)jscode2session接口得到openid和session_key(這里主要用到session_key),相關(guān)代碼:
wx.login({?
? ? success:function(res){
? ? ? ? console.log('loginCode:', res.code)
? ? }
});
//上面的code, 傳給后臺(tái)(我們是.netcore),然后調(diào)用以下接口生成session_key返回前端
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
2、 通過(guò)getPhoneNumber組件,引導(dǎo)用戶授權(quán),獲取encryptedData(加密數(shù)據(jù))和iv(加密向量)
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">手機(jī)號(hào)碼</button>
3、在上述getPhoneNumber組件回調(diào)中,判斷授權(quán)成功("getPhoneNumber:ok"),請(qǐng)求后臺(tái)數(shù)據(jù)解密接口,得到手機(jī)號(hào)
// getPhoneNumber組件回調(diào)
getPhoneNumber(e) {
? ? if(e.detail.errMsg == "getPhoneNumber:ok") {
? ? ? ? // post請(qǐng)求后臺(tái)手機(jī)號(hào)解密接口
? ? ? ? wx.request({
????????? ? url:?'https://itlao5.com/WxApp/decodePhoneNumber',
????????? ? data:?{
??????????? ? ? encryptedData:?e.detail.encryptedData,
???????????? ? iv:?e.detail.iv,
??????????? ? ? sessionKey:?that.data.session_key,
??????????? ? ? uid:?"",
????????? ? },
????????? ? method:?"post",
????????? ? success:?function?(res)?{
??????????? ? ? console.log(res); // 這里就是你接口返回的數(shù)據(jù),包含手機(jī)號(hào)
????????? ? }
??????? })
? ? }
}
個(gè)人博客:IT老五
微信公眾號(hào):【IT老五(it-lao5)】,一起源創(chuàng),一起學(xué)習(xí)!