微信小程序支付demo,后端使用python

开发环境 {}

尝试从零开始用python写游戏外挂!

  • win10
  • python 2.7.13 (64位)
  • Flask (0.12.2)

线上环境

  • CentOS 6.5
  • python 2.7.13 (64位)
  • Flask (0.12.2)

一: 编写后端程序

  1. 查看统一下单接口,这里有两个地方要注意的。a.在小程序中用户标识(openid)这个参数是必要,因为trade_type=JSAPI; b.签名(sign)
  2. 生成签名(sign)
  3. a. 设置要签名的参数(注意:要加入openid, 否则会导致签名错误)
data = {
 'appid': appid,
 'mch_id': mch_id,
 'nonce_str': get_nonce_str(),
 'body': '测试', # 商品描述
 'out_trade_no': str(int(time.time())), # 商户订单号
 'total_fee': '1',
 'spbill_create_ip': spbill_create_ip,
 'notify_url': notify_url,
 'attach': '{"msg": "自定义数据"}',
 'trade_type': trade_type,
 'openid': '1111111111111111111111'
 }

b. 按照指定的格式排序,拼接商户key,然后生成md5

stringA = '&'.join(["{0}={1}".format(k, pay_data.get(k))for k in sorted(pay_data)])
stringSignTemp = '{0}&key={1}'.format(stringA, self.merchant_key)
sign = hashlib.md5(stringSignTemp).hexdigest()

c. 签名校验工具(如果看不到调试工具请更换浏览器内核)

  1. 获取prepay_id
  2. a. 在上面的data中加入上面生成的md5
data['sign'] = md5

b. 把data字典转换成xml, 然后通过post方式提交

req = urllib2.Request(url, data, headers={'Content-Type': 'application/xml'})
result = urllib2.urlopen(req, timeout=timeout).read()

c. 得到prepay_id

  1. 生成wx.requestPayment小程序中的paySign签名 paySign说明文档

a. 生成参数, 这里要注意package参数是prepay_id=prepay_id

paySign_data = {
 'appId': appId,
 'timeStamp': timeStamp,
 'nonceStr': nonceStr,
 'package': 'prepay_id={0}'.format(prepay_id),
 'signType': 'MD5'
 }

b.参考生成签名步骤,注意:这里也要拼接商户key

5.返回wx.requestPayment小程序接口所需参数

6.支付回调通知

a. 微信会以post方式通知服务器,数据类型为xml

b.收到通知后应先对数据进行校验,然后返回信息给微信, 注意:这里要以xml方式返回数据

'return_code': 'SUCCESS',
'return_msg': 'OK'

二:编写小程序

1.新建一个快速项目

2.没有什么难的,直接上代码,通过上面的接口返回小程序所需的参数(提醒:支付接口可以本地测试)

 wx.request({
 url: 'http://127.0.0.1:5000/wxpay/pay',
 header: {
 'content-type': 'application/json'
 },
 success: function (res) {
 wx.requestPayment({
 timeStamp: res.data.timeStamp,
 nonceStr: res.data.nonceStr,
 package: res.data.package,
 signType: res.data.signType,
 paySign: res.data.paySign,
 'success': function (res) {
 console.log(res)
 },
 'fail': function (res) {
 console.log(res)
 }
 })
 }
 })

猜你喜欢

转载自blog.csdn.net/weixin_44138053/article/details/88235866