You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask应用中paypalrestsdk的payee字段引发支付窗口异常

PayPal付款窗口加载后消失问题(添加payee字段时)

我开发了一个简易Flask测试应用,目标是让用户向指定PayPal账户付款。为此,我在payment_data字典的transactions中添加了payee字段,赋值为目标PayPal账户的邮箱地址。但测试时点击网页上的PayPal按钮,PayPal窗口加载后随即消失;不添加payee字段时则能正常运行。

我的代码

app.py

from flask import Flask, render_template, jsonify, request
import paypalrestsdk

app = Flask(__name__)

paypalrestsdk.configure({
  "mode": "sandbox", # sandbox or live
  "client_id": "AY0xw74ZNbvbYuhq3SOWkJ_SxiR4bpJ_Il3z_Hk0lZZoRrKsIWE1UOBXmfYwyTV965AcGRjNS0eouLkO",
  "client_secret": "EDjD8TovplQDbb4VhmYpiGq3M8gLlMu0-sqSpcYkDncjAZG3sIJ3LsROC9cGjMbPIxFAjHNNYS4hqdYm" })

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/payment', methods=['POST'])
def payment():
    payment_data = {
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"
        },
        "redirect_urls": {
            "return_url": "http://localhost:3000/payment/execute",
            "cancel_url": "http://localhost:3000/"
        },
        "transactions": [{
            "item_list": {
                "items": [{
                    "name": "testitem",
                    "sku": "12345",
                    "price": "500.00",
                    "currency": "USD",
                    "quantity": 1
                }]
            },
            "amount": {
                "total": "500.00",
                "currency": "USD"
            },
            "description": "This is the payment transaction description.",
            "payee": "glolibros.business@gmail.com"  # Add the payee email here
        }]
    }

    payment = paypalrestsdk.Payment(payment_data)

    if payment.create():
        print('Payment Success!')
    else:
        print(payment.error)

    return jsonify({'paymentID': payment.id})

@app.route('/execute', methods=['POST'])
def execute():
    success = False

    payment = paypalrestsdk.Payment.find(request.form['paymentID'])

    if payment.execute({'payer_id' : request.form['payerID']}):
        print('Execute success!')
        success = True
    else:
        print(payment.error)

    return jsonify({'success' : success})

if  __name__ == '__main__':
    app.run(debug=True)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="paypal-button"></div>

    <script src="https://www.paypalobjects.com/api/checkout.js"></script>

    <script>
        var CREATE_PAYMENT_URL  = '/payment';
        var EXECUTE_PAYMENT_URL = '/execute';
    
        paypal.Button.render({
    
            env: 'sandbox', // Or 'sandbox'
    
            commit: true, // Show a 'Pay Now' button
    
            payment: function() {
                return paypal.request.post(CREATE_PAYMENT_URL).then(function(data) {
                    return data.paymentID;
                });
            },
    
            onAuthorize: function(data) {
                return paypal.request.post(EXECUTE_PAYMENT_URL, {
                    paymentID: data.paymentID,
                    payerID:   data.payerID
                }).then(function(res) {
    
                    console.log(res.success)
                });
            }
    
        }, '#paypal-button');
    </script>
</body>
</html>

问题原因及修复方案

1. Payee字段格式错误

PayPal REST API要求payee是一个包含email_address键的字典,而非直接传入邮箱字符串。修改payment_data中的payee字段:

"payee": {
    "email_address": "glolibros.business@gmail.com"
}

2. 错误处理缺失

原代码中即使payment.create()失败,仍会返回payment.id,导致前端拿到无效的支付ID,进而引发PayPal窗口崩溃。修改/payment路由的返回逻辑:

if payment.create():
    print('Payment Success!')
    return jsonify({'paymentID': payment.id})
else:
    print(payment.error)
    return jsonify({'error': str(payment.error)}), 400

3. 回调URL端口不匹配

你的Flask应用默认运行在5000端口,但redirect_urls中写的是3000端口,且return_url路径与实际路由不符(实际路由是/execute,不是/payment/execute)。修正redirect_urls:

"redirect_urls": {
    "return_url": "http://localhost:5000/execute",
    "cancel_url": "http://localhost:5000/"
}

4. 沙箱账户关联检查

确保glolibros.business@gmail.com对应的沙箱账户已与你的开发者账户关联,否则PayPal会拒绝该支付请求。

内容的提问来源于stack exchange,提问作者mael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 15:35:11