飞道的博客

Python3 微信支付(小程序支付)V3接口

411人阅读  评论(0)

起因:

        因公司项目需要网上充值功能,从而对接微信支付,目前也只对接了微信支付小程序支付功能,在网上找到的都是对接微信支付V2版本接口,与我所对接的接口版本不一致,无法使用,特此记录下微信支付完成功能,使用Django完成后端功能,此文章用于记录使用,

        以下代码仅供参考,如若直接商用出现任何后果请自行承担,本人概不负责。

功能:

       调起微信支付,微信回调

代码:
       
1、准备工作:


  
  1. mchid = "xxxxxx" # 商户号
  2. pay_key = "xxxxxx" # 商户秘钥V3 使用V3接口必须使用V3秘钥
  3. serial_num = "xxxxxx" # 证书序列号
  4. # ======================前三个参数在微信支付中可找到===============================
  5. # ============ 商户号(mchid ) 在账户中心——商户信息——微信支付商户号 (是纯数字) ==================
  6. # ============= 商户秘钥(pay_key) 在账户中心——API安全——APIv3秘钥 (需手动设置) ===================
  7. # ============= 证书序列号(serial_num) 在账户中心——API安全——API证书 (需手动申请,通过后会有串证书序列号),申请完成后需要把证书下载到项目中,便于使用 ===================
  8. appid = "xxxxxx" # 微信小程序appid
  9. wx_secret = "xxxxxx" # 微信小程序秘钥
  10. # ============= 微信小程序appid 在产品中心——AppID账号管理——添加关联的AppID ===================
  11. WX_Pay_URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"
  12. # ============= 微信支付调用地址,用于请求接收 预支付交易会话标识: prepay_id ===================
  13. WX_Notify_URL = "https://127.0.0.1:8000"
  14. # ============= 接收微信支付回调地址,必须是https ===================

        2、调起微信支付(后端只能请求微信支付接口向微信支付官方获取到预支付交易会话标识,并返回给前端,前端才能调起输入密码支付界面)


  
  1. import json
  2. import decimal
  3. import traceback
  4. import requests
  5. from django.http import HttpResponse
  6. def payment_view( request, *args, **kwargs):
  7. """
  8. 微信支付(小程序)
  9. :param request:
  10. :param args:
  11. :param kwargs:
  12. :return:
  13. """
  14. try:
  15. reqdata = json.loads(request.body)
  16. # 前端参数
  17. jscode = reqdata[ "jscode"] # 微信ID
  18. price = decimal.Decimal(reqdata[ "price"]).quantize(decimal.Decimal( "0.00")) # 充值金额,保留两位小数
  19. nickname = reqdata[ "nickname"] # 微信昵称/支付宝名称 前端获取到返给后端做记录,可要可不要的字段
  20. paymode = reqdata[ "paymode"] # 支付方式 1微信支付
  21. remark = reqdata[ "remark"] # 支付内容描述
  22. # 根据jscode 获取openID
  23. rets = requests.get(url = "https://api.weixin.qq.com/sns/jscode2session?" \
  24. "appid=%s&secret=%s&js_code=%s" \
  25. "&grant_type=authorization_code" % (appid,wx_secret, js_code), timeout= 3, verify= False)
  26. if not rets:
  27. return HttpResponse(general_error_msg(msg= "未获取到微信信息"))
  28. # 0.获取支付的微信openid
  29. print( f"组织ID:{userinfo['orgid']}, jscode:{jscode}")
  30. wxuser = getappopenid(orgid, jscode)
  31. if wxuser:
  32. # session_key = wxuser["session_key"]
  33. openid = wxuser[ "openid"]
  34. else:
  35. return HttpResponse(general_error_msg(msg= "未获取到微信用户信息"))
  36. # 1.以交易日期生成交易号
  37. orderno = order_num()
  38. # 2.生成新交易记录 paystatus 支付状态 1成功 0待支付 -1支付失败
  39. conorder.objects.create(orderno=orderno, openid=openid, openname=nickname,
  40. paymode=paymode,goodstotalprice=price, paystatus= 0,
  41. remark=remark,createtime=get_now_time( 1))
  42. # 3.生成统一下单的报文body
  43. url = WX_Pay_URL
  44. body = {
  45. "appid": appid,
  46. "mchid": mchid,
  47. "description": remark,
  48. "out_trade_no": orderno,
  49. "notify_url": WX_Notify_URL + "/pay/notify", # 后端接收回调通知的接口
  50. "amount": { "total": int(price * 100), "currency": "CNY"}, # 正式上线price要*100,微信金额单位为分(必须整型)。
  51. "payer": { "openid": openid},
  52. }
  53. data = json.dumps(body)
  54. headers, random_str, time_stamps = make_headers_v3(mchid, serial_num, data=data, method= 'POST')
  55. # 10.发送请求获得prepay_id
  56. try:
  57. response = requests.post(url, data=data, headers=headers) # 获取预支付交易会话标识(prepay_id)
  58. print( "预支付交易会话标识", response)
  59. if response.status_code == 200:
  60. wechatpay_serial, wechatpay_timestamp, wechatpay_nonce, wechatpay_signature, certificate, serial_no = check_wx_cert(
  61. response, mchid, pay_key, serial_num)
  62. # 11.9签名验证
  63. if wechatpay_serial == serial_no: # 应答签名中的序列号同证书序列号应相同
  64. print( 'serial_no match')
  65. try:
  66. data3 = f"{wechatpay_timestamp}\n{wechatpay_nonce}\n{response.text}\n"
  67. verify(data3, wechatpay_signature, certificate)
  68. print( 'The signature is valid.')
  69. # 12.生成调起支付API需要的参数并返回前端
  70. res = {
  71. 'orderno': orderno, # 订单号
  72. 'timeStamp': time_stamps,
  73. 'nonceStr': random_str,
  74. 'package': 'prepay_id=' + response.json()[ 'prepay_id'],
  75. 'signType': "RSA",
  76. 'paySign': get_sign( f"{appid}\n{time_stamps}\n{random_str}\n{'prepay_id=' + response.json()['prepay_id']}\n"),
  77. }
  78. return HttpResponse(success_msg(msg= "下单成功", total= 0, data=res))
  79. except Exception as e:
  80. log.error( f"证书序列号验签失败{e}, {traceback.format_exc()}")
  81. return HttpResponse(general_error_msg(msg= "下单失败"))
  82. else:
  83. log.error( f"证书序列号比对失败【请求头中证书序列号:{wechatpay_serial};本地存储证书序列号:{serial_no};】")
  84. return HttpResponse(general_error_msg(msg= "调起微信支付失败!"))
  85. else:
  86. log.error( f"获取预支付交易会话标识 接口报错【params:{data};headers:{headers};response:{response.text}】")
  87. return HttpResponse(general_error_msg(msg= "调起微信支付失败!"))
  88. except Exception as e:
  89. log.error( f"调用微信支付接口超时【params:{data};headers:{headers};】:{e},{traceback.format_exc()}")
  90. return HttpResponse(general_error_msg(msg= "微信支付超时!"))
  91. except Exception as e:
  92. log.error( f"微信支付接口报错:{e},{traceback.format_exc()}")
  93. return HttpResponse(general_error_msg(msg= "微信支付接口报错!"))

3、相关方法


  
  1. import base64
  2. import random
  3. import string
  4. import time
  5. import traceback
  6. from datetime import datetime
  7. import requests
  8. from BaseMethods.log import log
  9. from Crypto.PublicKey import RSA
  10. from Crypto.Signature import pkcs1_15
  11. from Cryptodome.Hash import SHA256
  12. from sqlalchemy.util import b64encode
  13. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  14. # 各包版本
  15. # django-ratelimit==3.0.1
  16. # SQLAlchemy~=1.4.44
  17. # pycryptodome==3.16.0
  18. # pycryptodomex==3.16.0
  19. # cryptography~=38.0.4
  20. # Django~=3.2.4
  21. # 获取唯一标识
  22. def get_uuid( utype=0):
  23. """
  24. 唯一码
  25. :param utype:
  26. :return:
  27. """
  28. if utype == 0:
  29. return uuid.uuid1()
  30. elif utype == 1:
  31. return str(uuid.uuid1())
  32. elif utype == 2:
  33. return str(uuid.uuid1(). hex)
  34. elif utype == 3:
  35. return str((uuid.uuid5(uuid.NAMESPACE_DNS, str(uuid.uuid1()) + str(random.random()))))
  36. # 获取当前时间
  37. def get_now_time( type=0):
  38. """
  39. :param type: 类型0-5
  40. :return: yyyy-mm-dd HH:MM:SS;y-m-d H:M:S.f;y-m-d;ymdHMS;y年m月d日h时M分S秒
  41. """
  42. if type == 0:
  43. return datetime.datetime.now()
  44. elif type == 1:
  45. return datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")
  46. elif type == 2:
  47. return datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S.%f")
  48. elif type == 3:
  49. return datetime.datetime.now().strftime( "%Y-%m-%d")
  50. elif type == 4:
  51. return datetime.datetime.now().strftime( "%Y%m%d%H%M%S")
  52. elif type == 5:
  53. locale.setlocale(locale.LC_CTYPE, 'chinese')
  54. timestr = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S")
  55. t = time.strptime(timestr, "%Y-%m-%d %H:%M:%S")
  56. result = (time.strftime( "%Y年%m月%d日%H时%M分%S秒", t))
  57. return result
  58. elif type == 6:
  59. return datetime.datetime.now().strftime( "%Y%m%d")
  60. # 重构系统jargon类,用于处理时间格式报错问题
  61. class DateEncoder(json.JSONEncoder):
  62. def default( self, obj):
  63. if isinstance(obj, datetime.datetime):
  64. return obj.strftime( '%Y-%m-%d %H:%M:%S')
  65. elif isinstance(obj, datetime.date):
  66. return obj.strftime( "%Y-%m-%d")
  67. elif isinstance(obj, Decimal):
  68. return float(obj)
  69. elif isinstance(obj, bytes):
  70. return str(obj, encoding= 'utf-8')
  71. elif isinstance(obj, uuid.UUID):
  72. return str(obj)
  73. elif isinstance(obj, datetime.time):
  74. return obj.strftime( '%H:%M')
  75. elif isinstance(obj, datetime.timedelta):
  76. return str(obj)
  77. else:
  78. return json.JSONEncoder.default(self, obj)
  79. def decrypt( nonce, ciphertext, associated_data, pay_key):
  80. """
  81. AES解密
  82. :param nonce:
  83. :param ciphertext:
  84. :param associated_data:
  85. :param pay_key:
  86. :return:
  87. """
  88. key = pay_key
  89. key_bytes = str.encode(key)
  90. nonce_bytes = str.encode(nonce)
  91. ad_bytes = str.encode(associated_data)
  92. data = base64.b64decode(ciphertext)
  93. aesgcm = AESGCM(key_bytes)
  94. return aesgcm.decrypt(nonce_bytes, data, ad_bytes)
  95. def order_num():
  96. """
  97. 生成订单号
  98. :return:
  99. """
  100. # 下单时间的年月日毫秒12+随机数8位
  101. now_time = datetime.now()
  102. result = str(now_time.year) + str(now_time.month) + str(now_time.day) + str(now_time.microsecond) + str(
  103. random.randrange( 10000000, 99999999))
  104. return result
  105. def get_sign( sign_str):
  106. """
  107. 定义生成签名的函数
  108. :param sign_str:
  109. :return:
  110. """
  111. try:
  112. with open( r'static/cret/apiclient_key.pem') as f:
  113. private_key = f.read()
  114. rsa_key = RSA.importKey(private_key)
  115. signer = pkcs1_15.new(rsa_key)
  116. digest = SHA256.new(sign_str.encode( 'utf-8'))
  117. # sign = b64encode(signer.sign(digest)).decode('utf-8')
  118. sign = b64encode(signer.sign(digest))
  119. return sign
  120. except Exception as e:
  121. log.error( "生成签名的函数方法报错【func:get_sign;sign_str:%s】:%s ==> %s" % (sign_str, e, traceback.format_exc()))
  122. def check_wx_cert( response, mchid, pay_key, serial_no):
  123. """
  124. 微信平台证书
  125. :param response: 请求微信支付平台所对应的的接口返回的响应值
  126. :param mchid: 商户号
  127. :param pay_key: 商户号秘钥
  128. :param serial_no: 证书序列号
  129. :return:
  130. """
  131. wechatpay_serial, wechatpay_timestamp, wechatpay_nonce, wechatpay_signature, certificate = None, None, None, None, None
  132. try:
  133. # 11.应答签名验证
  134. wechatpay_serial = response.headers[ 'Wechatpay-Serial'] # 获取HTTP头部中包括回调报文的证书序列号
  135. wechatpay_signature = response.headers[ 'Wechatpay-Signature'] # 获取HTTP头部中包括回调报文的签名
  136. wechatpay_timestamp = response.headers[ 'Wechatpay-Timestamp'] # 获取HTTP头部中包括回调报文的时间戳
  137. wechatpay_nonce = response.headers[ 'Wechatpay-Nonce'] # 获取HTTP头部中包括回调报文的随机串
  138. # 11.1.获取微信平台证书 (等于又把前面的跑一遍,实际上应是获得一次证书就存起来,不用每次都重新获取一次)
  139. url2 = "https://api.mch.weixin.qq.com/v3/certificates"
  140. # 11.2.生成证书请求随机串
  141. random_str2 = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range( 32))
  142. # 11.3.生成证书请求时间戳
  143. time_stamps2 = str( int(time.time()))
  144. # 11.4.生成请求证书的签名串
  145. data2 = ""
  146. sign_str2 = f"GET\n{'/v3/certificates'}\n{time_stamps2}\n{random_str2}\n{data2}\n"
  147. # 11.5.生成签名
  148. sign2 = get_sign(sign_str2)
  149. # 11.6.生成HTTP请求头
  150. headers2 = {
  151. "Content-Type": "application/json",
  152. "Accept": "application/json",
  153. "Authorization": 'WECHATPAY2-SHA256-RSA2048 '
  154. + f'mchid="{mchid}",nonce_str="{random_str2}",signature="{sign2}",timestamp="{time_stamps2}",serial_no="{serial_no}"'
  155. }
  156. # 11.7.发送请求获得证书
  157. response2 = requests.get(url2, headers=headers2) # 只需要请求头
  158. cert = response2.json()
  159. # 11.8.证书解密
  160. nonce = cert[ "data"][ 0][ 'encrypt_certificate'][ 'nonce']
  161. ciphertext = cert[ "data"][ 0][ 'encrypt_certificate'][ 'ciphertext']
  162. associated_data = cert[ "data"][ 0][ 'encrypt_certificate'][ 'associated_data']
  163. serial_no = cert[ "data"][ 0][ 'serial_no']
  164. certificate = decrypt(nonce, ciphertext, associated_data, pay_key)
  165. except Exception as e:
  166. log.error( f"微信平台证书验证报错:{e}{traceback.format_exc()}")
  167. return wechatpay_serial, wechatpay_timestamp, wechatpay_nonce, wechatpay_signature, certificate, serial_no
  168. def verify( check_data, signature, certificate):
  169. """
  170. 验签函数
  171. :param check_data:
  172. :param signature:
  173. :param certificate:
  174. :return:
  175. """
  176. key = RSA.importKey(certificate) # 这里直接用了解密后的证书,但没有去导出公钥,似乎也是可以的。怎么导公钥还没搞懂。
  177. verifier = pkcs1_15.new(key)
  178. hash_obj = SHA256.new(check_data.encode( 'utf8'))
  179. return verifier.verify(hash_obj, base64.b64decode(signature))
  180. def make_headers_v3( mchid, serial_num, data='', method='GET'):
  181. """
  182. 定义微信支付请求接口中请求头认证
  183. :param mchid: 商户ID
  184. :param serial_num: 证书序列号
  185. :param data: 请求体内容
  186. :param method: 请求方法
  187. :return: headers(请求头)
  188. """
  189. # 4.定义生成签名的函数 get_sign(sign_str)
  190. # 5.生成请求随机串
  191. random_str = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range( 32))
  192. # 6.生成请求时间戳
  193. time_stamps = str( int(time.time()))
  194. # 7.生成签名串
  195. sign_str = f"{method}\n{'/v3/pay/transactions/jsapi'}\n{time_stamps}\n{random_str}\n{data}\n"
  196. # 8.生成签名
  197. sign = get_sign(sign_str)
  198. # 9.生成HTTP请求头
  199. headers = {
  200. 'Content-Type': 'application/json',
  201. 'Authorization': 'WECHATPAY2-SHA256-RSA2048 '
  202. + f'mchid="{mchid}",nonce_str="{random_str}",signature="{sign}",timestamp="{time_stamps}",serial_no="{serial_num}"'
  203. }
  204. return headers, random_str, time_stamps

4、微信回调


  
  1. import decimal
  2. import json
  3. import traceback
  4. from django.http import HttpResponse
  5. def notify_view( request, *args, **kwargs):
  6. """
  7. 支付完成之后的通知(微信官方返回的数据)
  8. :param request:
  9. :param args:
  10. :param kwargs:
  11. :return:
  12. """
  13. try:
  14. # 1.获得支付通知的参数
  15. body = request.body
  16. data = bytes.decode(body, 'utf-8')
  17. newdata = json.loads(data)
  18. # newdata = {
  19. # "id": "9d40acfd-13cb-5175-a5aa-6c421f794952",
  20. # "create_time": "2023-01-06T15:12:49+08:00",
  21. # "resource_type": "encrypt-resource",
  22. # "event_type": "TRANSACTION.SUCCESS",
  23. # "summary": "\xe6\x94\xaf\xe4\xbb\x98\xe6\x88\x90\xe5\x8a\x9f",
  24. # "resource": {
  25. # "original_type":
  26. # "transaction",
  27. # "algorithm": "AEAD_AES_256_GCM",
  28. # "ciphertext": "UF5gLXfe8qBv9qxQsf+/Mb6as+vbIhUS8Dm25qGIJIIdXTorUUjqZH1+"
  29. # "jMQxkxma/Gn9bOxeAoQWPEuIoJ2pB328Iv90jmHTrouoP3L60mjNgGJS8d3H8i1zAPBXCpP4mgvgRANWsw4pAWj1lFM5BZr4aP+"
  30. # "pNMc5TdwreGBG3rO9sbCLXsSRfW8pVZ7IfPnhPDTOWP3P1k5ikHedcRt4/HP69oDBEe5RSsD93wO/"
  31. # "lrIwycStVHyecBaliwpVMRnNnRCXqhlalNJ3NJ6jcgy32fP1J+L90ntwGyqMmZUS71P5TN1H0iH5rXNpRY9IF3pvN+"
  32. # "lei5IS86wEoVXkmEsPcJrHaabn7rghxuZoqwuauMIiMwBLllnEmgXfAbJA4FJy+"
  33. # "OLhZPrMWMkkiNCLcL069QlvhLXYi/0V9PQVTnvtA5RLarj26s4WSqTZ2I5VGHbTqSIZvZYK3F275KEbQsemYETl18xwZ+"
  34. # "WAuSrYaSKN/pKykK37vUGtT3FeIoJup2c6M8Ghull3OcVmqCOsgvU7/pNjl1rLKEJB6t/X9avcHv+feikwQBtBmd/b2qCeSrEpM7US",
  35. # "associated_data": "transaction",
  36. # "nonce": "cKEdw8eV9Bh0"
  37. # }
  38. # }
  39. nonce = newdata[ 'resource'][ 'nonce']
  40. ciphertext = newdata[ 'resource'][ 'ciphertext']
  41. associated_data = newdata[ 'resource'][ 'associated_data']
  42. try:
  43. payment = decrypt(nonce, ciphertext, associated_data, pay_key)
  44. break
  45. except Exception as e:
  46. print(e)
  47. if not payment:
  48. return HttpResponse({ "code": "FAIL", "message": "失败"}, status= 400)
  49. payment = eval(payment.decode( 'utf-8'))
  50. # payment = {
  51. # "mchid": "xxxx",
  52. # "appid": "xxxx",
  53. # "out_trade_no": "20231654836163523608",
  54. # "transaction_id": "4200001646202301065425000524",
  55. # "trade_type": "JSAPI",
  56. # "trade_state": "SUCCESS",
  57. # "trade_state_desc": "\xe6\x94\xaf\xe4\xbb\x98\xe6\x88\x90\xe5\x8a\x9f",
  58. # "bank_type": "OTHERS",
  59. # "attach": "",
  60. # "success_time": "2023-01-06T15:12:49+08:00",
  61. # "payer": {
  62. # "openid": "xxxxx"
  63. # },
  64. # "amount": {
  65. # "total": 1,
  66. # "payer_total": 1,
  67. # "currency": "CNY",
  68. # "payer_currency": "CNY"
  69. # }
  70. # }
  71. orderno = payment[ 'out_trade_no']
  72. zf_status = True if payment[ "trade_type"] == "SUCCESS" else False
  73. if zf_status:
  74. money = decimal.Decimal( int(payment[ "amount"][ "payer_total"]) / 100).quantize(decimal.Decimal( "0.00"))
  75. else:
  76. money = decimal.Decimal( 0.0).quantize(decimal.Decimal( "0.00"))
  77. # 7.回调报文签名验证
  78. # 同第一篇签名验证的代码
  79. wechatpay_serial, wechatpay_timestamp, wechatpay_nonce, wechatpay_signature, certificate = check_wx_cert(request, mchid, pay_key, serial_num)
  80. if wechatpay_serial == serial_num: # 应答签名中的序列号同证书序列号应相同
  81. # 8.获得回调报文中交易号后修改已支付订单状态
  82. res = conorder.objects. filter(orderno=orderno, paystatus=- 1).first()
  83. if res:
  84. res.paystatus = 1
  85. res.save()
  86. else:
  87. res.paystatus = - 1
  88. res.save()
  89. # 9.项目业务逻辑
  90. return HttpResponse({ "code": "SUCCESS", "message": "成功"})
  91. else:
  92. log.error( f"证书序列号比对失败【请求头中证书序列号:{wechatpay_serial};本地存储证书序列号:{serial_num};】")
  93. return HttpResponse({ "code": "FAIL", "message": "失败"}, status= 400)
  94. except Exception as e:
  95. log.error( f"微信回调接口报错:{e},{traceback.format_exc()}")
  96. return HttpResponse({ "code": "FAIL", "message": "失败"}, status= 400)

5、借鉴地址:

        在此非常感谢博主,文章链接如下:一文基本搞定python的django框架下微信支付v3的主要流程-1 - 知乎​​​​​​从去年底开始,下决心自己写代码来搞定自已策划的微信小程序” 来推鉴--投融资项目推荐服务平台“后,微信支付就成为挡在前面的一座大山。毕竟是从一个从没开发过一个程序的基本零基础,到要真正上线一个能商业运…https://zhuanlan.zhihu.com/p/402449405

6、请注意:

        以上代码仅供参考,如若直接商用出现任何后果请自行承担,本人概不负责。 


转载:https://blog.csdn.net/qq_42142258/article/details/128653725
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场