我正在编写一个简单的测试 Flask 应用程序,其中我试图允许用户支付某个 PayPal 帐户。为此,我在“ payment_data”字典中添加了一个“收款人”键,其值为 PayPal 帐户的电子邮件地址:
这是我的 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": "[email protected]" # 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>
尽管如此,当我测试应用程序并单击网站上显示的 PayPal 按钮时,会加载 PayPal 窗口,然后消失。当我的字典中不包含“收款人”键时,这种情况实际上不会发生。
API 调用失败并返回错误,因此无法打开任何内容。
API 调用失败的原因是
payee
键的值无效。它必须包含一个子项,例如 email
,如 v1/ payment API 参考中所述。
v1/付款 API 已过时(已有多年历史),您不应将其用于任何新的集成。与 v2/checkout/orders 集成。
没有 PayPal 支持 v2/checkout/orders 的 SDK;使用直接 HTTPS API 调用首先使用 client_id 和 Secret 自行获取 access_token。