Backend Development 7 min read

Integrating Alipay Payment Gateway in Python Projects

This article explains why third‑party payment is needed, outlines Alipay’s workflow, guides through obtaining APPID and generating public/private keys, and provides a complete Python implementation—including key handling, request signing, and API usage—to integrate Alipay payments into backend applications.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Integrating Alipay Payment Gateway in Python Projects

Before third‑party payment platforms, users had to sign contracts with banks for each transaction, which was cumbersome; third‑party services like Alipay streamline the process by handling signing and settlement.

Alipay’s payment flow involves the merchant obtaining Alipay’s public key and its own private key, sending a signed request, and receiving a response that includes order details on success or failure.

Configuration steps :

Obtain the APPID from the Alipay Open Platform.

Generate a public/private key pair using the online encryption tool in the developer console.

Download the generated private key and the application public key.

After acquiring the keys, you can integrate Alipay into a Python project using the following code.

<code>from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from urllib.parse import quote_plus
from base64 import decodebytes, encodebytes
import json

class AliPay:
    """Alipay payment interface (PC side)"""
    def __init__(self, appid, app_notify_url, app_private_key_path,
                 alipay_public_key_path, return_url, debug=False):
        self.appid = appid
        self.app_notify_url = app_notify_url
        self.app_private_key_path = app_private_key_path
        self.app_private_key = None
        self.return_url = return_url
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())
        self.alipay_public_key_path = alipay_public_key_path
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.importKey(fp.read())
        if debug is True:
            self.__gateway = "https://openapi.alipaydev.com/gateway.do"
        else:
            self.__gateway = "https://openapi.alipay.com/gateway.do"

    def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
        biz_content = {
            "subject": subject,
            "out_trade_no": out_trade_no,
            "total_amount": total_amount,
            "product_code": "FAST_INSTANT_TRADE_PAY",
        }
        biz_content.update(kwargs)
        data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)
        return self.sign_data(data)

    def build_body(self, method, biz_content, return_url=None):
        data = {
            "app_id": self.appid,
            "method": method,
            "charset": "utf-8",
            "sign_type": "RSA2",
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "version": "1.0",
            "biz_content": biz_content
        }
        if return_url is not None:
            data["notify_url"] = self.app_notify_url
            data["return_url"] = self.return_url
        return data

    def sign_data(self, data):
        data.pop("sign", None)
        unsigned_items = self.ordered_data(data)
        unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
        sign = self.sign(unsigned_string.encode("utf-8"))
        quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items)
        signed_string = quoted_string + "&sign=" + quote_plus(sign)
        return signed_string

    def ordered_data(self, data):
        complex_keys = []
        for key, value in data.items():
            if isinstance(value, dict):
                complex_keys.append(key)
        for key in complex_keys:
            data[key] = json.dumps(data[key], separators=(',', ':'))
        return sorted([(k, v) for k, v in data.items()])

    def sign(self, unsigned_string):
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string))
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign

    def _verify(self, raw_content, signature):
        key = self.alipay_public_key
        signer = PKCS1_v1_5.new(key)
        digest = SHA256.new()
        digest.update(raw_content.encode("utf8"))
        if signer.verify(digest, decodebytes(signature.encode("utf8"))):
            return True
        return False

    def verify(self, data, signature):
        if "sign_type" in data:
            data.pop("sign_type")
        unsigned_items = self.ordered_data(data)
        message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
        return self._verify(message, signature)
</code>

Instantiate the class with your APPID, notification URLs, and the paths to the private and public keys:

<code>def init_alipay():
    # Initialize Alipay
    alipay = AliPay(
        appid="appid",
        app_notify_url="回调地址",
        return_url="回调地址",
        app_private_key_path="私钥相对路径",
        alipay_public_key_path="公钥相对路径",
        debug=True  # payment environment
    )
    return alipay
</code>

Example API endpoint that creates a payment request and returns the gateway URL:

<code>async def get(self):
    alipay = init_alipay()
    # Pass a title, order number, and amount
    params = alipay.direct_pay("三方广告平台", order_no, money)
    url = f"https://openapi.alipaydev.com/gateway.do?{params}"
    return self.write(ret_json(url))
</code>

In summary, Alipay provides its own API documentation; the steps above show how to configure keys and use the provided Python class to perform payments directly from a backend service.

backendPythoncryptographyPayment IntegrationAlipay
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.