本文主要是介绍Flask与微信小程序数据通讯 第二步 微信支付之小程序支付,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_3&index=1
微信小程序API 微信支付_w3cschool
flask项目和微信小程序通讯的项目,如何微信支付功能?
Flask是一个基于Python的轻量级Web框架,它可以用来构建Web应用程序。微信小程序是一种基于微信平台的应用程序,可以在微信中直接使用。下面是关于Flask项目和微信小程序通讯的一种实现方式以及如何添加微信支付功能的介绍:
-
Flask项目和微信小程序通讯:
- 首先,你可以使用Flask提供的路由功能来定义不同的URL路径和对应的处理函数,用于处理微信小程序发送的请求。
- 在处理函数中,你可以通过解析微信小程序发送的数据,进行相应的业务逻辑处理,并返回相应的结果给微信小程序。
-
如何实现微信支付功能:
- 首先,你需要在微信支付商户平台上注册并获取到相应的商户号和API密钥。
- 在Flask项目中,你可以使用第三方库(如wechatpy、wechatpay等)来实现与微信支付接口的交互。
- 在处理用户发起支付请求时,你可以调用相应的接口生成预支付订单,并将相关参数返回给前端。
- 前端收到预支付订单参数后,可以调用微信小程序提供的支付接口进行支付操作。
- 支付完成后,微信会向你预先设置的回调URL发送支付结果通知,你需要在Flask项目中编写相应的回调处理函数来处理支付结果。
mina/pages/my/order_list.wxml
<view class="container"><view class="status-box"><view bindtap="statusTap" class="status-label {{index == currentType ? 'active' : ''}}" wx:for-items="{{statusType}}" wx:key="{{index}}" data-index="{{index}}">{{item}}<view class="{{tabClass[index]}}"></view></view></view><view class="no-order" wx:if="{{!order_list.length}}"><image src="/images/no-order.png" class="no-order-img"></image><view class="text">暂无订单</view></view><view class="order-list" wx:if="{{order_list.length}}"><view class="a-order" wx:for="{{order_list}}" wx:key="{{index}}" wx:for-item="item"><view class="order-date" data-id="{{item.order_sn}}" bindtap="orderDetail"><view class="date-box">下单时间:{{item.date}}</view><view class="status {{(item.status==0 || item.status==1) ? '':'red'}}">{{item.status_desc}}</view></view><view class="goods-info" data-id="{{item.order_sn}}" bindtap="orderDetail"><view class="goods-des"><view>订单号:{{item.order_number}} </view><view wx:if="{{item.note && item.note != ''}}">备注: {{item.note}}</view></view></view><view ><scroll-view class="goods-img-container" scroll-x="true"><view class="img-box" wx:for="{{item.goods_list}}" wx:for-item="itemGood"><image src="{{itemGood.pic_url}}" class="goods-img"></image></view></scroll-view></view><view class="price-box"><view class="total-price">合计:¥ {{item.total_price}}</view><view class="btn cancel-btn" bindtap="orderCancel" data-id="{{item.order_sn}}" wx:if="{{item.status==-8}}">取消订单</view><view class="btn topay-btn" bindtap="toPay" data-id="{{item.order_sn}}" wx:if="{{item.status==-8}}">马上付款</view><view class="btn topay-btn" bindtap="orderConfirm" data-id="{{item.order_sn}}" wx:if="{{item.status==-6}}">确认收货</view><view class="btn topay-btn" bindtap="orderComment" data-id="{{item.order_sn}}" wx:if="{{item.status==-5}}">走,去评价</view></view></view></view>
</view>
首先在wxml中定义一个支付按钮,绑定toPay事件
小程序端js中发出wx.requst给flask服务器
mina/pages/my/order_list.js 中的topay函数
var app = getApp();
Page({data: {order_list:[],statusType: ["待付款", "待发货", "待确认", "待评价", "已完成","已关闭"],status:[ "-8","-7","-6","-5","1","0" ],currentType: 0,tabClass: ["", "", "", "", "", ""]},statusTap: function (e) {var curType = e.currentTarget.dataset.index;this.setData({currentType: curType});this.getPayOrder();},orderDetail: function (e) {wx.navigateTo({url: "/pages/my/order_info?order_sn=" + e.currentTarget.dataset.id})},onLoad: function (options) {// 生命周期函数--监听页面加载},onShow: function () {this.getPayOrder();},orderCancel:function( e ){this.orderOps( e.currentTarget.dataset.id,"cancel","确定取消订单?" );},getPayOrder:function(){var that = this;wx.request({url: app.buildUrl("/my/order"),header: app.getRequestHeader(),data: {status: that.data.status[ that.data.currentType ]},success: function (res) {var resp = res.data;if (resp.code != 200) {app.alert({"content": resp.msg});return;}that.setData({order_list:resp.data.pay_order_list});}});},toPay:function( e ){var that = this;// 使用微信小程序的wx.request方法发送一个POST请求,并在请求成功后进行支付操作// 使用wx.request方法发送POST请求,请求的URL是"/order/pay",并且设置请求头为app.getRequestHeader()方法返回的值wx.request({url: app.buildUrl("/order/pay"),header: app.getRequestHeader(),method: 'POST',data: {order_sn: e.currentTarget.dataset.id},// 如果请求成功,会执行success回调函数。在回调函数中,首先获取返回数据res.data,并将其赋值给变量resp。success: function (res) {var resp = res.data;// 判断resp.code是否等于200,如果不等于200,则调用app.alert方法弹出提示框,并返回。if (resp.code != 200) {app.alert({"content": resp.msg});return;}// 如果resp.code等于200,则从resp.data中获取pay_info,并将其赋值给变量pay_info。var pay_info = resp.data.pay_info;// 使用wx.requestPayment方法进行支付操作,传入参数包括时间戳、随机字符串、package、签名类型和支付签名。wx.requestPayment({'timeStamp': pay_info.timeStamp,'nonceStr': pay_info.nonceStr,'package': pay_info.package,'signType': 'MD5','paySign': pay_info.paySign,// 如果支付成功,会执行success回调函数;如果支付失败,会执行fail回调函数。'success': function (res) {},'fail': function (res) {}});}});},orderConfirm:function( e ){this.orderOps( e.currentTarget.dataset.id,"confirm","确定收到?" );},orderComment:function( e ){wx.navigateTo({url: "/pages/my/comment?order_sn=" + e.currentTarget.dataset.id});},orderOps:function(order_sn,act,msg){var that = this;var params = {"content":msg,"cb_confirm":function(){wx.request({url: app.buildUrl("/order/ops"),header: app.getRequestHeader(),method: 'POST',data: {order_sn: order_sn,act:act},success: function (res) {var resp = res.data;app.alert({"content": resp.msg});if ( resp.code == 200) {that.getPayOrder();}}});}};app.tip( params );}
});
wx.requestPayment(Object object) | 微信开放文档
web/controllers/api/Order.py 的orderPay()函数
# -*- coding: utf-8 -*-
from web.controllers.api import route_api
from flask import request, jsonify,g
from app import app, db
import json, decimal
from common.models.food.Food import Food
from common.models.pay.PayOrder import PayOrder
from common.libs.UrlManager import UrlManager
from common.libs.Helper import getCurrentDate
from common.libs.pay.PayService import PayService
from common.libs.pay.WeChatService import WeChatService
from common.libs.member.CartService import CartService
from common.models.member.MemberAddress import MemberAddress
from common.models.member.OauthMemberBind import OauthMemberBind@route_api.route("/order/info", methods=[ "POST" ])
def orderInfo():resp = {'code': 200, 'msg': '操作成功~', 'data': {}}req = request.valuesparams_goods = req['goods'] if 'goods' in req else Nonemember_info = g.member_infoparams_goods_list = []if params_goods:params_goods_list = json.loads(params_goods)food_dic = {}for item in params_goods_list:food_dic[item['id']] = item['number']food_ids = food_dic.keys()food_list = Food.query.filter(Food.id.in_(food_ids)).all()data_food_list = []yun_price = pay_price = decimal.Decimal(0.00)if food_list:for item in food_list:tmp_data = {"id": item.id,"name": item.name,"price": str(item.price),'pic_url': UrlManager.buildImageUrl(item.main_image),'number': food_dic[item.id]}pay_price = pay_price + item.price * int( food_dic[item.id] )data_food_list.append(tmp_data)# 获取地址address_info = MemberAddress.query.filter_by( is_default = 1,member_id = member_info.id,status = 1 ).first()default_address = ''if address_info:default_address = {"id": address_info.id,"name": address_info.nickname,"mobile": address_info.mobile,"address":"%s%s%s%s"%( address_info.province_str,address_info.city_str,address_info.area_str,address_info.address )}resp['data']['food_list'] = data_food_listresp['data']['pay_price'] = str(pay_price)resp['data']['yun_price'] = str(yun_price)resp['data']['total_price'] = str(pay_price + yun_price)resp['data']['default_address'] = default_addressreturn jsonify(resp)@route_api.route("/order/create", methods=[ "POST"])
def orderCreate():resp = {'code': 200, 'msg': '操作成功~', 'data': {}}req = request.valuestype = req['type'] if 'type' in req else ''note = req['note'] if 'note' in req else ''express_address_id = int( req['express_address_id'] ) if 'express_address_id' in req and req['express_address_id'] else 0params_goods = req['goods'] if 'goods' in req else Noneitems = []if params_goods:items = json.loads(params_goods)if len( items ) < 1:resp['code'] = -1resp['msg'] = "下单失败:没有选择商品~~"return jsonify(resp)address_info = MemberAddress.query.filter_by( id = express_address_id ).first()if not address_info or not address_info.status:resp['code'] = -1resp['msg'] = "下单失败:快递地址不对~~"return jsonify(resp)member_info = g.member_infotarget = PayService()params = {"note":note,'express_address_id':address_info.id,'express_info':{'mobile':address_info.mobile,'nickname':address_info.nickname,"address":"%s%s%s%s"%( address_info.province_str,address_info.city_str,address_info.area_str,address_info.address )}}resp = target.createOrder( member_info.id ,items ,params)#如果是来源购物车的,下单成功将下单的商品去掉if resp['code'] == 200 and type == "cart":CartService.deleteItem( member_info.id,items )return jsonify( resp )@route_api.route("/order/pay", methods=[ "POST"])
def orderPay():resp = {'code': 200, 'msg': '操作成功~', 'data': {}}# 获取请求中的订单号(order_sn)和用户信息(member_info)member_info = g.member_inforeq = request.valuesorder_sn = req['order_sn'] if 'order_sn' in req else ''# 根据订单号和用户ID查询支付订单信息(pay_order_info),如果不存在,则返回错误提示信息。pay_order_info = PayOrder.query.filter_by( order_sn = order_sn,member_id = member_info.id ).first()if not pay_order_info:resp['code'] = -1resp['msg'] = "系统繁忙。请稍后再试~~"return jsonify(resp)# 根据用户ID查询第三方登录绑定信息(oauth_bind_info),如果不存在,则返回错误提示信息。oauth_bind_info = OauthMemberBind.query.filter_by( member_id = member_info.id ).first()if not oauth_bind_info:resp['code'] = -1resp['msg'] = "系统繁忙。请稍后再试~~"return jsonify(resp)# 获取配置文件中的小程序配置(config_mina)和回调URL(notify_url)。config_mina = app.config['MINA_APP']notify_url = app.config['APP']['domain'] + config_mina['callback_url']# 创建WeChatService对象(target_wechat),并传入商户密钥(merchant_key)。target_wechat = WeChatService( merchant_key=config_mina['paykey'] )# 创建一个包含支付相关信息,其中包括了appid、mch_idnonce_str、body、out_trade_no、total_fee、notify_url、trade_type和openid等字段。data = {'appid': config_mina['appid'],'mch_id': config_mina['mch_id'],'nonce_str': target_wechat.get_nonce_str(),'body': '订餐', # 商品描述'out_trade_no': pay_order_info.order_sn, # 商户订单号'total_fee': int( pay_order_info.total_price * 100 ),'notify_url': notify_url,'trade_type': "JSAPI",'openid': oauth_bind_info.openid}# 调用target_wechat对象的get_pay_info方法,传入支付数据data,获取支付信息pay_info。pay_info = target_wechat.get_pay_info( pay_data=data)# 将prepay_id保存到pay_order_info对象中,并将其添加到数据库中。#保存prepay_id为了后面发模板消息pay_order_info.prepay_id = pay_info['prepay_id']db.session.add( pay_order_info )db.session.commit()# 将pay_info添加到resp字典的data字段中resp['data']['pay_info'] = pay_inforeturn jsonify(resp)@route_api.route("/order/callback", methods=[ "POST"])
def orderCallback():result_data = {'return_code': 'SUCCESS','return_msg': 'OK'}header = {'Content-Type': 'application/xml'}config_mina = app.config['MINA_APP']target_wechat = WeChatService(merchant_key=config_mina['paykey'])callback_data = target_wechat.xml_to_dict( request.data )app.logger.info( callback_data )sign = callback_data['sign']callback_data.pop( 'sign' )gene_sign = target_wechat.create_sign( callback_data )app.logger.info(gene_sign)if sign != gene_sign:result_data['return_code'] = result_data['return_msg'] = 'FAIL'return target_wechat.dict_to_xml(result_data), headerif callback_data['result_code'] != 'SUCCESS':result_data['return_code'] = result_data['return_msg'] = 'FAIL'return target_wechat.dict_to_xml(result_data), headerorder_sn = callback_data['out_trade_no']pay_order_info = PayOrder.query.filter_by(order_sn=order_sn).first()if not pay_order_info:result_data['return_code'] = result_data['return_msg'] = 'FAIL'return target_wechat.dict_to_xml(result_data), headerif int( pay_order_info.total_price * 100 ) != int( callback_data['total_fee'] ):result_data['return_code'] = result_data['return_msg'] = 'FAIL'return target_wechat.dict_to_xml(result_data), headerif pay_order_info.status == 1:return target_wechat.dict_to_xml(result_data), headertarget_pay = PayService()target_pay.orderSuccess( pay_order_id = pay_order_info.id,params = { "pay_sn":callback_data['transaction_id'] } )target_pay.addPayCallbackData( pay_order_id = pay_order_info.id, data = request.data)return target_wechat.dict_to_xml(result_data), header@route_api.route("/order/ops", methods=[ "POST"])
def orderOps():resp = {'code': 200, 'msg': '操作成功~', 'data': {}}req = request.valuesmember_info = g.member_infoorder_sn = req['order_sn'] if 'order_sn' in req else ''act = req['act'] if 'act' in req else ''pay_order_info = PayOrder.query.filter_by(order_sn=order_sn, member_id=member_info.id).first()if not pay_order_info:resp['code'] = -1resp['msg'] = "系统繁忙。请稍后再试~~"return jsonify(resp)if act == "cancel":target_pay = PayService( )ret = target_pay.closeOrder( pay_order_id=pay_order_info.id )if not ret:resp['code'] = -1resp['msg'] = "系统繁忙。请稍后再试~~"return jsonify(resp)elif act == "confirm":pay_order_info.express_status = 1pay_order_info.updated_time = getCurrentDate()db.session.add( pay_order_info )db.session.commit()return jsonify(resp)
orderPay()
问题: g的值有用户的member_id信息,这值是在哪被定义的
问题: 为什么使用g变量而不是session
reqeust.values
request.values是一个字典对象,用于获取HTTP请求中的参数。它可以获取GET和POST请求中的参数,并且可以同时获取表单数据和URL参数。request.values是一个融合了request.args和request.form的字典对象。
当HTTP请求为GET请求时,request.values会获取URL中的参数,即查询字符串中的参数。当HTTP请求为POST请求时,request.values会获取表单中的参数。
使用request.values可以方便地获取HTTP请求中的参数,无论是GET请求还是POST请求,无论是URL参数还是表单参数。
common/libs/pay/WeChatService.py
# -*- coding: utf-8 -*-
import hashlib,requests,uuid,json,datetime
import xml.etree.ElementTree as ET
from app import app,db
from common.models.pay.OauthAccessToken import OauthAccessToken
from common.libs.Helper import getCurrentDate
class WeChatService():def __init__(self,merchant_key = None):self.merchant_key = merchant_keydef create_sign(self, pay_data):'''生成签名:return:'''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.encode("utf-8") ).hexdigest()return sign.upper()def get_pay_info(self,pay_data = None):'''获取支付信息:param xml_data::return:'''sign = self.create_sign( pay_data )pay_data ['sign'] = signxml_data = self.dict_to_xml( pay_data )headers = {'Content-Type': 'application/xml'}url = "https://api.mch.weixin.qq.com/pay/unifiedorder"r = requests.post( url= url, data=xml_data.encode('utf-8'),headers = headers)r.encoding = "utf-8"app.logger.info( r.text )if r.status_code == 200:prepay_id = self.xml_to_dict( r.text ).get('prepay_id')pay_sign_data = {'appId': pay_data.get('appid'),'timeStamp': pay_data.get('out_trade_no'),'nonceStr': pay_data.get('nonce_str'),'package': 'prepay_id={0}'.format(prepay_id),'signType': 'MD5'}pay_sign = self.create_sign( pay_sign_data )pay_sign_data.pop('appId')pay_sign_data['paySign'] = pay_signpay_sign_data['prepay_id'] = prepay_idreturn pay_sign_datareturn Falsedef dict_to_xml(self,dict_data):'''dict to xml:param dict_data::return:'''xml = ["<xml>"]for k, v in dict_data.items():xml.append("<{0}>{1}</{0}>".format(k, v))xml.append("</xml>")return "".join(xml)def xml_to_dict(self,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.textreturn xml_dictdef get_nonce_str(self):'''获取随机字符串:return:'''return str(uuid.uuid4()).replace('-', '')def getAccessToken(self):token = Nonetoken_info = OauthAccessToken.query.filter( OauthAccessToken.expired_time >= getCurrentDate() ).first()if token_info:token = token_info.access_tokenreturn tokenconfig_mina = app.config['MINA_APP']url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}"\.format( config_mina['appid'],config_mina['appkey'] )r = requests.get( url = url )if r.status_code != 200 or not r.text:return tokendata = json.loads( r.text )now = datetime.datetime.now()date = now + datetime.timedelta(seconds=data['expires_in'] - 200)model_token = OauthAccessToken()model_token.access_token = data['access_token']model_token.expired_time = date.strftime( "%Y-%m-%d %H:%M:%S" )model_token.created_time = getCurrentDate()db.session.add( model_token )db.session.commit()return data['access_token']
openid 在用户登录成功时就已经添加到数据库中了
web/controllers/api/Member.py
openid = MemberService.getWeChatOpenId( code )
common/libs/member/MemberService.py
@staticmethoddef getWeChatOpenId( code ):url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code" \.format(app.config['MINA_APP']['appid'], app.config['MINA_APP']['appkey'], code)r = requests.get(url)res = json.loads(r.text)openid = Noneif 'openid' in res:openid = res['openid']return openid
这篇关于Flask与微信小程序数据通讯 第二步 微信支付之小程序支付的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!