Python使用SDK(python-alipay-sdk) 与支付宝API对接

一. python-alipay-sdk 安装下载:

卸载pycrypto(如有)

pip uninstall pycrypto


安装python-alipay-sdk

pip install python-alipay-sdk


二.生成密钥文件

1. 使用OpenSSL

openssl

2. 生成私钥

genrsa -out app_private_key.pem   2048 

3. 生成公钥

rsa -in app_private_key.pem -pubout -out app_public_key.pem

4. 退出OpenSSL

exit

 

三.登录支付宝绑定己方公钥, 获取后方公钥(沙箱):
https://sandbox.alipaydev.com/user/accountDetails.htm?currentBar=1


四.初始化:
项目文件中,定位己方私钥和以及他方公钥,并进行初始化.

import os
from alipay import AliPay
from django.conf import settings


        # 进行alipay初始化

        # 配置地址
        private_path = os.path.join(settings.BASE_DIR, 'apps/order/app_private_key.pem')
        public_path = os.path.join(settings.BASE_DIR, 'apps/order/alipay_public_key.pem')
        # 获取公私钥字符串
        app_private_key_string = open(private_path).read()
        alipay_public_key_string = open(public_path).read()

        alipay = AliPay(
            appid="2016101100664228",
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",
            debug=True,  # 上线则改为False , 沙箱True
        )

五.使用:   

        # 调用接口(传参订单号和总价,标题)
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(total_pay),
            subject='支付订单:%s' % order_id,
            return_url=None,
            notify_url=None,
        )

        # 拼接应答地址
        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string

返回应答pay_url即可.

posted @ 2019-10-14 02:04  Jrri  阅读(5139)  评论(5编辑  收藏  举报