转自:https://www.cnblogs.com/zzqit/p/9952302.html#_label3
之前写的功能,回头复习一下,做个笔记
想实现这个功能,微信小程序端方法是:
wx.requestPayment( { ‘timeStamp‘: res.data.data["timeStamp"], ‘nonceStr‘: res.data.data["nonceStr"], ‘package‘: res.data.data["package"], ‘signType‘: ‘MD5‘, ‘paySign‘: res.data.data["paySign"], ‘success‘: function (res) { if (res.errMsg == "requestPayment:ok") { wx.showToast({ title: ‘支付成功‘, icon: ‘success‘, duration: 1000 }) } }, ‘fail‘: function (res) { }, ‘complete‘: function (res) { } })
在调用wx.requestPayment方法之前呢,我们需要准备res.data.data里提供的数据,也就是后台传过来的数据
后台生成这些数据只需要小程序提供用户的openid就可以了
后台生成数据的代码:
def wechat_pay(): goods_price = request.args.get("price") openid = g.current_user.get("openId") appid = "" #小程序appid,小程序-开发-开发设置里找 mch_id = "" #微信支付商户号,微信支付|商户平台-账户中心-商户信息里找 api_key = "" #API秘钥,微信支付|商户平台-账户中心-API安全里找 notify_url = "" #支付成功回调路径 orderid = datetime.datetime.now().strftime(‘%Y%m%d%H%M%S‘) #已时间为订单号 info = WX_PayToolUtil(appid, mch_id, api_key, notify_url) data = info.getPayUrl(orderid, openid, goods_price) return json_response(0, data=data)
WX_PayToolUtil方法:
# coding=utf-8 import requests import hashlib import xmltodict import time import random import string from random import Random class WX_PayToolUtil(): """ 微信支付工具 """ def __init__(self, APP_ID, MCH_ID, API_KEY, NOTIFY_URL): self._APP_ID = APP_ID # 小程序ID self._MCH_ID = MCH_ID # # 商户号 self._API_KEY = API_KEY # 商户秘钥 self._UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder" # 接口链接 self._NOTIFY_URL = NOTIFY_URL # 异步通知 def generate_sign(self, param): ‘‘‘生成签名‘‘‘ stringA = ‘‘ ks = sorted(param.keys())# 参数按键值排序 for k in ks: stringA += (k + ‘=‘ + param[k] + ‘&‘) # 拼接商户KEY stringSignTemp = stringA + "key=" + self._API_KEY # md5加密,也可以用其他方式 hash_md5 = hashlib.md5(stringSignTemp.encode(‘utf8‘)) sign = hash_md5.hexdigest().upper() return sign def random_str(self): """ 生成随机字符串 :param randomlength: 字符串长度 :return: """ strs = ‘‘ chars = ‘AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789‘ length = len(chars) - 1 random = Random() for i in range(0, 30): strs += chars[random.randint(0, length)] return strs def getPayUrl(self, orderid, openid, goodsPrice, **kwargs): """向微信支付端发出请求,获取url""" key = self._API_KEY nonce_str = self.random_str()# 生成随机字符串,小于32位 params = { ‘appid‘: self._APP_ID, # 小程序ID ‘mch_id‘: self._MCH_ID, # 商户号 ‘nonce_str‘: nonce_str, # 随机字符串 "body": ‘learning card‘, # 支付说明 ‘out_trade_no‘: orderid, # 生成的订单号 ‘total_fee‘: str(goodsPrice), # 标价金额 ‘spbill_create_ip‘: "", # 终端IP,你服务器IP ‘notify_url‘: self._NOTIFY_URL, ‘trade_type‘: "JSAPI", # 支付类型 "openid": openid, # 用户id } # 生成签名 params[‘sign‘] = self.generate_sign(params) param = {‘root‘: params} xml = xmltodict.unparse(param) response = requests.post(self._UFDODER_URL, data=xml.encode(‘utf-8‘), headers={‘Content-Type‘: ‘text/xml‘}) # xml 2 dict msg = response.text xmlmsg = xmltodict.parse(msg) # 4. 获取prepay_id if xmlmsg[‘xml‘][‘return_code‘] == ‘SUCCESS‘: prepay_id = xmlmsg[‘xml‘][‘prepay_id‘] # 时间戳 timeStamp = str(int(time.time())) # 5. 五个参数 data = { "appId": self._APP_ID, "nonceStr": nonce_str, "package": "prepay_id=" + prepay_id, "signType": ‘MD5‘, "timeStamp": timeStamp, } # 6. paySign签名 paySign = self.generate_sign(data) data["paySign"] = paySign # 加入签名 # 7. 传给前端的签名后的参数 return data
将生成的数据响应给小程序再调用开头的wx.requestPayment即可
调用前别忘了把微信商户号关联到微信小程序,小程序公众平台微信支付中关联商户号
微信开发文档,字段的具体含义去里面找:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1