微信h5支付python版

最近闲暇,整理下微信支付,根据官方文档进行的。
官方配置文件这里就不多说了,

tornado感觉方便快捷,所以就用这个整理处理一份。经由django改编。
文档结构

进入、处理、回调需要配置3个url就能搞定了。

0、导包

import hashlib
import uuid
import re
from tornado.httpserver import HTTPServer
import tornado.web
from tornado.ioloop import IOLoop
import os
import requests
from urllib import request as reqt
from tornado.options import define, parse_command_line, options
from tornado.web import Application# md5
def get_token(md5str):m1 = hashlib.md5()m1.update(md5str.encode("utf-8"))token = m1.hexdigest()return token

1、进入r'/index', indexHandler),

class indexHandler(tornado.web.RequestHandler):def get(self):self.render("index.html")

index.html

<!DOCTYPE HTML>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>微信Demo</title></head><body><script type="text/javascript">//用户点击跳转地址(非静默授权) 参数appid为公众号的id redirect_uri为微信回调接口 state为可携带的参数// window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6ce0cd5c2d7b1299&redirect_uri=http://wanyou.abc6.net:22708/index2/mainServlet&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";window.location.href="/Notify_wx";</script></body>
</html>

2.处理 /Notify_wx
需要准备的有,

        mch_id bodykey host

body 要和index.html中title一值,我就在这里浪费了大半天。
金额等可以在index自行传参,后台处理

class Notify_wxHandler(tornado.web.RequestHandler):def get(self):total_fee = "20"# 金额appid = 'appid'mch_id = 'mch_id'body = "微信Demo"key = ''host = "域名 "# 微信填写的备案域名nonce_str = str(uuid.uuid4()).replace('-', "")[:-3]# 生成随机字符串notify_url = 'http://{}/Notify_URL'.format(host)# 回调函数wap_name = '腾讯充值'wap_name.encode('utf-8')scene_info = {"h5_info": {"type": "Wap", "wap_url": "http://{}/Notify_wx".format(host), "wap_name": wap_name}}out_trade_no = get_token(nonce_str)# md5 加密生成订单编号ip = self.request.remote_ip# x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR')# print(self.request.META)# if x_forwarded_for:#     spbill_create_ip = x_forwarded_for.split(',')[0]  # 所以这里是真实的ip# else:#     spbill_create_ip = self.request.META.get('REMOTE_ADDR')  # 这里获得代理ip# 此处 为django获取ip的方法total_amount = str(int(float(total_fee) * 100))trade_type = 'MWEB'signA = "appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&out_trade_no=%s&scene_info=%s&spbill_create_ip=%s&total_fee=%s&trade_type=%s" % (appid, body, mch_id, nonce_str, notify_url, out_trade_no, scene_info, ip, total_amount,trade_type)print(signA)strSignTmp = signA + "&key=" + keysign = get_token(strSignTmp).upper()# 进行MD5加密print(sign)post_data = "<xml>"for i in (signA + "&sign=" + sign).split("&"):xml1 = i.split("=")[0]xml2 = i.split("=")[1]post_data = post_data + '<' + xml1 + '>' + xml2 + '</' + xml1 + '>'post_data = post_data + '</xml>'# 组合xml请求print(post_data)# post_data.encode('utf-8')headers = {'Content-Type': 'binary'}# 解决post_data 中文编码问题url = "https://api.mch.weixin.qq.com/pay/unifiedorder"res = requests.post(url, data=post_data.encode(), headers=headers, verify=False)# 提交订单信息# res.text.encode('utf-8')print(res.text.encode('latin_1').decode('utf8'))pattern = re.compile("<mweb_url><!\[CDATA\[(.*?)]]></mweb_url")redicrt_url = pattern.findall(res.text)[0]# 匹配微信回调函数,调用微信app进行支付self.redirect(redicrt_url)# 重定向至微信

客户充值完成之后微信会回调传一个xml,通过返回信息确定是否支付,

3、回调 (r'/Notify_URL', Notify_URLHandler),
忘记了get还是post了,先当post用了

class Notify_URLHandler(tornado.web.RequestHandler):def post(self):print(self.request.body)xml1 = str(self.request.body, encoding='utf-8')print("cml", xml1)pattertn = re.compile(r'out_trade_no><!\[CDATA\[(.*?)]]></out_trade_no')out_trade_no = pattertn.findall(xml1)[0]print(out_trade_no)appid = ''mch_id = ''body = ""key = ''nonce_str = str(uuid.uuid4()).replace('-', "")[:-3]signA = "appid=%s&mch_id=%s&nonce_str=%s&out_trade_no=%s" % (appid, mch_id, nonce_str, out_trade_no)print(signA)strSignTmp = signA + "&key=" + keysign = get_token(strSignTmp).upper()xml = '''<xml><appid>%s</appid><mch_id>%s</mch_id><nonce_str>%s</nonce_str><out_trade_no>%s</out_trade_no><sign>%s</sign></xml>''' % (appid,mch_id,nonce_str, out_trade_no, sign)url = 'https://api.mch.weixin.qq.com/pay/orderquery'headers = {'Accept-Language': 'zh-CN,en-US;q=0.8',# 'Content-Type': 'application/json'# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Accept": "application/xml;charset=UTF-8",}# 我用requests 出现乱码,用urllibreq = reqt.Request(url, headers=headers, data=xml.encode())  # POST方法#page = reqt.urlopen(req).read()print(page)page = page.decode('utf-8')#print(page)pattertn2 = re.compile(r'trade_state_desc><!\[CDATA\[(.*?)]]></trade_state_desc')trade_state_desc = pattertn2.findall(page)[0]print(trade_state_desc)if trade_state_desc == '支付成功':print("匹配成功")######################## 这里处理自己需要的处理的#######################self.write("")

上述基本完成,把那几个参数替换成自己的有问题在探讨
现附上整个代码。

#!/usr/bin/python
# -*- encoding:utf-8 -*-
import hashlib
import uuid
import re
from tornado.httpserver import HTTPServer
import tornado.web
from tornado.ioloop import IOLoop
import os
import requests
from urllib import request as reqt
from tornado.options import define, parse_command_line, options
from tornado.web import Applicationsession = requests.session()session.verify = Falsedef get_token(md5str):m1 = hashlib.md5()m1.update(md5str.encode("utf-8"))token = m1.hexdigest()return tokenclass indexHandler(tornado.web.RequestHandler):def get(self):self.render("index.html")class Notify_URLHandler(tornado.web.RequestHandler):def get(self):print(self.request.body)xml1 = str(self.request.body, encoding='utf-8')print("cml", xml1)pattertn = re.compile(r'out_trade_no><!\[CDATA\[(.*?)]]></out_trade_no')out_trade_no = pattertn.findall(xml1)[0]print(out_trade_no)appid = ''mch_id = ''body = ""key = ''nonce_str = str(uuid.uuid4()).replace('-', "")[:-3]signA = "appid=%s&mch_id=%s&nonce_str=%s&out_trade_no=%s" % (appid, mch_id, nonce_str, out_trade_no)print(signA)strSignTmp = signA + "&key=" + keysign = get_token(strSignTmp).upper()xml = '''<xml><appid>%s</appid><mch_id>%s</mch_id><nonce_str>%s</nonce_str><out_trade_no>%s</out_trade_no><sign>%s</sign></xml>''' % (appid,mch_id,nonce_str, out_trade_no, sign)url = 'https://api.mch.weixin.qq.com/pay/orderquery'headers = {'Accept-Language': 'zh-CN,en-US;q=0.8',# 'Content-Type': 'application/json'# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Accept": "application/xml;charset=UTF-8",}# 我用requests 出现乱码,用urllibreq = reqt.Request(url, headers=headers, data=xml.encode())  # POST方法#page = reqt.urlopen(req).read()print(page)page = page.decode('utf-8')#print(page)pattertn2 = re.compile(r'trade_state_desc><!\[CDATA\[(.*?)]]></trade_state_desc')trade_state_desc = pattertn2.findall(page)[0]print(trade_state_desc)if trade_state_desc == '支付成功':print("匹配成功")######################## 这里处理自己需要的处理的#######################self.write("")def post(self):print(self.request.body)self.write("")# 微信回调函数class Notify_wxHandler(tornado.web.RequestHandler):def get(self):total_fee = "20"# 金额appid = 'appid'mch_id = 'mch_id'body = "微信Demo"key = ''host = "域名 "# 微信填写的备案域名nonce_str = str(uuid.uuid4()).replace('-', "")[:-3]# 生成随机字符串notify_url = 'http://{}/Notify_URL'.format(host)# 回调函数wap_name = '腾讯充值'wap_name.encode('utf-8')scene_info = {"h5_info": {"type": "Wap", "wap_url": "http://{}/Notify_wx".format(host), "wap_name": wap_name}}out_trade_no = get_token(nonce_str)# md5 加密生成订单编号ip = self.request.remote_ip# x_forwarded_for = self.request.META.get('HTTP_X_FORWARDED_FOR')# print(self.request.META)# if x_forwarded_for:#     spbill_create_ip = x_forwarded_for.split(',')[0]  # 所以这里是真实的ip# else:#     spbill_create_ip = self.request.META.get('REMOTE_ADDR')  # 这里获得代理ip# 此处 为django获取ip的方法total_amount = str(int(float(total_fee) * 100))trade_type = 'MWEB'signA = "appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&out_trade_no=%s&scene_info=%s&spbill_create_ip=%s&total_fee=%s&trade_type=%s" % (appid, body, mch_id, nonce_str, notify_url, out_trade_no, scene_info, ip, total_amount,trade_type)print(signA)strSignTmp = signA + "&key=" + keysign = get_token(strSignTmp).upper()# 进行MD5加密print(sign)post_data = "<xml>"for i in (signA + "&sign=" + sign).split("&"):xml1 = i.split("=")[0]xml2 = i.split("=")[1]post_data = post_data + '<' + xml1 + '>' + xml2 + '</' + xml1 + '>'post_data = post_data + '</xml>'# 组合xml请求print(post_data)# post_data.encode('utf-8')headers = {'Content-Type': 'binary'}# 解决post_data 中文编码问题url = "https://api.mch.weixin.qq.com/pay/unifiedorder"res = requests.post(url, data=post_data.encode(), headers=headers, verify=False)# 提交订单信息# res.text.encode('utf-8')print(res.text.encode('latin_1').decode('utf8'))pattern = re.compile("<mweb_url><!\[CDATA\[(.*?)]]></mweb_url")redicrt_url = pattern.findall(res.text)[0]# 匹配微信回调函数,调用微信app进行支付self.redirect(redicrt_url)# 重定向至微信if __name__ == '__main__':define("port", default=8001, help="默认端口8000")parse_command_line()app = Application([(r'/index', indexHandler),(r'/Notify_wx', Notify_wxHandler),(r'/Notify_URL', Notify_URLHandler),],# 项目配置信息# 网页模板template_path=os.path.join(os.path.dirname(__file__), "templates"),# 静态文件static_path=os.path.join(os.path.dirname(__file__), "static"),# debug=False)# 部署server = HTTPServer(app)server.listen(options.port)# 轮询监听IOLoop.current().start()

最后附上源码链接, https://github.com/baicai2/wxH5PayDemo

微信h5支付python版相关推荐

  1. 微信支付python版2.0_刷卡支付-翟东平-专题视频课程

    微信支付python版2.0_刷卡支付-244人已学习 课程介绍         微信支付系列课程将讲解"刷卡支付"."扫码支付"."公众号支付&qu ...

  2. app 访问h5 如何截取_微信H5支付申请相关问题

    之前的文章「微信支付申请相关问题」里说过微信公众号和 APP 申请微信支付,今天来说下微信 H5 支付的申请. 背景介绍 H5 支付是指商户在微信客户端外的移动端网页展示商品或服务,用户在前述页面确认 ...

  3. 微信h5支付,微信外浏览器支付实现

    对接第三方比较重要的点都有什么? 1.按规则 2.单独封装 3.做好出入参 2021-02-07修改 看一下官方文档还是很必要的,知道必不可少的参数是什么:https://pay.weixin.qq. ...

  4. 微信H5支付坑一--手续费未结算

    2019独角兽企业重金招聘Python工程师标准>>> 简单随笔小记: 场景:在微信H5支付的过程中,无论怎么支付完成,在微信商户后台查询手续费依然未扣除,当时手续费账户月为5元. ...

  5. java微信网页支付_java实现微信H5支付

    原标题:java实现微信H5支付 前面做了app微信支付的回调处理,现在需要做微信公众号的支付,花了一天多时间,终于折腾出来了!鉴于坑爹的微信官方没有提供Java版的demo,所以全靠自己按照同样坑爹 ...

  6. 记录下关于微信h5支付那点事儿(百分之80拷贝官方)

    LZ-Says:困意上来,感觉简直痛不欲生~ 生亦何欢~!!! 前言 这俩天在玩微信的H5支付,不得不说,腾讯出品,Enmmm,懂就好... 原想着这是一件很easy的东西,WebView加载一个地址 ...

  7. 微信H5支付、非微信H5支付、公众号支付、小程序支付

    文章目录 前言 一.微信H5支付和非微信H5支付 二.公众号支付 三.小程序支付 总结 前言 最近公司又要搞微信支付,大体上就是把app上VIP那一套内容但做成网页版,更方便用户去购买vip,老板就让 ...

  8. 解决iOS微信H5支付跳转微信后不返回App问题(Swift-WKWebview)(转)

    解决iOS微信H5支付跳转微信后不返回App问题(Swift-WKWebview)(转) 参考文章: (1)解决iOS微信H5支付跳转微信后不返回App问题(Swift-WKWebview)(转) ( ...

  9. Android 应用内微信 H5 支付

    一般情况下,要实现应用内支付接入 App 支付 SDK 即可满足业务需求,不过考虑到对于一些类似游戏中心的场景,更多是需要支持 H5 支付.相对微信来说,支付宝的对接简单完善很多,所以本篇文章主要说说 ...

最新文章

  1. [WC2013]平面图——平面图点定位
  2. zuul filter
  3. mysql warning 在哪看_查看MySQL的warning
  4. Linux中增加软路由的两种方法,Linux中增加软路由的三种方法
  5. 设置数据库及表的默认字符集
  6. 大学计算机vb基础知识6,大学计算机基础vb试题大学计算机基础试题和答案.doc
  7. SPSS中有关相关性分析的介绍(双变量相关分析、偏相关)
  8. js 生成二维码(qrcodejs)
  9. Java线程的状态及主要转化方法
  10. QTcpSocket服务器多线程
  11. recyclerView多条目加载,点击动画事件
  12. uniapp安卓上传图片有时候会自动旋转问题解决
  13. 基于stm32f407的示波器
  14. dw自动滚动图片_DW图片无缝滚动代码
  15. jupyter notebook 基本操作
  16. jmu-python-生日悖论(熟练掌握随机数的生成以及检查重复)
  17. 如何优化WebService进行大批量数据传送(WSE3.0应用技巧)
  18. 观远数据:BI技术平民化,让消费企业获得百倍增长机会
  19. 火绒真的比360安全卫士好吗?
  20. 切比雪夫------切比雪夫不等式

热门文章

  1. 建立maven的web项目可能会遇到的一个问题Cannot detect Web Project version.
  2. 检测cpu是否支持虚拟化和二级地址转换
  3. matlab版开源GNSS_SDR-masterGPS软件接收机代码解读
  4. nginx流媒体服务器(基于CentOS7)实现rtmp直播流,m3u8视频流
  5. verilog运算符优先级别
  6. STM32 F103 基础实验
  7. 嵌入式GUI LVGL『Text Area文本区域控件』介绍
  8. HTML+CSS+JavaScript实现在线网盘
  9. SiteMesh 使用与配置
  10. 揭开神经网络加速器的神秘面纱之DianNao