Of course! Using RSA for Alipay in Python is a common requirement for integrating with their payment gateway. The core of this process involves signing requests and verifying notifications using asymmetric cryptography.

Here's a comprehensive guide covering the concepts, necessary libraries, and a step-by-step code example.
Core Concepts: Why RSA?
- Security: Alipay uses RSA (specifically, SHA1withRSA or SHA256withRSA) to ensure that a request or notification truly comes from them and hasn't been tampered with.
- Signing (Alipay -> Merchant):
- When Alipay sends a notification (like a payment success callback) to your server, it includes a signature (
signfield). - You use Alipay's public key to verify this signature. If the verification is successful, you can trust that the data is authentic and came from Alipay.
- When Alipay sends a notification (like a payment success callback) to your server, it includes a signature (
- Signing (Merchant -> Alipay):
- When your application sends a request to Alipay's API (like creating a payment order), you must sign your parameters.
- You use your own private key to create this signature.
- Alipay uses your public key (which you must have uploaded to their developer console) to verify your request's signature.
Step 1: Prerequisites & Keys
You need two sets of keys:
-
Your Merchant Keys:
- Private Key (
app_private_key.pem): Keep this secret and secure on your server. It's used to sign requests you send to Alipay. - Public Key (
app_public_key.pem): This is the corresponding public key. You must upload this public key to the Alipay developer console (in the "应用公钥" or "应用证书" section) so Alipay can verify your requests.
- Private Key (
-
Alipay's Keys:
- Alipay Public Key (
alipay_public_key.pem): Alipay provides this key. You must download it from the Alipay developer console (in the "支付宝公钥" or "支付宝证书" section). You use this key to verify notifications sent from Alipay.
- Alipay Public Key (
How to Generate Keys: You can use OpenSSL to generate a 2048-bit RSA key pair:
# Generate private key openssl genrsa -out app_private_key.pem 2048 # Generate public key from the private key openssl rsa -in app_private_key.pem -pubout -out app_public_key.pem
Then, upload app_public_key.pem to Alipay and download alipay_public_key.pem from Alipay.
Step 2: Install Necessary Python Libraries
We'll use the official alipay-python-sdk and the standard library cryptography for key handling.
pip install alipay-python-sdk pip install cryptography
Step 3: Python Code Example
This example demonstrates:
- Initializing the Alipay client with your keys.
- Signing parameters for an API request (e.g., creating a trade page).
- Verifying a notification (e.g., a payment success callback) from Alipay.
import json
from datetime import datetime
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
from alipay import AliPay
from alipay.utils import AliPayConfig
# --- 1. Load Keys ---
# IMPORTANT: Replace these with the actual paths to your key files.
# In a real application, load these from environment variables or a secure config store.
# Your merchant's private key (for signing requests to Alipay)
with open('app_private_key.pem', 'rb') as f:
app_private_key_string = f.read()
# Alipay's public key (for verifying notifications from Alipay)
with open('alipay_public_key.pem', 'rb') as f:
alipay_public_key_string = f.read()
# --- 2. Initialize Alipay Client ---
# The SDK handles the low-level details of signing and verifying.
# You just need to provide the keys and app information.
alipay = AliPay(
appid="YOUR_APP_ID", # Your Alipay App ID
app_notify_url=None, # Default callback URL for asynchronous notifications
app_private_key_string=app_private_key_string,
# The public key string you uploaded to Alipay
alipay_public_key_string=alipay_public_key_string,
sign_type="RSA2", # Use RSA2 (SHA256withRSA) for better security
debug=False # Set to True to use the Alipay sandbox environment
)
# --- 3. Example A: Sign Parameters for an API Request ---
# This is what you do when you want to create a payment order.
# The SDK does this automatically when you call a method like `alipay.page_exec()`.
# This example shows the manual process for understanding.
# The parameters you want to send to Alipay
order_params = {
"out_trade_no": f"ORDER_{datetime.now().strftime('%Y%m%d%H%M%S')}",
"total_amount": "0.01",
"subject": "Test Product",
"product_code": "FAST_INSTANT_TRADE_PAY",
"time_expire": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
# The SDK automatically signs these parameters when you call an API.
# Let's simulate the core signing logic.
# The SDK concatenates parameters into a specific format and then signs.
# For demonstration, we'll use a simplified string.
# In reality, the SDK handles the complex parameter sorting and concatenation.
# The actual string to be signed is created by the SDK.
# This is a simplified representation.
string_to_sign = f"out_trade_no={order_params['out_trade_no']}&total_amount={order_params['total_amount']}&subject={order_params['subject']}&..."
# Manually signing with the private key (the SDK does this for you)
# Note: The SDK handles key loading and padding correctly.
# This is for educational purposes.
private_key = serialization.load_pem_private_key(
app_private_key_string,
password=None,
)
signature_bytes = private_key.sign(
string_to_sign.encode('utf-8'),
padding.PKCS1v15(),
hashes.SHA256()
)
# The signature is base64 encoded for sending in the request
signature = signature_bytes.hex() # The SDK uses base64, let's use hex for this example
print("--- Signing a Request ---")
print(f"Original Params: {json.dumps(order_params, indent=2)}")
print(f"Generated Signature: {signature}")
print("\nIn a real request, this signature and the params would be sent to Alipay.")
print("The SDK handles this entire process when you call `alipay.page_exec()`.\n")
# --- 4. Example B: Verify a Notification from Alipay ---
# This is what you do in your server's callback endpoint.
# Alipay sends a POST request with parameters, including a 'sign' field.
# Simulated data received from Alipay's notification callback
# This is a simplified version. In reality, it comes as a form POST.
alipay_notification_data = {
"app_id": "YOUR_APP_ID",
"out_trade_no": f"ORDER_{datetime.now().strftime('%Y%m%d%H%M%S')}",
"buyer_id": "2088102147424123",
"trade_no": "2025102622001412345678901234",
"trade_status": "TRADE_SUCCESS",
"total_amount": "0.01",
"gmt_payment": "2025-10-26 12:00:00",
"sign": "YOUR_RECEIVED_SIGNATURE_FROM_ALIPAY_NOTIFICATION", # This is the signature you need to verify
"sign_type": "RSA2"
}
# Extract the parameters and the signature
params_to_verify = {k: v for k, v in alipay_notification_data.items() if k != 'sign'}
received_signature = alipay_notification_data['sign']
# The SDK provides a convenient method to verify the notification.
# It sorts the parameters, concatenates them, and verifies the signature using Alipay's public key.
is_verified = alipay.verify(params_to_verify, received_signature, sign_type=alipay_notification_data['sign_type'])
print("--- Verifying a Notification ---")
print(f"Notification Data: {json.dumps(alipay_notification_data, indent=2)}")
print(f"Verification Result: {is_verified}")
if is_verified:
print("\n✅ SUCCESS: The notification is authentic and has not been tampered with.")
# Now you can safely process the business logic, e.g., update your database.
print(f"Payment successful for order: {alipay_notification_data['out_trade_no']}")
else:
print("\n❌ FAILED: The notification is NOT valid. Do NOT trust this data!")
Important Considerations
-
RSA vs. RSA2:
- RSA: Uses SHA1 for hashing. It's considered less secure and is being phased out.
- RSA2: Uses SHA256 for hashing. This is the recommended and more secure option. Always use
sign_type="RSA2"in your configuration.
-
SDK is Your Friend: The
alipay-python-sdkis highly recommended because it abstracts away the complexities of:- Parameter sorting and concatenation (which follows a strict format).
- URL encoding.
- Key loading and handling.
- Choosing the correct padding and hashing algorithm.
-
Security Best Practices:
- Never hardcode keys in your source code. Load them from environment variables, a secrets manager, or a secure configuration file.
- Keep your private key secure. If it's compromised, an attacker can impersonate your application to Alipay.
- Validate all data from Alipay, even after the signature is verified. Don't trust
total_amountblindly; compare it with the amount in your own system.
-
Notifications (Asynchronous vs. Synchronous):
- Synchronous: The user is redirected back to your site after paying. The result is in the URL (
params). You should still verify this signature. - Asynchronous: Alipay sends a POST request to your
notify_url. This is more reliable because it doesn't depend on the user's browser. You must verify the signature on this endpoint. The SDK'sverify()method is designed for this.
- Synchronous: The user is redirected back to your site after paying. The result is in the URL (
