python獲取小程序手機號並綁定


最近在做小程序開發,在其中也遇到了很多的坑,獲取小程序的手機號並綁定就遇到了一個很傻的坑。

流程介紹

官方流程圖

 

小程序使用方法

需要將 <button> 組件 open-type 的值設置為 getPhoneNumber,當用戶點擊並同意之后,可以通過 bindgetphonenumber 事件回調獲取到微信服務器返回的加密數據, 然后在第三方服務端結合 session_key 以及 app_id 進行解密獲取手機號。

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"> </button>

返回參數說明

 

參數 類型 說明
encryptedData String 包括敏感數據在內的完整用戶信息的加密數據,詳細見加密數據解密算法
iv String 加密算法的初始向量,詳細見加密數據解密算法

接受到這些參數以后小程序把code,encryptedData,iv發給后台,然后后台解密

后台解密

在解密以前需要session_key進行配合解密,所以首先通過code獲取session_key

 # 獲取openid,session_key
 # Appid為小程序id
    openid_url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code" % ( APP_ID, APP_KEY, code ) req = requests.get(openid_url) rep = req.json() session_key = rep.get("session_key")

在得到session_key,encryptedData,iv以后就可以進行解密了,python2實現代碼如下:

 1 import base64  2 import json  3 from Crypto.Cipher import AES  4 
 5 class WXBizDataCrypt:  6     def __init__(self, appId, sessionKey):  7         self.appId = appId  8         self.sessionKey = sessionKey  9 
10     def decrypt(self, encryptedData, iv): 11         # base64 decode
12         sessionKey = base64.b64decode(self.sessionKey) 13         encryptedData = base64.b64decode(encryptedData) 14         iv = base64.b64decode(iv) 15 
16         cipher = AES.new(sessionKey, AES.MODE_CBC, iv) 17 
18         decrypted = json.loads(self._unpad(cipher.decrypt(encryptedData))) 19 
20         if decrypted['watermark']['appid'] != self.appId: 21             raise Exception('Invalid Buffer') 22 
23         return decrypted 24 
25     def _unpad(self, s): 26         return s[:-ord(s[len(s)-1:])]

調用傳參

# APP_ID為小程序id不是openid!!!
pc = wx_jm(APP_ID, session_key) res = pc.decrypt(encryptedData, iv)

參數詳情參照微信官方文檔https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

微信官方提供了多種編程語言的示例代碼點擊下載

返回數據格式

{ "phoneNumber": "13580006666", "purePhoneNumber": "13580006666", "countryCode": "86", "watermark": { "appid":"APPID", "timestamp":TIMESTAMP } }

 小程序開發系列教程https://blog.csdn.net/michael_ouyang/article/details/54700871


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM