python实现,微信V3支付。签名。

pip install aiohttp
pip install pycryptodomex  #windows环境
准备:已开通移动应用的appid、v3秘匙、证书序列和私匙
微信开放平台:https://open.weixin.qq.com/cgi-bin/index

一、根据官方文档准备好 body数据。这里使用app支付(https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_2_1.shtml)。

url = "https://api.mch.weixin.qq.com/v3/pay/transactions/app"
body = {
	"appid": "appid", 
	"mchid": "商户号", 
	"notify_url": "支付通知url", 
	"description": "华联-方便面", 
	"out_trade_no": "平台订单号(唯一)", 
	"time_expire": "2021-03-11T09:30:48+08:00",  #支付订单失效时间
	"amount": {"total": 1, "currency": "CNY"}    #total(分)、currency(币种)
}

二、生成签名(https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay4_0.shtml)

签名串一共有五行,每一行为一个参数。行尾以 \n结束,包括最后一行。如果参数本身以\n结束,也需要附加一个\n。

HTTP请求方法\n
URL\n
时间戳\n
随机字符串\n
请求报文主体\n

def sign_str(method, url, timestamp, nonce_str, body):
    """
    拼接sign字符串
    """
    sign_list = [
        method,
        url,
        timestamp,
        nonce_str,
        body
    ]
    return '\n'.join(sign_list) + '\n'
#生成sign
def calculate_sign(body, method, url, timestamp, nonce_str):
    a = sign_str(method, url, timestamp, nonce_str, json.dumps(body))
    signer = pkcs1_15.new(RSA.importKey(open(r"apiclient_key.pem").read()))
    signature = signer.sign(SHA256.new(a.encode("utf-8")))
    sign = encodebytes(signature).decode("utf-8").replace("\n", "")
    return sign

三、请求headers

sign = calculate_sign(body, "POST", self.url, timestamp, nonce_str)

Authorization = 'WECHATPAY2-SHA256-RSA2048 ' \
            'mchid="{mchid}",' \
            'nonce_str="{nonce_str}",' \
            'signature="{sign}",' \
            'timestamp="{timestamp}",' \
            'serial_no="{serial_no}"'.\
            format(mchid="商户号",
                   nonce_str="随机字符串(必须和签名中一致)",
                   sign=sign,
                   timestamp="时间戳(必须和签名中一致)",
                   serial_no="证书序列号"
                  )
headers = {
    'Content-Type': "application/json",
    'Accept': 'application/json',
    'Authorization': Authorization,
}

四、生成订单(请求url)

async def send_post(self, body):
    async with aiohttp.ClientSession() as session:
        async with session.post(url, data = json.dumps(body), headers = self.headers) as response:
            return await response.json()
posted @ 2021-03-11 11:32  做个笔记  阅读(1190)  评论(0编辑  收藏  举报