Backend Development 7 min read

Integrating Alipay Payment in Python Projects

This article explains why third‑party payment platforms like Alipay are used, describes Alipay's payment flow, outlines the configuration steps to obtain APPID and keys, and provides a complete Python implementation for integrating Alipay into backend services.

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

Third‑party payment platforms like Alipay simplify online transactions by handling user‑bank contracts, saving time and effort.

Alipay’s payment flow involves the merchant using Alipay’s public key and its own private key to sign requests; Alipay verifies, processes the payment, and returns order details or error messages.

The configuration steps are:

1. Obtain the APPID from the Alipay Open Platform.

2. Generate a private key online via the development assistant.

3. Retrieve the public key from the application settings.

After acquiring the keys, you can integrate Alipay in a Python project by creating a payment class that builds request parameters, signs them with RSA2, and sends them to Alipay’s gateway.

Example implementation:

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)"""
    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())
        self.__gateway = ("https://openapi.alipaydev.com/gateway.do"
                          if debug else "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 = [k for k, v in data.items() if isinstance(v, dict)]
        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):
        signer = PKCS1_v1_5.new(self.app_private_key)
        signature = signer.sign(SHA256.new(unsigned_string))
        return encodebytes(signature).decode("utf8").replace("\n", "")

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

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

Initialize the class with your APPID, notification URLs, and the paths to the private and public key files, then call direct_pay to obtain a signed URL that redirects the user to Alipay’s payment page.

def init_alipay():
    alipay = AliPay(
        appid="your_appid",
        app_notify_url="your_notify_url",
        return_url="your_return_url",
        app_private_key_path="path/to/your_private_key.pem",
        alipay_public_key_path="path/to/alipay_public_key.pem",
        debug=True
    )
    return alipay

async def get(self):
    alipay = init_alipay()
    params = alipay.direct_pay("Product Name", order_no, amount)
    url = f"https://openapi.alipaydev.com/gateway.do?{params}"
    return self.write(ret_json(url))

This code provides a ready‑to‑use Alipay integration for Python back‑end services.

backendPythonAPIcryptographyPayment 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.