100 lines
3.1 KiB
Python
100 lines
3.1 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
|
||
"""
|
||
发起支付模块
|
||
"""
|
||
|
||
import json
|
||
import time
|
||
import random
|
||
import string
|
||
import asyncio
|
||
from .api import YsmPayApi
|
||
|
||
def generate_nonce_str(length=10):
|
||
"""生成随机字符串"""
|
||
chars = string.ascii_letters + string.digits
|
||
return ''.join(random.choice(chars) for _ in range(length))
|
||
|
||
async def create_payment(appid, appsecret, order_id, description, amount,
|
||
notify_url, nopay_url, callback_url, pay_type=1):
|
||
"""
|
||
创建支付请求(异步)
|
||
|
||
Args:
|
||
appid: 支付通道ID
|
||
appsecret: 密钥
|
||
order_id: 商户订单号
|
||
description: 订单描述
|
||
amount: 支付金额(单位:分)
|
||
notify_url: 异步回调地址
|
||
nopay_url: 未支付跳转地址
|
||
callback_url: 支付成功跳转地址
|
||
pay_type: 支付类型,默认为1(微信内)
|
||
|
||
Returns:
|
||
str: 支付链接
|
||
"""
|
||
# 构造支付请求数据
|
||
data = {
|
||
'appid': appid, # 支付通道ID
|
||
'mch_orderid': order_id, # 商户网站订单号
|
||
'description': description, # 订单标题
|
||
'total': amount, # 订单金额(分)
|
||
'notify_url': notify_url, # 异步通知地址
|
||
'nopay_url': nopay_url, # 未支付跳转地址
|
||
'callback_url': callback_url, # 支付成功跳转地址
|
||
'time': int(time.time()), # 时间戳
|
||
'nonce_str': f"abc{int(time.time())}", # 随机字符串
|
||
'payType': pay_type, # 支付类型
|
||
}
|
||
|
||
# 生成签名
|
||
data['sign'] = YsmPayApi.hash_sign(data, appsecret)
|
||
|
||
# 发起支付请求
|
||
url = 'https://www.yishoumi.cn/u/payment' # 支付网关
|
||
response = await YsmPayApi.http_post(url, json.dumps(data))
|
||
|
||
# 解析响应
|
||
result = json.loads(response) if response else None
|
||
|
||
# 返回支付链接
|
||
if result and 'url' in result:
|
||
return result['url']
|
||
else:
|
||
# 返回错误信息以便调用者处理
|
||
if result and 'msg' in result:
|
||
raise Exception(f"支付创建失败: {result['msg']} (错误代码: {result.get('code', 'unknown')})")
|
||
else:
|
||
raise Exception("支付创建失败: 无响应或响应格式错误")
|
||
|
||
async def main():
|
||
# 示例使用
|
||
appid = 'YSMcd16b45d' # 支付通道ID
|
||
appsecret = '899850e778e8d2b53e4c4a4e88695688' # AppSecret
|
||
|
||
# 生成订单号
|
||
order_id = f"123321{int(time.time())}"
|
||
|
||
# 创建支付
|
||
pay_url = await create_payment(
|
||
appid=appid,
|
||
appsecret=appsecret,
|
||
order_id=order_id,
|
||
description="快充数据线",
|
||
amount=100, # 1元
|
||
notify_url="http://abc.com/notify.php",
|
||
nopay_url="http://abc.com/notify.php",
|
||
callback_url="http://abc.com/notify.php",
|
||
pay_type=1 # 微信内支付
|
||
)
|
||
|
||
if pay_url:
|
||
print(f"支付链接: {pay_url}")
|
||
else:
|
||
print("创建支付失败")
|
||
|
||
if __name__ == "__main__":
|
||
asyncio.run(main()) |