最近在做小程序開發,在其中也遇到了很多的坑,獲取小程序的手機號并綁定就遇到了一個很傻的坑。
流程介紹
官方流程圖
小程序使用方法
需要將 <button> 組件 open-type 的值設置為 getphonenumber,當用戶點擊并同意之后,可以通過 bindgetphonenumber 事件回調獲取到微信服務器返回的加密數據, 然后在第三方服務端結合 session_key 以及 app_id 進行解密獲取手機號。
1
|
<button open - type = "getphonenumber" bindgetphonenumber = "getphonenumber" > < / button> |
返回參數說明
參數 | 類型 | 說明 |
---|---|---|
encrypteddata | string | 包括敏感數據在內的完整用戶信息的加密數據,詳細見加密數據解密算法 |
iv | string | 加密算法的初始向量,詳細見加密數據解密算法 |
接受到這些參數以后小程序把code,encrypteddata,iv發給后臺,然后后臺解密
后臺解密
在解密以前需要session_key進行配合解密,所以首先通過code獲取session_key
1
2
3
4
5
6
7
8
|
# 獲取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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import base64 import json from crypto.cipher import aes class wxbizdatacrypt: def __init__( self , appid, sessionkey): self .appid = appid self .sessionkey = sessionkey def decrypt( self , encrypteddata, iv): # base64 decode sessionkey = base64.b64decode( self .sessionkey) encrypteddata = base64.b64decode(encrypteddata) iv = base64.b64decode(iv) cipher = aes.new(sessionkey, aes.mode_cbc, iv) decrypted = json.loads( self ._unpad(cipher.decrypt(encrypteddata))) if decrypted[ 'watermark' ][ 'appid' ] ! = self .appid: raise exception( 'invalid buffer' ) return decrypted def _unpad( self , s): return s[: - ord (s[ len (s) - 1 :])] |
調用傳參
1
2
3
|
# 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
微信官方提供了多種編程語言的示例代碼點擊下載
返回數據格式
1
2
3
4
5
6
7
8
9
10
|
{ "phonenumber" : "13580006666" , "purephonenumber" : "13580006666" , "countrycode" : "86" , "watermark" : { "appid" : "appid" , "timestamp" :timestamp } } |
總結
以上所述是小編給大家介紹的python獲取微信小程序手機號并綁定遇到的坑,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/zzqit/p/9983407.html