Guzzle POST请求返回500 INTERNAL_ERROR问题排查求助
问题诊断与修复方案
你遇到的500内部错误大概率是代码请求格式不符合API要求导致的——既然Postman能正常调用,说明服务器在接收合法请求时可以正常工作。以下是代码中的关键问题及修复方法:
1. chargeItems格式错误
支付API要求chargeItems是商品对象的数组(哪怕只有一件商品),但你的代码直接传递了单个关联数组,未包裹在外层数组中。服务器解析格式失败,触发内部错误。
错误代码片段:
'chargeItems' => [ 'itemId' => '687463b2d866bd66a', 'description' => 'new order for test', 'price' => $amount, 'quantity' => '1' ],
修复后代码:
'chargeItems' => [ [ 'itemId' => '687463b2d866bd66a', 'description' => 'new order for test', 'price' => $amount, 'quantity' => '1' ] ],
2. 响应体重复读取导致解析失败
在catch块中已经调用$response->getBody()->getContents()读取了响应体,后续在try/catch外部再次调用时,流指针已到末尾,会返回空字符串,直接导致json_decode失败。
统一修复后的完整逻辑:
$httpClient = new \GuzzleHttp\Client(); $paymentStatus = null; try { $response = $httpClient->request('POST', 'https://atfawry.fawrystaging.com/ECommerceWeb/api/payments/charge', [ 'headers' => [ 'Accept' => 'application/json' ], 'json' => [ // 用Guzzle的json选项,自动处理编码和Content-Type头 'merchantCode' => $merchantCode, 'customerName' => 'Gazy saleh', 'customerMobile' => '01234567891', 'customerEmail' => 'gazy3@yahoo.com', // 修正邮箱拼写错误 'customerProfileId' => $merchant_cust_prof_id, 'merchantRefNumber' => $merchantRefNumber, 'amount' => $amount, 'currencyCode' => 'EGP', 'language' => 'en-eg', 'chargeItems' => [ [ 'itemId' => '687463b2d866bd66a', 'description' => 'new order for test', 'price' => $amount, 'quantity' => '1' ] ], 'debitMobileWalletNo'=> $debitMobileWalletNo, 'signature' => $signature, 'paymentMethod' => 'MWALLET', 'description' => 'new order for test' ] ]); $responseData = json_decode($response->getBody()->getContents(), true); $paymentStatus = $responseData['type']; } catch (\GuzzleHttp\Exception\GuzzleException $e) { $response = $e->getResponse(); $responseBodyAsString = $response->getBody()->getContents(); echo $response->getStatusCode() . PHP_EOL; echo $responseBodyAsString; // 可在此添加日志记录等异常处理逻辑 }
3. 额外注意事项
- 邮箱拼写错误:代码中
customerEmail为gazy3@yahio.com,应为gazy3@yahoo.com,Postman中大概率使用了正确地址,这也可能是服务器报错的诱因。 - 优先用Guzzle的
json选项:代替手动json_encode和设置Content-Type,Guzzle会自动处理编码和请求头,减少人为失误。
验证建议
修复后若仍报错,可:
- 对比Postman和代码生成的请求体(通过Guzzle调试功能打印请求内容),确保所有参数完全一致。
- 检查
signature生成逻辑是否正确,签名错误也可能触发服务器内部错误。
内容的提问来源于stack exchange,提问作者abdelnasser ahmed
相关产品推荐
相关产品推荐

