1. 使用python工具包
https://github.com/fzlee/alipay/blob/master/README.zh-hans.md
安装
从 1.3.0升级上来的用户, 请先卸载pycrypto:
pip uninstall pycrypto
安装python-alipay-sdk
pip install python-alipay-sdk --upgrade
生成密钥文件
openssl
OpenSSL> genrsa -out app_private_key.pem 2048 # 私钥
OpenSSL> rsa -in app_private_key.pem -pubout -out app_public_key.pem # 导出公钥
OpenSSL>exit
cat app_publict_key.pem 查看公钥的内容
将-----BEGIN PUBLIC KEY-----和-----END PUBLIC KEY-----中间的内容保存在支付宝的用户配置中(沙箱或者正式)
https://openhome.alipay.com/platform/appDaily.htm?tab=info
下载支付宝的公钥文件
将公钥的内容复制保存到一个文本文件中(alipay_pubilc_key.pem),注意需要在文本的首尾添加标记位(-----BEGIN PUBLIC KEY-----和-----END PUBLIC KEY-----) ,形如:
将刚刚生成的私钥app_private_key.pem和支付宝公钥alipay_public_key.pem放到我们的项目目录中
使用支付宝 python包的初始化
#业务处理:使用python skd 调用支付宝的支付接口
app_private_key_string = open('apps/order/app_private_key.pem').read()
alipay_public_key_string = open('apps/order/alipay_public_key.pem').read()
# print('&&&&&&&&&&&&&&&&&&'+app_private_key_string)
alipay = AliPay(
appid="2016101000653584",
app_notify_url=None, # 默认回调url
app_private_key_string=app_private_key_string,
# 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
alipay_public_key_string=alipay_public_key_string,
sign_type="RSA2", # RSA 或者 RSA2
debug = True # 默认False
)
支付接口
https://docs.open.alipay.com/270/alipay.trade.page.pay/
#调用支付接口
# 如果你是 Python 3的用户,使用默认的字符串即可
subject = "天天生鲜%s"%order_id
# 电脑网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string
total_pay = order.total_price + order.transit_price
order_string = alipay.api_alipay_trade_page_pay(
out_trade_no=order_id,
total_amount=str(total_pay),
subject=subject,
return_url=None,
notify_url=None # 可选, 不填则使用默认notify url
)
获取支付结果接口
https://docs.open.alipay.com/api_1/alipay.trade.query
循环获取支付结果的状态:
while True:
response = alipay.api_alipay_trade_query(out_trade_no=order_id)
# response = {
# "trade_no": "2017032121001004070200176844", # 支付宝交易号
# "code": "10000", # 接口调用是否成功
# "invoice_amount": "20.00",
# "open_id": "20880072506750308812798160715407",
# "fund_bill_list": [
# {
# "amount": "20.00",
# "fund_channel": "ALIPAYACCOUNT"
# }
# ],
# "buyer_logon_id": "csq***@sandbox.com",
# "send_pay_date": "2017-03-21 13:29:17",
# "receipt_amount": "20.00",
# "out_trade_no": "out_trade_no15",
# "buyer_pay_amount": "20.00",
# "buyer_user_id": "2088102169481075",
# "msg": "Success",
# "point_amount": "0.00",
# "trade_status": "TRADE_SUCCESS", # 支付结果
# "total_amount": "20.00"
# }
code = response.get('code')
if code == '10000' and response.get('trade_status') == 'TRADE_SUCCESS':
# 支付成功
# 获取支付宝交易号
print('支付成功')
trade_no = response.get('trade_no')
# 更新订单状态
order.trade_no = trade_no
order.order_status = 4 # 待评价
order.save()
# 返回结果
return JsonResponse({'res':3, 'message':'支付成功'})
elif code == '40004' or (code == '10000' and response.get('trade_status') == 'WAIT_BUYER_PAY'):
# 等待买家付款
# 业务处理失败,可能一会就会成功
import time
print('等待下次循环')
time.sleep(5)
continue
else:
# 支付出错
print(code)
return JsonResponse({'res':4, 'errmsg':'支付失败'})