php - 如何将金额字段设置为 PayPal SDK
问题描述
我正在使用 PayPal express 并希望将金额字段值从客户端脚本发送到服务器文件 (payment.php),并且还希望将其值发送到服务器端文件。
这是客户端脚本
<script src="https://www.paypal.com/sdk/js?client-id=<client-id>"></script>
<script>
paypal.Buttons({
createOrder: function() {
return fetch('payment.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
}).then(function(res) {
return res.json();
}).then(function(data) {
return data.id;
});
},
onApprove: function(data, actions) {
// This function captures the funds from the transaction.
return actions.order.capture().then(function(details) {
// This function shows a transaction success message to your buyer.
window.location = "paypal-transaction-complete.php?&orderID="+data.orderID;
});
}
}).render('#paypal-button-container');
</script>
<div id="paypal-button-container"></div>
这是我要获取金额字段值的payment.php
<?php
namespace Sample\CaptureIntentExamples;
require __DIR__ . '/vendor/autoload.php';
//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
require 'paypal-client.php';
class CreateOrder
{
public static function createOrder($debug=false)
{
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = self::buildRequestBody();
// 3. Call PayPal to set up a transaction
$client = PayPalClient::client();
$response = $client->execute($request);
echo json_encode($response->result, JSON_PRETTY_PRINT);
return $response;
}
private static function buildRequestBody()
{
return array(
'intent' => 'CAPTURE',
'application_context' =>
array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/cancel'
),
'purchase_units' =>
array(
0 =>
array(
'amount' =>
array(
'currency_code' => 'USD',
'value' => '20.00'
)
)
)
);
}
}
if (!count(debug_backtrace()))
{
CreateOrder::createOrder(true);
}
?>
请让我知道我该怎么做?谢谢!
解决方案
使用 PHP 最简单的方法是使用 GET 字符串。
return fetch('payment.php?amount=' + document.getElementById('amount').value , {
^ 您可能想要验证或清理该输入或 URL 编码该值,但在大多数情况下它应该可以工作。
array(
'currency_code' => 'USD',
'value' => $_GET['amount']
)
它不是现代的,但对你来说就是 PHP,解析 JSON 可能是矫枉过正。
在服务器上创建时不应该使用actions.order.capture()
它,如果它真的有效,我会感到惊讶。在您的服务器上实现一个捕获订单路由,并使用这个具有适当错误处理的 JS 示例:https ://developer.paypal.com/demo/checkout/#/pattern/server
推荐阅读
- javascript - 添加新 div 时更新包含“div”数量的变量
- android - 如何在底部应用栏中使用后退按钮实现导航。安卓
- javascript - 如何使用nodejs删除mongodb中的一些数组?
- c# - C#:有没有办法让 T 更短的通用约束?
- c++ - 在头文件中使用 std::any 错误 - 使用未声明的标识符“任何”
- java - 我创建的方法中是否缺少任何东西?我对方法创建感到困惑
- ios - SwiftUI - AsyncImage 导致大量 tmp 文件夹?
- javascript - 如何在单击时为动态创建的元素显示相同的弹出窗口?
- html - CSS 问题,检查状态不会改变样式
- c - C 中的共享内存 (sysV)