How to implement WeChat payment function code example in Python

        

        WeChat Pay is an internet-based mobile payment service provided by WeChat, the Chinese instant messaging tool. Users can make online payments, transfers and collections on the WeChat platform through WeChat Pay. WeChat Pay supports a variety of payment methods, including bank card payment, WeChat wallet balance payment, scan code payment, etc. Users can use WeChat Pay to purchase goods, pay bills, transfer money to friends, etc. WeChat Pay is very popular in mainland China and is also accepted in some other countries and regions. The development of WeChat Pay provides users with a more convenient and secure payment method.

The following is a code example (written in Python) for accessing WeChat payment:

import requests
import json
from hashlib import md5

# 配置参数
appid = 'your_appid'
mch_id = 'your_mch_id'
key = 'your_key'

# 统一下单API
url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'

# 构造请求数据
data = {
    'appid': appid,
    'mch_id': mch_id,
    'nonce_str': 'your_nonce_str',
    'body': '订单描述',
    'out_trade_no': 'your_out_trade_no',
    'total_fee': 'your_total_fee',
    'spbill_create_ip': 'your_client_ip',
    'notify_url': 'your_notify_url',
    'trade_type': 'JSAPI',
    'openid': 'your_openid',
}

# 生成签名
sign = ''
data_items = sorted(data.items(), key=lambda x: x[0])
for k, v in data_items:
    sign += '{}={}&'.format(k, v)
sign += 'key={}'.format(key)
sign = md5(sign.encode('utf-8')).hexdigest().upper()
data['sign'] = sign

# 发送请求
response = requests.post(url, data=xml_data)
result = response.text

# 解析响应
result_data = {}
xml_data = result.encode('utf-8')
tree = ET.fromstring(xml_data)
for child in tree:
    result_data[child.tag] = child.text

print(result_data)

Please note the following parameters in the replacement code:

  • your_appid: AppID applied for on the WeChat open platform.
  • your_mch_id: Merchant number applied for on WeChat Pay Merchant Platform.
  • your_key: API key set on the WeChat Pay merchant platform.
  • your_nonce_str: Random string, which can be generated by yourself.
  • your_out_trade_no: Merchant order number, uniqueness must be ensured.
  • your_total_fee: The total amount of the order, in cents.
  • your_client_ip: Client IP address.
  • your_notify_url: Payment result notification address.
  • your_trade_type: Transaction type, such as 'JSAPI'.
  • your_openid: The user’s unique identifier under the official account.

This code example demonstrates how to perform a unified order operation with WeChat Pay and generate a signature. Please modify the parameters according to the actual situation and ensure that the WeChat payment related parameters are correctly configured.

Guess you like

Origin blog.csdn.net/m0_37649480/article/details/135416689