Alipay SDK for Python
raw JSON → 3.7.1098 verified Thu Apr 16 auth: no python
The `alipay-sdk-python` library is the official Python SDK for integrating with Alipay's Open Platform APIs. It provides functionalities for various payment scenarios, including web, app, and QR code payments, as well as refund, query, and notification processing. Maintained by Alipay, it receives regular updates, typically several times a month, reflecting API changes and improvements. The current version is 3.7.1098.
pip install alipay-sdk-python Common errors
error ModuleNotFoundError: No module named 'alipay' ↓
cause Attempting to import classes from `alipay` directly (e.g., `from alipay import AliPay`) which was the import path for older versions of the SDK (v2.x and below).
fix
Update your imports to use the new package structure, primarily
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient and from alipay.aop.api.AlipayClientConfig import AlipayClientConfig. Refer to the quickstart example. error Alipay F21008: 签名验证失败 (Signature verification failed) ↓
cause This error indicates a mismatch in the cryptographic keys used for signing the request or verifying the response. Common causes include incorrect `app_private_key`, `alipay_public_key`, or `app_id`, or an incorrect key format (e.g., not PKCS8, or containing headers/footers).
fix
Double-check your
APP_ID, APP_PRIVATE_KEY, and ALIPAY_PUBLIC_KEY in your configuration. Ensure the private key is in PKCS8 format without headers/footers. Also, confirm you are using the correct keys for the specified Alipay environment (sandbox vs. production). error Alipay F40001: Missing Required Arguments: app_id ↓
cause Essential configuration parameters like `app_id` are not provided or are empty when initializing `AlipayClientConfig` or making an API call.
fix
Ensure that
alipay_client_config.app_id is set to your actual Alipay App ID. Review all required configuration parameters for the AlipayClientConfig and for the specific API request you are making, as some biz_content fields might also be mandatory. Warnings
breaking The `alipay-sdk-python` library underwent a significant API refactor around version 3.0.0. Older versions (2.x and below) used a different package structure and client initialization pattern (e.g., `from alipay import AliPay`). Version 3.x and above use `from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient`. ↓
fix Update your import paths and client initialization logic to match the 3.x API. Refer to the official documentation or the quickstart for the correct patterns.
gotcha Alipay private keys must be in PKCS8 format without headers/footers (`-----BEGIN RSA PRIVATE KEY-----` / `-----END RSA PRIVATE KEY-----`). If your private key is generated with headers, you must remove them before providing it to the SDK, or convert it to PKCS8. ↓
fix Ensure your `app_private_key` value is a plain string containing only the base64 encoded private key material. For example, if you have a key file, open it, copy only the content between `BEGIN` and `END` lines, and remove all newlines.
gotcha Incorrect configuration of `server_url` or mismatch between keys (App Private Key / Alipay Public Key) and the environment (sandbox vs. production) is a frequent cause of 'Signature verification failed' errors or other API communication issues. ↓
fix Verify that `alipay_client_config.server_url` points to the correct environment (`https://openapi.alipaydev.com/gateway.do` for sandbox, `https://openapi.alipay.com/gateway.do` for production) and that the corresponding `app_id`, `app_private_key`, and `alipay_public_key` are valid for that environment.
gotcha Alipay's asynchronous notifications (`notify_url`) require strict signature verification to prevent spoofing. Failing to correctly verify the signature on incoming notifications can lead to security vulnerabilities. ↓
fix Always use the SDK's built-in signature verification utility (e.g., `alipay_client.verify_notification`) when processing `notify_url` callbacks. Do not manually parse or trust notification data without verification.
Imports
- AlipayClientConfig
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig - DefaultAlipayClient wrong
from alipay import AliPaycorrectfrom alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient - AlipayTradePagePayRequest
from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
Quickstart
import os
from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
# 1. Configuration (replace with your actual keys or use environment variables)
APP_ID = os.environ.get('ALIPAY_APP_ID', 'YOUR_APP_ID')
APP_PRIVATE_KEY = os.environ.get('ALIPAY_PRIVATE_KEY', 'YOUR_APP_PRIVATE_KEY')
ALIPAY_PUBLIC_KEY = os.environ.get('ALIPAY_ALIPAY_PUBLIC_KEY', 'YOUR_ALIPAY_PUBLIC_KEY')
alipay_client_config = AlipayClientConfig()
alipay_client_config.server_url = 'https://openapi.alipaydev.com/gateway.do' # Use 'https://openapi.alipay.com/gateway.do' for production
alipay_client_config.app_id = APP_ID
alipay_client_config.app_private_key = APP_PRIVATE_KEY
alipay_client_config.alipay_public_key = ALIPAY_PUBLIC_KEY
alipay_client_config.encrypt_type = 'AES' # Optional: set encryption type if needed
alipay_client = DefaultAlipayClient(alipay_client_config=alipay_client_config)
# 2. Prepare API Request
request = AlipayTradePagePayRequest()
request.biz_content = (
'{"out_trade_no":"20230817010101001",' # Your unique order ID
'"total_amount":"88.88",' # Total amount
'"subject":"Test Product",' # Product subject
'"product_code":"FAST_INSTANT_TRADE_PAY"}'
)
request.return_url = 'http://localhost:8000/alipay/return' # URL for browser redirect after payment
request.notify_url = 'http://localhost:8000/alipay/notify' # URL for async server-to-server notification
# 3. Execute Request and get payment form
try:
# page_execute returns an HTML form string for browser redirection
response_html = alipay_client.page_execute(request=request)
print("Payment HTML form generated successfully:")
print(response_html) # In a web app, you would render this HTML to the user
except Exception as e:
print(f"An error occurred: {e}")