Alipay Integration¶
Alipay is China's leading digital payment platform with over 1 billion users.
Features¶
- QR Code Payments: Scan to pay in-store
- In-App Payments: Pay within your mobile app
- Website Payments: Redirect to Alipay for payment
- Express Checkout: One-touch payment for returning users
- Multi-Currency: Support for CNY and major foreign currencies
Prerequisites¶
- Alipay merchant account
- Completed business verification
- API credentials from Alipay Developer Center
Configuration¶
Environment Variables¶
ALIPAY_APP_ID=your_app_id
ALIPAY_PRIVATE_KEY=your_private_key
ALIPAY_PUBLIC_KEY=alipay_public_key
ALIPAY_GATEWAY_URL=https://openapi.alipay.com/gateway.do
Config File¶
[payment.alipay]
enabled = true
app_id = "${ALIPAY_APP_ID}"
private_key = "${ALIPAY_PRIVATE_KEY}"
public_key = "${ALIPAY_PUBLIC_KEY}"
gateway_url = "https://openapi.alipay.com/gateway.do"
sandbox = false
API Usage¶
Create Payment (Website)¶
POST /api/v1/payments
Content-Type: application/json
Authorization: Bearer <token>
{
"gateway": "alipay",
"amount": "299.00",
"currency": "CNY",
"payment_method": "web",
"subject": "Product Purchase",
"body": "Order #12345",
"return_url": "https://yoursite.com/payment/success",
"notify_url": "https://yoursite.com/webhooks/alipay"
}
Response:
Redirect the customer to payment_url to complete payment.
Create Payment (Mobile App)¶
POST /api/v1/payments
{
"gateway": "alipay",
"amount": "299.00",
"currency": "CNY",
"payment_method": "app",
"subject": "Product Purchase"
}
Response:
Pass order_string to your mobile app to initiate Alipay SDK payment.
Query Payment Status¶
Webhook Notifications¶
Alipay sends async notifications to your notify_url:
POST https://yoursite.com/webhooks/alipay
Content-Type: application/x-www-form-urlencoded
trade_status=TRADE_SUCCESS
out_trade_no=your_order_id
trade_no=alipay_trade_id
total_amount=299.00
...
Verify the notification signature before processing.
Payment Status¶
| Status | Description |
|---|---|
WAIT_BUYER_PAY |
Awaiting customer payment |
TRADE_CLOSED |
Payment window expired or refunded |
TRADE_SUCCESS |
Payment completed |
TRADE_FINISHED |
Transaction complete, no refunds allowed |
Refunds¶
Testing¶
Use Alipay sandbox:
Sandbox buyer account: sandbox_buyer@alipay.com
Best Practices¶
- Signature Verification: Always verify Alipay signatures
- Idempotency: Handle duplicate notifications gracefully
- Timeout Handling: Alipay payments timeout after 15 minutes
- Mobile Optimization: Ensure mobile-friendly payment flow