目录结构

libs
-alipay
-_init
.py
-pay.py
-setting.py
-secret
-private_key.pem
-public_key.pem

init.py

  1. from .pay import gateway,alipay

pay.py

from alipay import AliPay
from alipay.utils import AliPayConfig
from . import setting

alipay = AliPay(
    appid=setting.APPID,
    app_notify_url=None,  # 默认回调url
    app_private_key_string=setting.APP_PRIVATE_KEY_STRING,
    # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
    alipay_public_key_string=setting.ALIPAY_PUBLIC_KEY_STRING,
    # RSA 或者 RSA2
    sign_type=setting.SIGN_TYPE,
    # 默认False
    debug=setting.DEBUG,
    # 输出调试数据
    verbose=False,
    # 可选, 请求超时时间
    config=AliPayConfig(timeout=15)
)

gateway = setting.GATEWAY

setting.py

import os

os.path.join(os.path.dirname(__file__), 'secret', 'private_key.pem')
os.path.join(os.path.dirname(__file__), 'secret', 'public_key.pem')
APPID = "appid",
APP_PRIVATE_KEY_STRING = open(os.path.join(os.path.dirname(__file__), 'secret', 'private_key.pem')).read()
ALIPAY_PUBLIC_KEY_STRING = open(os.path.join(os.path.dirname(__file__), 'secret', 'public_key.pem')).read()
SIGN_TYPE = "RSA2",
DEBUG = True

GATEWAY = 'https://openapi.alipaydev.com/gateway.do?' if DEBUG else 'https://openapi.alipay.com/gateway.do?'

secret文件夹内的两个文件为应用私钥和支付宝公钥

使用(电脑网站支付)

# 如果你是Python 2用户(考虑考虑升级到Python 3吧),请确保非ascii的字符串为utf8编码:
subject = u"测试订单".encode("utf8")
# 如果你是 Python 3的用户,使用默认的字符串即可
subject = "测试订单"

# 电脑网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string
order_string = alipay.api_alipay_trade_page_pay(
    out_trade_no="20161112",
    total_amount=0.01,
    subject=subject,
    return_url="https://example.com",
    notify_url="https://example.com/notify" # 可选, 不填则使用默认notify url
)

使用(APP支付)

# App支付,将order_string返回给app即可
order_string = alipay.api_alipay_trade_app_pay(
    out_trade_no="20161112",
    total_amount=0.01,
    subject=subject,
    notify_url="https://example.com/notify" # 可选, 不填则使用默认notify url
)

使用(小程序支付)

# 小程序支付
alipay.api_alipay_trade_create(
    out_trade_no="20161112",
    total_amount=0.01,
    subject=subject,
    buyer_id="",
    notify_url="https://example.com/notify" # 可选
)