python 微信支付API-v3版本(H5支付)

依赖包
pip install pycryptodome
pip install pycryptodomex
pip install requests
pip install pyjwt
import json
import random
import socket
import string
import time
from Cryptodome.PublicKey import RSA
from base64 import b64encode
from Cryptodome.Signature import pkcs1_15
from Cryptodome.Hash import SHA256
import requests
#生成签名函数
from django.http import JsonResponse


# 获取本机IP
def get_host_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('10.0.0.1', 8080))
    ip = s.getsockname()[0]
    s.close()
    return ip


# 获取加密
def get_sign(sign_str):
    rsa_key = RSA.importKey(open('apiclient_key.pem').read())
    signer = pkcs1_15.new(rsa_key)
    digest = SHA256.new(sign_str.encode('utf8'))
    sign = b64encode(signer.sign(digest)).decode('utf-8')
    return sign

class WXPay:
    """
    微信 H5支付
    """
    def __init__(self):
        self.appid = "wxcc4xxxx9dad392"
        self.mchid = "152xxxx361"
        self.url = 'https://api.mch.weixin.qq.com/v3/pay/transactions/h5'
        self.notify_url = "https://weixin.qq.com/"
        self.serial_no = '1F53E1B89F286xxxx41CCC1D8249B'#商户号证书序列号

    #统一下单
    def unified_order(self,order_no,total,description):
        data = {
            "mchid": self.mchid,
            "out_trade_no": order_no,
            "appid": self.appid,
            "description": description,
            "notify_url": self.notify_url,
            "amount": {
            "total": total,
            "currency": "CNY"
            },
            "scene_info": {
            "payer_client_ip": get_host_ip(),
            "h5_info": {
                "type": "Wap"
            }
            }
    }
        data = json.dumps(data)    # 只能序列化一次
        random_str = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(32))
        time_stamps = str(int(time.time()))
        """
            HTTP请求方法\n
            URL\n
            请求时间戳\n
            请求随机串\n
            请求报文主体\n
        """
        sign_str = f"POST\n{'/v3/pay/transactions/h5'}\n{time_stamps}\n{random_str}\n{data}\n"
        sign = get_sign(sign_str)

        headers = {
            'Content-Type': 'application/json; charset=UTF-8',
            'Authorization': 'WECHATPAY2-SHA256-RSA2048 ' + f'mchid="{self.mchid}",nonce_str="{random_str}",signature="{sign}",timestamp="{time_stamps}",serial_no="{self.serial_no}"'
        }
        response = requests.post(self.url, data=data, headers=headers)
        return response
    
    #jsapi支付
    # 返回{"prepay_id":"wx*************************"}
    # res = {
    #     "message": dict(
    #         package='prepay_id='+response.json()['prepay_id'],
    #         timeStamp=time_stamps,
    #         nonceStr=random_str,
    #         paySign=get_sign(f"{appid}\n{time_stamps}\n{random_str}\n{'prepay_id='+response.json()['prepay_id']}\n"),
    #         signType='RSA',
    #     ),
    #     "meta": {
    #         "msg": "",
    #         "status": 200
    #     }
    # }
    # return JsonResponse(res)


if __name__=="__main__":
   wx=WXPay()
   print(wx.unified_order("80480600",1,"订单支付").text)

在这里插入图片描述

你可能感兴趣的:(python)