如何为PayPal SDK设置amount字段并从前端传递至后端payment.php
开发需求说明
当前开展PayPal Express 功能开发,需要实现从前端脚本向服务端payment.php传递amount字段值,并且服务端可正常读取该值用于创建支付订单的目标。
现有前端支付按钮代码
<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) { // 交易授权完成后捕获资金 return actions.order.capture().then(function(details) { // 捕获成功后跳转交易完成页 window.location = "paypal-transaction-complete.php?&orderID="+data.orderID; }); } }).render('#paypal-button-container'); </script> <div id="paypal-button-container"></div>
现有payment.php服务端代码
当前代码中支付金额为硬编码的20.00美元,需调整为读取前端传入的动态值。
<?php namespace Sample\CaptureIntentExamples; require __DIR__ . '/vendor/autoload.php'; // 引入PayPal 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(); // 调用PayPal接口创建交易订单 $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); } ?>
动态金额传递实现改造
前端侧改造
在createOrder方法的fetch请求中补充请求体字段,将业务侧的amount值随POST请求发送至payment.php。
核心调整代码:
createOrder: function() { // 从业务上下文/页面元素中读取待支付金额 const payAmount = document.querySelector('#amount-dom').value; return fetch('payment.php', { method: 'post', headers: { 'content-type': 'application/json' }, // 新增请求体携带金额参数 body: JSON.stringify({amount: payAmount}) }).then(res => res.json()).then(data => data.id); }
服务端侧改造
- 新增请求体读取逻辑:通过
php://input读取前端发送的JSON数据,提取amount字段 - 新增参数合法性校验:判断金额是否为可解析的数字,非法值直接返回错误
- 替换原buildRequestBody方法中硬编码的金额值,使用读取到的动态金额生成支付订单请求体
核心调整代码:
class CreateOrder { // 存储解析得到的合法金额 private static $payAmount; public static function createOrder($debug=false) { // 读取前端POST的JSON请求体 $inputData = json_decode(file_get_contents('php://input'), true); // 参数校验 if(empty($inputData['amount']) || !is_numeric($inputData['amount'])) { http_response_code(400); echo json_encode(['msg' => '非法金额参数']); exit; } // 格式化金额为PayPal要求的两位小数字符串格式 self::$payAmount = number_format((float)$inputData['amount'], 2, '.', ''); $request = new OrdersCreateRequest(); $request->prefer('return=representation'); $request->body = self::buildRequestBody(); $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' => self::$payAmount ) ) ) ); } }
联调验证
- 检查浏览器开发者工具Network面板,确认发往payment.php的POST请求体中已携带amount字段
- 检查接口返回的PayPal订单创建结果,确认订单中的金额值与前端传入值一致
内容的提问来源于stack exchange,提问作者Pant
相关产品推荐
相关产品推荐

