杰瑞科技汇

python alipay notify

Of course! Handling Alipay's asynchronous notification (often called "notify" or "notify_url") is a critical part of any integration. It confirms that a payment has been successfully completed on Alipay's servers and allows your server to update your database, trigger other actions, etc.

python alipay notify-图1
(图片来源网络,侵删)

Here’s a comprehensive guide on how to handle Alipay's asynchronous notification in Python, covering the concepts, code examples, and best practices.

The Core Concept: Asynchronous Notification

When a user completes a payment on the Alipay page, Alipay redirects them back to your website. This is a synchronous response and can be faked. For a transaction to be considered truly successful, your server must receive an asynchronous notification from Alipay's servers to a URL you specify (the notify_url).

This process is more secure because:

  • It's server-to-server.
  • Alipay signs the notification, so you can verify that it genuinely came from Alipay.
  • It's not dependent on the user's browser or their ability to successfully return to your site.

Prerequisites

  1. Alipay Developer Account: You need an account on the Alipay Open Platform.
  2. Application Created: Create an application (e.g., a "Web Application") in the Alipay developer console.
  3. App ID & Keys: Get your AppID, App Private Key, and Alipay Public Key. You'll generate these in the Alipay console.
  4. Notify URL: You have a publicly accessible URL on your server that Alipay will send notifications to (e.g., https://yourdomain.com/alipay/notify).
  5. Python Library: We'll use the official alipay-python-sdk library, which simplifies the process of generating requests and verifying signatures.

Install the library:

python alipay notify-图2
(图片来源网络,侵删)
pip install alipay-python-sdk

Step-by-Step Implementation

Here’s a complete, practical example using Flask for the web server. The principles are the same for Django, FastAPI, or any other Python web framework.

Step 3.1: Configure Your Alipay Client

Create a configuration file or module to set up your Alipay client. You need to provide your private key and Alipay's public key for verification.

alipay_config.py

from alipay import AliPay
from alipay.utils import AliPayConfig
# IMPORTANT: Store your keys securely, e.g., in environment variables
# or a configuration management system.
APP_ID = '2025001100000001'  # Replace with your App ID
ALIPAY_PUBLIC_KEY = """-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy... (Your Alipay Public Key) ...-----END PUBLIC KEY-----"""
# Your application's private key
APP_PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAy... (Your App Private Key) ...-----END RSA PRIVATE KEY-----"""
# Notify URL (for reference, you'll set this in the Alipay dashboard)
NOTIFY_URL = 'https://your-domain.com/alipay/notify'
# Return URL (where the user is redirected after payment)
RETURN_URL = 'https://your-domain.com/payment/success'
# Initialize the Alipay client
alipay = AliPay(
    appid=APP_ID,
    app_notify_url=NOTIFY_URL,
    app_auth_token=None,  # Not needed for direct payment
    app_private_key_string=APP_PRIVATE_KEY,
    alipay_public_key_string=ALIPAY_PUBLIC_KEY,
    sign_type="RSA2",  # Recommended
    debug=False,  # Set to True for Alipay's sandbox environment
    verbose=False,
    config=AliPayConfig(timeout=15) # Set a timeout for requests
)

Step 3.2: Create the Payment Page (Frontend)

This page will have a button that initiates the payment by redirecting the user to Alipay.

python alipay notify-图3
(图片来源网络,侵删)

templates/pay.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">Pay with Alipay</title>
</head>
<body>
    <h1>Alipay Payment Demo</h1>
    <p>Click the button below to pay 0.01 RMB.</p>
    <form action="/alipay/create" method="POST">
        <input type="hidden" name="subject" value="Test Product">
        <input type="hidden" name="out_trade_no" value="{{ out_trade_no }}">
        <input type="hidden" name="total_amount" value="0.01">
        <button type="submit">Pay with Alipay</button>
    </form>
</body>
</html>

Step 3.3: Create the Backend (Flask App)

This is the core of the solution. We need three routes:

  1. Create Payment: Generates the Alipay payment page URL.
  2. Handle Notify URL: The endpoint for Alipay's asynchronous notifications.
  3. Handle Return URL: The endpoint for the user's synchronous return.

app.py

import os
import uuid
from flask import Flask, request, jsonify, render_template, redirect, url_for
from alipay_config import alipay
app = Flask(__name__)
# IMPORTANT: Use a secret key in a real application!
app.secret_key = 'a_very_secret_key_that_should_be_changed' 
# --- Route to create the payment ---
@app.route('/alipay/create', methods=['POST'])
def create_payment():
    # Get order details from the form
    subject = request.form.get('subject')
    out_trade_no = request.form.get('out_trade_no') # Your internal order ID
    total_amount = request.form.get('total_amount')
    # If you don't provide an out_trade_no, the SDK might generate one,
    # but it's better to generate it yourself on the server.
    if not out_trade_no:
        out_trade_no = str(uuid.uuid4())
    # Generate the payment page URL
    # The 'return_url' is where Alipay will redirect the user after payment.
    # The 'notify_url' is where Alipay will send the async notification.
    # You can set notify_url globally in the Alipay client or per request.
    payment_url = alipay.api_alipay_trade_page_pay(
        out_trade_no=out_trade_no,
        total_amount=total_amount,
        subject=subject,
        return_url="http://127.0.0.1:5000/payment/success", # User's redirect URL
        notify_url="http://127.0.0.1:5000/alipay/notify"  # Your server's notify URL
    )
    # Redirect the user to Alipay's payment page
    return redirect(payment_url)
# --- Route to handle the user's return (Synchronous) ---
@app.route('/payment/success')
def payment_success():
    # This is NOT a reliable way to confirm payment!
    # It's just for user experience. You MUST check the notify_url.
    # Alipay will send the trade_no and out_trade_no as query parameters.
    trade_no = request.args.get('trade_no')
    out_trade_no = request.args.get('out_trade_no')
    # You can show a success page here
    return f"Payment successful! Your order ID is {out_trade_no}. Alipay trade ID: {trade_no}. <a href='/'>Go Home</a>"
# --- Route to handle Alipay's asynchronous notification (CRITICAL) ---
@app.route('/alipay/notify', methods=['POST'])
def alipay_notify():
    # Get the raw data from the POST request
    data = request.form.to_dict()
    # IMPORTANT: Verify the signature first!
    # If the signature is invalid, the request is not from Alipay.
    # This is the most critical security step.
    sign = data.pop('sign', None) # Remove the sign key before verification
    if not sign:
        return 'FAIL: Missing sign parameter', 400
    is_verify = alipay.verify(data, sign)
    if is_verify:
        # Signature is valid. Now process the business logic.
        # Check the trade_status to ensure the payment was successful.
        trade_status = data.get('trade_status')
        if trade_status in ('TRADE_SUCCESS', 'TRADE_FINISHED'):
            # Payment is successful. Update your database, etc.
            out_trade_no = data.get('out_trade_no') # Your order ID
            trade_no = data.get('trade_no')         # Alipay's transaction ID
            buyer_id = data.get('buyer_id')
            total_amount = data.get('total_amount')
            # --- YOUR BUSINESS LOGIC GOES HERE ---
            # Example: Update your database to mark order 'out_trade_no' as paid.
            # db.update_order_status(out_trade_no, 'paid', trade_no)
            print(f"SUCCESS: Order {out_trade_no} paid successfully. Alipay trade: {trade_no}")
            # -------------------------------------
            # Respond to Alipay with 'success' to acknowledge receipt.
            # If you don't respond, or respond with anything else, Alipay
            # will keep sending the notification.
            return '
分享:
扫描分享到社交APP
上一篇
下一篇