python 微信小程序支付、查询、退款使用wechatpy库

news2025/4/18 14:40:49

首先使用 wechatpy 库,执行以下命令进行安装

pip install wechatpy

1、 直连商户支付

import logging
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from wechatpy.pay import WeChatPay
from wechatpy.pay.api import WeChatOrder, WeChatRefund
# 假设这里有获取数据库配置的函数
from your_app.models import PaymentConfig  # 请替换为实际的模型

# 获取当前模块的日志记录器,用于记录程序运行中的信息和错误
logger = logging.getLogger(__name__)


def get_payment_config():
    """
    从数据库中获取直连商户的支付配置信息。

    :return: 包含支付配置信息的字典,如果未找到则返回 None
    """
    try:
        # 假设只有一个直连商户配置,从数据库中获取
        config = PaymentConfig.objects.first()
        return {
            'appid': config.appid,  # 微信小程序的 AppID
            'mch_id': config.mch_id,  # 微信支付商户号
            'api_key': config.api_key,  # 微信支付 API 密钥
            'cert_path': config.cert_path,  # 商户证书路径
            'key_path': config.key_path  # 商户私钥路径
        }
    except AttributeError:
        # 若未找到对应的支付配置,记录错误信息
        logger.error("Payment config not found.")
        return None


@require_http_methods(["POST"])
def wx_pay(request):
    """
    处理微信小程序支付请求,创建预支付订单并返回支付参数。

    :param request: Django 请求对象,包含 POST 请求的数据
    :return: JSON 响应,包含支付结果和相关信息
    """
    # 获取 POST 请求中的所有数据,并转换为字典
    data = request.POST.dict()
    # 获取支付配置
    config = get_payment_config()
    if not config:
        # 若未找到支付配置,返回错误信息
        return JsonResponse({'code': 400, 'msg': 'Payment config not found'})

    # 根据支付配置初始化微信支付对象
    wechat_pay = WeChatPay(
        appid=config['appid'],
        mch_id=config['mch_id'],
        api_key=config['api_key'],
        cert_path=config['cert_path'],
        key_path=config['key_path']
    )
    # 创建微信订单 API 对象
    order_api = WeChatOrder(wechat_pay)
    try:
        # 调用微信支付 API 创建预支付订单
        result = order_api.create(
            trade_type='JSAPI',  # 交易类型,JSAPI 表示微信小程序支付
            body=data.get('body'),  # 商品描述
            out_trade_no=data.get('out_trade_no'),  # 商户订单号
            total_fee=int(float(data.get('total_fee')) * 100),  # 订单总金额,单位为分
            notify_url=data.get('notify_url'),  # 支付结果通知地址
            openid=data.get('openid')  # 用户的微信 openid
        )
        if result.get('return_code') == 'SUCCESS' and result.get('result_code') == 'SUCCESS':
            # 若预支付订单创建成功,获取预支付 ID
            prepay_id = result.get('prepay_id')
            # 获取微信小程序支付所需的参数
            pay_params = wechat_pay.jsapi.get_jsapi_params(prepay_id)
            # 返回成功响应,包含支付参数
            return JsonResponse({'code': 200, 'msg': 'Success', 'data': pay_params})
        else:
            # 若预支付订单创建失败,返回错误信息
            return JsonResponse({'code': 400, 'msg': result.get('return_msg')})
    except Exception as e:
        # 若出现异常,记录错误信息并返回错误响应
        logger.error(f"Payment error: {e}")
        return JsonResponse({'code': 500, 'msg': 'Payment error'})


@require_http_methods(["POST"])
def wx_query(request):
    """
    处理微信订单查询请求,返回订单的详细信息。

    :param request: Django 请求对象,包含 POST 请求的数据
    :return: JSON 响应,包含查询结果和相关信息
    """
    # 获取 POST 请求中的所有数据,并转换为字典
    data = request.POST.dict()
    # 获取支付配置
    config = get_payment_config()
    if not config:
        # 若未找到支付配置,返回错误信息
        return JsonResponse({'code': 400, 'msg': 'Payment config not found'})

    # 根据支付配置初始化微信支付对象
    wechat_pay = WeChatPay(
        appid=config['appid'],
        mch_id=config['mch_id'],
        api_key=config['api_key'],
        cert_path=config['cert_path'],
        key_path=config['key_path']
    )
    # 创建微信订单 API 对象
    order_api = WeChatOrder(wechat_pay)
    try:
        # 调用微信支付 API 查询订单信息
        result = order_api.query(out_trade_no=data.get('out_trade_no'))
        # 返回成功响应,包含订单查询结果
        return JsonResponse({'code': 200, 'msg': 'Success', 'data': result})
    except Exception as e:
        # 若出现异常,记录错误信息并返回错误响应
        logger.error(f"Query error: {e}")
        return JsonResponse({'code': 500, 'msg': 'Query error'})


@require_http_methods(["POST"])
def wx_refund(request):
    """
    处理微信订单退款请求,发起退款操作并返回结果。

    :param request: Django 请求对象,包含 POST 请求的数据
    :return: JSON 响应,包含退款结果和相关信息
    """
    # 获取 POST 请求中的所有数据,并转换为字典
    data = request.POST.dict()
    # 获取支付配置
    config = get_payment_config()
    if not config:
        # 若未找到支付配置,返回错误信息
        return JsonResponse({'code': 400, 'msg': 'Payment config not found'})

    # 根据支付配置初始化微信支付对象
    wechat_pay = WeChatPay(
        appid=config['appid'],
        mch_id=config['mch_id'],
        api_key=config['api_key'],
        cert_path=config['cert_path'],
        key_path=config['key_path']
    )
    # 创建微信退款 API 对象
    refund_api = WeChatRefund(wechat_pay)
    try:
        # 调用微信支付 API 发起退款操作
        result = refund_api.create(
            out_trade_no=data.get('out_trade_no'),  # 商户订单号
            out_refund_no=data.get('out_refund_no'),  # 商户退款单号
            total_fee=int(float(data.get('total_fee')) * 100),  # 订单总金额,单位为分
            refund_fee=int(float(data.get('refund_fee')) * 100)  # 退款金额,单位为分
        )
        if result.get('return_code') == 'SUCCESS' and result.get('result_code') == 'SUCCESS':
            # 若退款操作成功,返回成功响应,包含退款结果
            return JsonResponse({'code': 200, 'msg': 'Success', 'data': result})
        else:
            # 若退款操作失败,返回错误信息
            return JsonResponse({'code': 400, 'msg': result.get('return_msg')})
    except Exception as e:
        # 若出现异常,记录错误信息并返回错误响应
        logger.error(f"Refund error: {e}")
        return JsonResponse({'code': 500, 'msg': 'Refund error'})
    

2、有子商户的实现

import logging
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from wechatpy.pay import WeChatPay
from wechatpy.pay.api import WeChatOrder, WeChatRefund
# 假设这里有获取数据库配置的函数
from your_app.models import PaymentConfig  # 请替换为实际的模型

# 获取当前模块的日志记录器,用于记录程序运行中的信息和错误
logger = logging.getLogger(__name__)


def get_payment_config(sub_mch_id):
    """
    根据子商户 ID 从数据库中获取支付配置信息。

    :param sub_mch_id: 子商户 ID
    :return: 包含支付配置信息的字典,如果未找到则返回 None
    """
    try:
        # 从数据库中查找指定子商户 ID 的支付配置
        config = PaymentConfig.objects.get(sub_mch_id=sub_mch_id)
        return {
            'appid': config.appid,  # 微信小程序的 AppID
            'mch_id': config.mch_id,  # 微信支付商户号
            'sub_mch_id': config.sub_mch_id,  # 子商户号
            'api_key': config.api_key,  # 微信支付 API 密钥
            'cert_path': config.cert_path,  # 商户证书路径
            'key_path': config.key_path  # 商户私钥路径
        }
    except PaymentConfig.DoesNotExist:
        # 若未找到对应的支付配置,记录错误信息
        logger.error(f"Payment config not found for sub_mch_id: {sub_mch_id}")
        return None


@require_http_methods(["POST"])
def wx_pay(request):
    """
    处理微信小程序支付请求,创建预支付订单并返回支付参数。

    :param request: Django 请求对象,包含 POST 请求的数据
    :return: JSON 响应,包含支付结果和相关信息
    """
    # 获取 POST 请求中的所有数据,并转换为字典
    data = request.POST.dict()
    # 从请求数据中获取子商户 ID
    sub_mch_id = data.get('sub_mch_id')
    # 根据子商户 ID 获取支付配置
    config = get_payment_config(sub_mch_id)
    if not config:
        # 若未找到支付配置,返回错误信息
        return JsonResponse({'code': 400, 'msg': 'Payment config not found'})

    # 根据支付配置初始化微信支付对象
    wechat_pay = WeChatPay(
        appid=config['appid'],
        mch_id=config['mch_id'],
        sub_mch_id=config['sub_mch_id'],
        api_key=config['api_key'],
        cert_path=config['cert_path'],
        key_path=config['key_path']
    )
    # 创建微信订单 API 对象
    order_api = WeChatOrder(wechat_pay)
    try:
        # 调用微信支付 API 创建预支付订单
        result = order_api.create(
            trade_type='JSAPI',  # 交易类型,JSAPI 表示微信小程序支付
            body=data.get('body'),  # 商品描述
            out_trade_no=data.get('out_trade_no'),  # 商户订单号
            total_fee=int(float(data.get('total_fee')) * 100),  # 订单总金额,单位为分
            notify_url=data.get('notify_url'),  # 支付结果通知地址
            openid=data.get('openid')  # 用户的微信 openid
        )
        if result.get('return_code') == 'SUCCESS' and result.get('result_code') == 'SUCCESS':
            # 若预支付订单创建成功,获取预支付 ID
            prepay_id = result.get('prepay_id')
            # 获取微信小程序支付所需的参数
            pay_params = wechat_pay.jsapi.get_jsapi_params(prepay_id)
            # 返回成功响应,包含支付参数
            return JsonResponse({'code': 200, 'msg': 'Success', 'data': pay_params})
        else:
            # 若预支付订单创建失败,返回错误信息
            return JsonResponse({'code': 400, 'msg': result.get('return_msg')})
    except Exception as e:
        # 若出现异常,记录错误信息并返回错误响应
        logger.error(f"Payment error: {e}")
        return JsonResponse({'code': 500, 'msg': 'Payment error'})


@require_http_methods(["POST"])
def wx_query(request):
    """
    处理微信订单查询请求,返回订单的详细信息。

    :param request: Django 请求对象,包含 POST 请求的数据
    :return: JSON 响应,包含查询结果和相关信息
    """
    # 获取 POST 请求中的所有数据,并转换为字典
    data = request.POST.dict()
    # 从请求数据中获取子商户 ID
    sub_mch_id = data.get('sub_mch_id')
    # 根据子商户 ID 获取支付配置
    config = get_payment_config(sub_mch_id)
    if not config:
        # 若未找到支付配置,返回错误信息
        return JsonResponse({'code': 400, 'msg': 'Payment config not found'})

    # 根据支付配置初始化微信支付对象
    wechat_pay = WeChatPay(
        appid=config['appid'],
        mch_id=config['mch_id'],
        sub_mch_id=config['sub_mch_id'],
        api_key=config['api_key'],
        cert_path=config['cert_path'],
        key_path=config['key_path']
    )
    # 创建微信订单 API 对象
    order_api = WeChatOrder(wechat_pay)
    try:
        # 调用微信支付 API 查询订单信息
        result = order_api.query(out_trade_no=data.get('out_trade_no'))
        # 返回成功响应,包含订单查询结果
        return JsonResponse({'code': 200, 'msg': 'Success', 'data': result})
    except Exception as e:
        # 若出现异常,记录错误信息并返回错误响应
        logger.error(f"Query error: {e}")
        return JsonResponse({'code': 500, 'msg': 'Query error'})


@require_http_methods(["POST"])
def wx_refund(request):
    """
    处理微信订单退款请求,发起退款操作并返回结果。

    :param request: Django 请求对象,包含 POST 请求的数据
    :return: JSON 响应,包含退款结果和相关信息
    """
    # 获取 POST 请求中的所有数据,并转换为字典
    data = request.POST.dict()
    # 从请求数据中获取子商户 ID
    sub_mch_id = data.get('sub_mch_id')
    # 根据子商户 ID 获取支付配置
    config = get_payment_config(sub_mch_id)
    if not config:
        # 若未找到支付配置,返回错误信息
        return JsonResponse({'code': 400, 'msg': 'Payment config not found'})

    # 根据支付配置初始化微信支付对象
    wechat_pay = WeChatPay(
        appid=config['appid'],
        mch_id=config['mch_id'],
        sub_mch_id=config['sub_mch_id'],
        api_key=config['api_key'],
        cert_path=config['cert_path'],
        key_path=config['key_path']
    )
    # 创建微信退款 API 对象
    refund_api = WeChatRefund(wechat_pay)
    try:
        # 调用微信支付 API 发起退款操作
        result = refund_api.create(
            out_trade_no=data.get('out_trade_no'),  # 商户订单号
            out_refund_no=data.get('out_refund_no'),  # 商户退款单号
            total_fee=int(float(data.get('total_fee')) * 100),  # 订单总金额,单位为分
            refund_fee=int(float(data.get('refund_fee')) * 100)  # 退款金额,单位为分
        )
        if result.get('return_code') == 'SUCCESS' and result.get('result_code') == 'SUCCESS':
            # 若退款操作成功,返回成功响应,包含退款结果
            return JsonResponse({'code': 200, 'msg': 'Success', 'data': result})
        else:
            # 若退款操作失败,返回错误信息
            return JsonResponse({'code': 400, 'msg': result.get('return_msg')})
    except Exception as e:
        # 若出现异常,记录错误信息并返回错误响应
        logger.error(f"Refund error: {e}")
        return JsonResponse({'code': 500, 'msg': 'Refund error'})
    

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2331949.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【BFT帝国】20250409更新PBFT总结

2411 2411 2411 Zhang G R, Pan F, Mao Y H, et al. Reaching Consensus in the Byzantine Empire: A Comprehensive Review of BFT Consensus Algorithms[J]. ACM COMPUTING SURVEYS, 2024,56(5).出版时间: MAY 2024 索引时间(可被引用): 240412 被引:…

Linux-CentOS-7—— 配置静态IP地址

文章目录 CentOS-7——配置静态IP地址VMware workstation的三种网络模式配置静态IP地址1. 编辑虚拟网络2. 确定网络接口名称3. 切换到网卡所在的目录4. 编辑网卡配置文件5. 查看网卡文件信息6. 重启网络服务7. 测试能否通网8. 远程虚拟主机(可选) 其他补…

Jupyter Lab 无法启动 Kernel 问题排查与解决总结

📄 Jupyter Lab 无法启动 Kernel 问题排查与解决总结 一、问题概述 🚨 现象描述: 用户通过浏览器访问远程服务器的 Jupyter Lab 页面(http://xx.xx.xx.xx:8891/lab)后,.ipynb 文件可以打开,但无…

算法训练之位运算

♥♥♥~~~~~~欢迎光临知星小度博客空间~~~~~~♥♥♥ ♥♥♥零星地变得优秀~也能拼凑出星河~♥♥♥ ♥♥♥我们一起努力成为更好的自己~♥♥♥ ♥♥♥如果这一篇博客对你有帮助~别忘了点赞分享哦~♥♥♥ ♥♥♥如果有什么问题可以评论区留言或者私信我哦~♥♥♥ ✨✨✨✨✨✨ 个…

C++设计模式+异常处理

#include <iostream> #include <cstring> #include <cstdlib> #include <unistd.h> #include <sstream> #include <vector> #include <memory> #include <stdexcept> // 包含异常类using namespace std;// 该作业要求各位写一…

checkra1n越狱出现的USB error -10问题解决

使用checkra1n进行越狱是出现&#xff1a; 解决办法(使用命令行进行越狱)&#xff1a; 1. cd /Applications/checkra1n.app/Contents/MacOS 2. ./checkra1n -cv 3. 先进入恢复模式 a .可使用爱思助手 b. 或者长按home,出现关机的滑条&#xff0c;同时按住home和电源键&#…

golang-defer延迟机制

defer延迟机制 defer是什么 defer是go中一种延迟调用机制。 执行时机 defer后面的函数只有在当前函数执行完毕后才能执行。 执行顺序 将延迟的语句按defer的逆序进行执行&#xff0c;也就是说先被defer的语句最后被执行&#xff0c;最后被defer的语句&#xff0c;最先被执…

【小沐学Web3D】three.js 加载三维模型(Angular)

文章目录 1、简介1.1 three.js1.2 angular.js 2、three.js Angular.js结语 1、简介 1.1 three.js Three.js 是一款 webGL&#xff08;3D绘图标准&#xff09;引擎&#xff0c;可以运行于所有支持 webGL 的浏览器。Three.js 封装了 webGL 底层的 API &#xff0c;为我们提供了…

一种替代DOORS在WORD中进行需求管理的方法 (二)

一、前景 参考&#xff1a; 一种替代DOORS在WORD中进行需求管理的方法&#xff08;基于WORD插件的应用&#xff09;_doors aspice-CSDN博客 二、界面和资源 WORD2013/WORD2016 插件 【已使用该工具通过第三方功能安全产品认证】&#xff1a; 1、 核心功能 1、需求编号和跟…

一个基于ragflow的工业文档智能解析和问答系统

工业复杂文档解析系统 一个基于ragflow的工业文档智能解析和问答系统,支持多种文档格式的解析、知识库管理和智能问答功能。 系统功能 1. 文档管理 支持多种格式文档上传(PDF、Word、Excel、PPT、图片等)文档自动解析和分块处理实时处理进度显示文档解析结果预览批量文档…

23种设计模式-行为型模式-访问者

文章目录 简介场景解决完整代码核心实现 总结 简介 访问者是一种行为设计模式&#xff0c;它能把算法跟他所作用的对象隔离开来。 场景 假如你的团队开发了一款能够使用图像里地理信息的应用程序。图像中的每个节点既能代表复杂实体&#xff08;例如一座城市&#xff09;&am…

组播网络构建:IGMP、PIM 原理及应用实践

IP组播基础 组播基本架构 组播IP地址 一个组播IP地址并不是表示具体的某台主机&#xff0c;而是一组主机的集合&#xff0c;主机声明加入某组播组即标识自己需要接收目的地址为该组播地址的数据IP组播常见模型分为ASM模型和SSM模型ASM&#xff1a;成员接收任意源组播数据&…

建筑兔零基础自学记录69|爬虫Requests-2

Requests库初步尝试 #导入requests库 import requests #requests.get读取百度网页 rrequests.get(http://www.baidu.com) #输出读取网页状态 print(r.status_code) #输出网页源代码 print(r.text) HTTP 状态码是三位数字&#xff0c;用于表示 HTTP 请求的结果。常见的状态码有…

NVIDIA PhysX 和 Flow 现已完全开源

NVIDIA PhysX SDK 在 3-Clause BSD 许可下开源已有六年半了&#xff0c;但其中并非所有内容都是开源的。直到最近&#xff0c;随着 GPU 模拟内核源代码在 GitHub 上的发布&#xff0c;这种情况才有所改变。以下是 NVIDIA 分享的消息&#xff0c;以及 Flow SDK 着色器实现的发布…

电脑DNS出错无法打开网页

目录 解决步骤 打开“控制面板”--》“查看网络状态和任务” 打开“更改适配器设置” 对WLAN右键&#xff0c;打开属性 打开“使用下面的DNS服务器地址”--》高级 添加“114.114.114.114”&#xff0c;点击确定 今天晚上突然网页打不开了&#xff0c;一开始我以为是网络的…

[Redis]redis-windows下载安装与使用

本篇记录windows redis下载安装与使用。 下载 官网下载方式(没windows版) https://redis.io/downloads/#stack 可以选择下载社区版Redis CE与增强版Redis Stack。 两者都不支持直接运行在windows上&#xff0c;需要Docker环境。 You can install Redis CE locally on your …

极氪汽车云原生架构落地实践

云原生架构落地实践的背景 随着极氪数字业务的飞速发展&#xff0c;背后的 IT 技术也在不断更新迭代。极氪极为重视客户对服务的体验&#xff0c;并将系统稳定性、业务功能的迭代效率、问题的快速定位和解决视为构建核心竞争力的基石。 为快速响应用户的需求&#xff0c;例如…

2025年AI开发学习路线

目录 一、基础阶段&#xff08;2-3个月&#xff09; 1. 数学与编程基础 2. 机器学习入门 二、核心技能&#xff08;3-4个月&#xff09; 1. 深度学习与框架 2. 大模型开发&#xff08;重点&#xff09; 三、进阶方向&#xff08;3-6个月&#xff09; 1. 多模态与智能体…

oracle 动态性能视图

Oracle 数据库中的 V$SQLAREA 是一个动态性能视图&#xff08;Dynamic Performance View&#xff09;&#xff0c;用于记录共享池&#xff08;Shared Pool&#xff09;中所有 SQL 语句的统计信息。每个 SQL 语句在共享池中存储为一个游标&#xff08;Cursor&#xff09;&#x…

Vue3+Vite+TypeScript+Element Plus开发-10.多用户动态加载菜单

系列文档目录 Vue3ViteTypeScript安装 Element Plus安装与配置 主页设计与router配置 静态菜单设计 Pinia引入 Header响应式菜单缩展 Mockjs引用与Axios封装 登录设计 登录成功跳转主页 多用户动态加载菜单 Pinia持久化 动态路由-配置 文章目录 目录 系列文档目…