PHP网站集成PayPal支付时JSON解析错误求助
问题分析与解决方案
你的核心问题是前端无法解析PHP接口返回的内容为JSON,根源出在三个地方:前端请求未传必要参数、PHP接口未正确输出JSON、缺乏错误处理导致返回非JSON内容。以下是具体修正方案:
1. 前端代码修正:补充请求体参数
你的前端fetch没有传递amount和info参数,PHP接口无法获取创建订单所需的核心数据,会导致后续逻辑报错并返回非JSON内容。修改后代码:
createOrder() { // 替换为实际业务中的订单金额和信息 const orderData = { amount: "9.99", info: "商品订单描述" }; return fetch("<?=base_url("public/paypal_create")?>", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(orderData) // 新增:传递订单数据 }) .then((response) => { // 新增:先检查HTTP响应状态,提前捕获错误 if (!response.ok) { throw new Error(`请求失败,状态码:${response.status}`); } return response.json(); }) .then((order) => order.id); }
2. PHP接口修正:正确输出JSON并添加错误处理
你的createOrder方法返回了解码后的数组,但前端需要的是JSON字符串;同时缺少参数校验、CURL错误处理,导致失败时返回无效内容。修改后代码:
控制器接口方法(对应public/paypal_create)
public function paypal_create() { // 接收前端传递的JSON数据 $input = json_decode(file_get_contents('php://input'), true); $amount = $input['amount'] ?? null; $info = $input['info'] ?? null; // 校验必要参数 if (!$amount) { http_response_code(400); echo json_encode(['error' => '缺少订单金额参数']); exit; } // 调用创建订单方法 $orderResult = $this->createOrder($amount, $info); // 设置响应头并输出JSON header('Content-Type: application/json'); echo json_encode($orderResult); }
修正后的createOrder方法
function createOrder($amount, $info) { $pp_env = PAYPAL_ENVIRONMENT_MODE == 1 ? PAYPAL_SANDBOX_ENV : PAYPAL_LIVE_ENV ; $accessToken = $this->generateAccessToken(); $url = $pp_env."/v2/checkout/orders"; $data = array( 'intent' => 'CAPTURE', 'purchase_units' => array( array( 'amount' => array( 'currency_code' => CURRENCY_CODE, 'value' => $amount, ), 'description' => $info // 用传入的info填充订单描述 ), ), ); $headers = array( "Content-type: application/json", "Accept: application/json", "Authorization: Bearer " . $accessToken, ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 生产环境建议开启SSL验证,沙箱可根据情况调整 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); $response = curl_exec($ch); // 捕获CURL请求错误 if(curl_errno($ch)) { $errorMsg = curl_error($ch); curl_close($ch); return ['error' => 'PayPal请求失败:' . $errorMsg]; } curl_close($ch); // 验证PayPal响应的JSON格式 $decodedResponse = json_decode($response, true); if(json_last_error() !== JSON_ERROR_NONE) { return ['error' => '解析PayPal响应失败:' . json_last_error_msg()]; } return $decodedResponse; }
关键修正点说明
- 前端传参:必须通过
body传递订单核心数据,否则PHP接口无法正常调用PayPal API。 - PHP输出JSON:控制器方法必须通过
echo json_encode()输出JSON字符串,而非返回数组;同时设置Content-Type响应头,确保前端识别为JSON格式。 - 错误捕获:添加CURL错误处理、JSON解析校验,避免请求失败时返回HTML错误提示或无效内容,导致前端JSON解析报错。
内容的提问来源于stack exchange,提问作者leboma241
相关产品推荐
相关产品推荐

