python获取微信小程序手机号并绑定遇到的坑

yipeiwu_com6年前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实现代码如下:

 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:])]

调用传参

# 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
  }
}

总结

以上所述是小编给大家介绍的python获取微信小程序手机号并绑定遇到的坑,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

python 字符串和整数的转换方法

数字转成字符串 方法一: 使用格式化字符串: tt=322 tem='%d' %tt tem即为tt转换成的字符串 常用的格式化字符串: %d 整数 %f%F 浮点数 %e%E...

python实现QQ邮箱/163邮箱的邮件发送

python实现QQ邮箱/163邮箱的邮件发送

QQ邮箱/163邮箱的邮件发送:py文件发送邮件内容相当于一个第三方的客户端,借助于QQ/163邮箱服务器来发送的邮件。 主要配置: 导入模块——import  ...

python文字和unicode/ascll相互转换函数及简单加密解密实现代码

这篇文章主要介绍了python文字和unicode/ascll相互转换函数及简单加密解密实现代码,下面我们来了解一下。 import re import random # ord()...

Python实现简单的文本相似度分析操作详解

本文实例讲述了Python实现简单的文本相似度分析操作。分享给大家供大家参考,具体如下: 学习目标: 1.利用gensim包分析文档相似度 2.使用jieba进行中文分词 3.了解TF-...

python xlsxwriter创建excel图表的方法

python xlsxwriter创建excel图表的方法

本文实例为大家分享了python xlsxwriter创建excel图表的具体代码,供大家参考,具体内容如 #coding=utf-8 import xlsxwriter fro...