微信小程序支付接口之Django后台
本文链接:https://blog.csdn.net/qq_41860162/article/details/89098694
Python3-django-微信小程序支付接口调用
工具类生成一系列微信官方文档需要的数据
import hashlib
import datetime
import xml.etree.ElementTree as ET #商户平台上设置、查询
Mch_id="商户Id"
client_appid="微信小程序APPId"
Mch_key="支付交易秘钥" # 生成签名的函数
def paysign(appid, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee):
ret = {
"appid": appid,
"body": body,
"mch_id": mch_id,
"nonce_str": nonce_str,
"notify_url": notify_url,
"openid": openid,
"out_trade_no": out_trade_no,
"spbill_create_ip": spbill_create_ip,
"total_fee": total_fee,
"trade_type": 'JSAPI'
} # 处理函数,对参数按照key=value的格式,并按照参数名ASCII字典序排序
stringA = '&'.join(["{0}={1}".format(k, ret.get(k)) for k in sorted(ret)])
stringSignTemp = '{0}&key={1}'.format(stringA, Mch_key)
sign = hashlib.md5(stringSignTemp.encode("utf-8")).hexdigest()
return sign.upper() # 生成随机字符串
def getNonceStr():
import random
data = "123456789zxcvbnmasdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP"
nonce_str = ''.join(random.sample(data, 30))
return nonce_str # 生成商品订单号
def getWxPayOrdrID():
date = datetime.datetime.now()
# 根据当前系统时间来生成商品订单号。时间精确到微秒
payOrdrID = date.strftime("%Y%m%d%H%M%S%f") return payOrdrID # 获取全部参数信息,封装成xml
def get_bodyData(openid, client_ip, price):
body = 'Mytest' # 商品描述
notify_url = 'https://127.0.0.1:8000/payOrder/' # 支付成功的回调地址 可访问 不带参数
nonce_str = getNonceStr() # 随机字符串
out_trade_no = getWxPayOrdrID() # 商户订单号
total_fee = str(price) # 订单价格 单位是 分 # 获取签名
sign = paysign(client_appid, body, Mch_id, nonce_str, notify_url, openid, out_trade_no, client_ip, total_fee) bodyData = '<xml>'
bodyData += '<appid>' + client_appid + '</appid>' # 小程序ID
bodyData += '<body>' + body + '</body>' # 商品描述
bodyData += '<mch_id>' + Mch_id + '</mch_id>' # 商户号
bodyData += '<nonce_str>' + nonce_str + '</nonce_str>' # 随机字符串
bodyData += '<notify_url>' + notify_url + '</notify_url>' # 支付成功的回调地址
bodyData += '<openid>' + openid + '</openid>' # 用户标识
bodyData += '<out_trade_no>' + out_trade_no + '</out_trade_no>' # 商户订单号
bodyData += '<spbill_create_ip>' + client_ip + '</spbill_create_ip>' # 客户端终端IP
bodyData += '<total_fee>' + total_fee + '</total_fee>' # 总金额 单位为分
bodyData += '<trade_type>JSAPI</trade_type>' # 交易类型 小程序取值如下:JSAPI
bodyData += '<sign>' + sign + '</sign>'
bodyData += '</xml>' return bodyData def xml_to_dict(xml_data):
'''
xml to dict
:param xml_data:
:return:
'''
xml_dict = {}
root = ET.fromstring(xml_data)
for child in root:
xml_dict[child.tag] = child.text
return xml_dict def dict_to_xml(dict_data):
'''
dict to xml
:param dict_data:
:return:
'''
xml = ["<xml>"]
for k, v in dict_data.iteritems():
xml.append("<{0}>{1}</{0}>".format(k, v))
xml.append("</xml>")
return "".join(xml) # 获取返回给小程序的paySign
def get_paysign(prepay_id, timeStamp, nonceStr):
pay_data = {
'appId': client_appid,
'nonceStr': nonceStr,
'package': "prepay_id=" + prepay_id,
'signType': 'MD5',
'timeStamp': timeStamp
}
stringA = '&'.join(["{0}={1}".format(k, pay_data.get(k)) for k in sorted(pay_data)])
stringSignTemp = '{0}&key={1}'.format(stringA, Mch_key)
sign = hashlib.md5(stringSignTemp.encode("utf-8")).hexdigest()
return sign.upper()
后台调用工具类来发起
def getOrder(request)
if request.method == 'POST':
#获取用户
user_id=request.POST.get('userid')
# 获取价格
print(request.get_host())
price = request.POST.get('price')
print(price) # 获取客户端ip
client_ip, port = request.get_host().split(":") # 获取小程序openid
cur=connection.cursor()
sql="select openid from users where id=%s" %(user_id)
print(sql)
cur.execute(sql)
openid = cur.fetchall()[0][0]
print(openid) # 请求微信的url
url = "https://api.mch.weixin.qq.com/pay/unifiedorder" # 拿到封装好的xml数据
body_data = pay.get_bodyData(openid, client_ip, price)
print()
# 获取时间戳
timeStamp = str(int(time.time())) # 请求微信接口下单
respone = requests.post(url, body_data.encode("utf-8"), headers={'Content-Type': 'application/xml'})
# 回复数据为xml,将其转为字典
content = pay.xml_to_dict(respone.content)
print(content) if content["return_code"] == 'SUCCESS':
# 获取预支付交易会话标识
prepay_id = content.get("prepay_id")
# 获取随机字符串
nonceStr = content.get("nonce_str") # 获取paySign签名,这个需要我们根据拿到的prepay_id和nonceStr进行计算签名
paySign = pay.get_paysign(prepay_id, timeStamp, nonceStr) # 封装返回给前端的数据
data = {"prepay_id": prepay_id, "nonceStr": nonceStr, "paySign": paySign, "timeStamp": timeStamp} return ht(dumps(data)) else:
return ht("请求支付失败")
else:
return ht("error")
微信小程序前端请求自己写的pay接口成功后调用wx.requestPayment接口成功发起支付请求
pay:function(){
var self = this
wx.request({
url: app.data.url + '/pay',
data: {
userid: app.data.user.id,
price: 1
//parseInt(self.data.totalprice)*100 // 这里修改价格
},
method: "POST",
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function (res) {
console.log(res)
if (true) {
var payModel = res.data;
wx.requestPayment({
'timeStamp': payModel.timeStamp,
'nonceStr': payModel.nonceStr,
'package': "prepay_id=" + payModel.prepay_id,
'signType': 'MD5',
'paySign': payModel.paySign,
'success': function (res) {
console.log("asdsasdasdasd",res)
wx.showToast({
title: '支付成功',
icon: 'success',
duration: 1500,
success: function () {
setTimeout(function () {
wx.switchTab({
url: '/pages/list/list',
})
}, 1500);
}
})
//上传订单
var uplist = []
console.log("lalal", uplist)
console.log("订单信息", self.data.list)
for (var i = 0; i < self.data.list.length; i++) {
uplist.push({
"userid": app.data.user.id,
"goodid": self.data.list[i].id,
"addressid": self.data.address.id,
"number": self.data.list[i].count,
"totalPrice": self.data.list[i].total_price,
"date": self.data.date
})
wx.request({
url: app.data.url + '/shopping/insertRecord',
method: "POST",
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: uplist[i],
success: function () {
console.log('好了一个');
}
})
console.log("上传订单", uplist)
}
},
'fail': function (res) {
}
})
} },
fail: function () {
},
complete: function () { }
})
}
微信小程序支付接口之Django后台的更多相关文章
- 微信小程序支付源码,后台服务端代码
作者:尹华南,来自原文地址 微信小程序支付绕坑指南 步骤 A:小程序向服务端发送商品详情.金额.openid B:服务端向微信统一下单 C:服务器收到返回信息二次签名发回给小程序 D:小程序发起支付 ...
- php 微信小程序支付
php 微信小程序支付 直接贴代码: 前端测试按钮wxml: <view class="container"> <text class="name&qu ...
- 【原创】微信小程序支付java后台案例(公众号支付同适用)(签名错误问题)
前言 1.微信小程序支付官方接口文档:[点击查看微信开放平台api开发文档]2.遇到的坑:预支付统一下单签名结果返回[签名错误]失败,建议用官方[签名验证工具]检查签名是否存在问题.3.遇到的坑:签名 ...
- .Net后台实现微信小程序支付
最近一直再研究微信支付和支付宝支付,官方支付文档中一直在讲与第三方支付打交道的原理,却没有介绍我们自己项目中的APP与后台该怎么交互(哈哈,人家也没必要介绍这一块).拜读了官方文档和前辈们的佳作,自己 ...
- 微信小程序支付及退款流程详解
微信小程序的支付和退款流程 近期在做微信小程序时,涉及到了小程序的支付和退款流程,所以也大概的将这方面的东西看了一个遍,就在这篇博客里总结一下. 首先说明一下,微信小程序支付的主要逻辑集中在后端,前端 ...
- 微信小程序支付接入注意点
一.微信支付后台服务器部署 服务器采用ubuntu16.04 + php7.0 + apache2.0. 微信支付后台服务使用了curl 和 samplexml ,因此php.ini配置中必须开启这两 ...
- .NET Core 微信小程序支付——(统一下单)
最近公司研发了几个电商小程序,还有一个核心的电商直播,只要是电商一般都会涉及到交易信息,离不开支付系统,这里我们统一实现小程序的支付流程(与服务号实现步骤一样). 目录1.开通小程序的支付能力2.商户 ...
- Java实现微信小程序支付(完整版)
在开发微信小程序支付的功能前,我们先熟悉下微信小程序支付的业务流程图: 不熟悉流程的建议还是仔细阅读微信官方的开发者文档. 一,准备工作 事先需要申请企业版小程序,并开通“微信支付”(即商户功能).并 ...
- Asp.net Core 微信小程序支付
最近要做一个微信小程序支付的功能 在网上找了一下 .net Core做微信支付的博客 和 demo 几乎没有 自己研究了好几天 参考了 很多 大牛的博客 勉强做出来了 因为参数都没有 比如 opid ...
随机推荐
- S5PV210 固件烧写 u-boot烧写
首先阅读CW210_CD自带光盘中CW210 开发板使用手册.pdf 使用usb 拨码开关置成usb启动.xx可以是ON或OFF.开发板上面也有丝印提示 usb线接好,串口线接好 使用DNW下载 自带 ...
- BBC评出的100本最具影响力经典书籍
今年,英国广播公司(BBC)邀请全球35个国家共108名文化人士,参与其发起的“影响思维和历史的100部虚构故事”的推荐,要求每人最多提名 5 部作品,这些作品最终将根据提名总量排名. 该活动经过一个 ...
- 关于SQL优化
建立索引常用的规则 表的主键.外键必须有索引: 数据量超过300的表应该有索引: 经常与其他表进行连接的表,在连接字段上应该建立索引: 经常出现在Where子句中的字段,特别是大表的字段,应该建立索引 ...
- SAMBA 服务配置
Samba文件共享服务 Linux系统中一种文件共享程序 在Windows网络环境中,主机之间进行文件和打印机共享是通过微软公司自己的SMB/CIFS网络协议实现的.SMB(Server Messag ...
- Vagrant+VirtualBox虚拟环境
Vagrant+VirtualBox虚拟环境 VagrantVirtualBox 软件安装 虚拟机基础配置 虚拟机创建 共享目录 配置网络 配置私有网络 配置公有网络 打包box与添加box 打包bo ...
- SpringCloud2.0 Hystrix Ribbon 基于Ribbon实现断路器
原文:https://www.cnblogs.com/songlu/p/9949203.html 1.启动[服务中心]集群,工程名:springcloud-eureka-server 参考 Sprin ...
- 【转】如何在 Linux 中查看可用的网络接口
原文:https://www.cnblogs.com/qianpangzi/p/10563979.html 查看ubuntu系统当前的可用的网络接口.方法如下 -------------------- ...
- 缺jar包异常:java.lang.NoClassDefFoundError: org/springframework/core/convert/support/PropertyTypeDescriptor
严重: StandardWrapper.Throwable java.lang.NoClassDefFoundError: org/springframework/core/convert/suppo ...
- selenium入门知识
自动化测试 重复测试.性能测试.压力测试 快速.可靠.可重复.可程序化.广泛的 自动化测试适合场合 回归测试.更多更频繁的测试.手工测试无法实现的工作.跨平台产品的测试.重复性很强的操作 不适合场合 ...
- Centos7-bond模式介绍
bond模式: Mode=0(balance-rr)表示负载分担round-robin Mode=1(active-backup)表示主备模式,只有一块网卡是active,另外一块是备的standby ...