pip install aiohttp
pip install pycryptodomex #windows環境
准備:已開通移動應用的appid、v3秘匙、證書序列和私匙
微信開放平台:https://open.weixin.qq.com/cgi-bin/index
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(幣種)
}
簽名串一共有五行,每一行為一個參數。行尾以 \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
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()