微信小程序支付接口之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 ...
随机推荐
- DataPipeline丨构建实时数据集成平台时,在技术选型上的考量点
文 | 陈肃 DataPipeline CTO 随着企业应用复杂性的上升和微服务架构的流行,数据正变得越来越以应用为中心. 服务之间仅在必要时以接口或者消息队列方式进行数据交互,从而避免了构建单一数 ...
- idea2018破解
准备:ideaIU-2018.1.4.exe 安装程序 JetbrainsCrack-2.10-release-enc.jar 破解jar包 第一步:打开安装目录/bin,找到idea.exe.vmo ...
- pandas 之 索引重塑
import numpy as np import pandas as pd There are a number of basic operations for rearanging tabular ...
- Python装饰器与闭包
闭包是Python装饰器的基础.要理解闭包,先要了解Python中的变量作用域规则. 变量作用域规则 首先,在函数中是能访问全局变量的: >>> a = 'global var' & ...
- find 和grep的区别
find(以文件属性为查找条件) grep(以文件内容为查找条件) grep works /usr/local/apache/htdocs/index.html 1.将/etc/passwd,有出现 ...
- Tensorflow简单实践系列(三):图和会话
当执行一个 TensorFlow 函数的时候,并不会马上执行运算,而是把运算存储到一个称为“图”(graph)的数据结构里面. 图存储的各种运算,只有在会话(session)里执行图,才会真正地执行. ...
- 项目Beta冲刺 用户试用报告
课程: 软件工程1916|W(福州大学) 作业要求: 项目Beta冲刺 团队名称: 火鸡堂 作业目标: 火鸡堂 队员学号 队员姓名 博客地址 备注 221600111 彼术向 http://www.c ...
- 网页禁止右键,禁止F12,禁止选中,禁止复制,禁止缓存等操作
一.禁止右键 //方法一 document.onmousedown = function () { ) { return false; } } //方法二 document.oncontextmenu ...
- PHP数组操作类
class ArrayHelper{ /** * 从数组中删除空白的元素(包括只有空白字符的元素) * * 用法: * @code php ...
- UI系统的作用
1.向用户展示信息: 2.将用于与系统的交互解释为指令.