【发布时间】:2021-04-02 23:12:07
【问题描述】:
我正在使用 PayPal API 模拟否定响应,以便在客户通过 onApprove 方法批准付款时获得响应并正确处理付款的关键部分。
我使用GuzzleHttp + Laravel 到capture 得到客户的认可。我在完整对象中获得COMPLETED 状态。所以请求工作正常。
$client = new \GuzzleHttp\Client();
return
$response = $client->request(
'POST',
'https://api-m.sandbox.paypal.com/v2/checkout/orders/' . $paypalOrderId . '/capture',
[
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $access_token,
// 'PayPal-Mock-Response' => json_encode(["mock_application_codes" => "INTERNAL_SERVER_ERROR"]),
'PayPal-Mock-Response' => json_encode(["mock_application_codes" => "INSTRUMENT_DECLINED"]),
],
],
);
我通过添加 header => 'PayPal-Mock-Response' => json_encode(["mock_application_codes" => "INSTRUMENT_DECLINED"]) 来模拟响应错误,如果不在 try-catch 块内,它当然会破坏代码。
这是请求没有 try-catch 时 Laravel 的输出:
"message": "Client error: `POST https://api-m.sandbox.paypal.com/v2/checkout/orders/6JE880117B631364H/capture` resulted in a `422 Unprocessable Entity`
response:\n{\n \"name\": \"UNPROCESSABLE_ENTITY\",\n \"details\": [\n {\n \"issue\": \"INSTRUMENT_DECLINED\",\n \"description\": \"The (truncated...)\n",
"exception": "GuzzleHttp\\Exception\\ClientException",
"file": "C:\\xampp\\htdocs\\react\\React-Laravel\\vinos-gdl\\vendor\\guzzlehttp\\guzzle\\src\\Exception\\RequestException.php",
"line": 113,
预计会出现此错误。因为我用Mock-Response 标头强制它。
当我在try-catch 块中插入代码时,就会出现“问题”。我得到了预期的Exception,但我无法从response 获得任何详细信息:
catch (ServerException $e) {
if ($e->hasResponse()) {
return response()->json(['msg' => 'Server Error', 'error' => $e->getResponse()], 500);
}
return response()->json([
'msg' => 'Server Error',
'request' => $e->getRequest(),
$e->hasResponse() ? $e->getResponse() : ""
]);
// return response()->json(['msg' => 'Client Error', 'error' => $e->getRequest()]);
} catch (ClientException $e) {
if ($e->hasResponse()) {
return response()->json(['msg' => 'Client Error', 'error' => $e->getResponse()], 400);
}
return response()->json([
'msg' => 'Client Error',
'request' => $e->getRequest(),
$e->hasResponse() ? $e->getResponse() : ""
]);
// return response()->json(['msg' => 'Server Error', 'error' => report($e)]);
}
catch (BadResponseException $e){
return response()->json(['error' => $e]);
}
这是ClientException的输出:
错误:请求失败,状态码为 400
{
"msg": "Client Error",
"error": {} // empty!!!
}
如果我强制ServerException:
{
"msg": "Server Error",
"error": {} // also empty
}
Exceptions 被抛出,但是,这肯定不足以正确处理错误。我需要从response 获取详细信息。
前端以防有人想看:
const onApprove = (data, actions) => {
console.log("payment approved by user", data);
const orderID = data.orderID;
return axios
.post("/paypal/rest-api/capture-order", {
orderID: orderID,
})
.then((res) => {
console.log("success creating order", res.data);
})
.catch((err) => {
console.error(err);
});
};
【问题讨论】:
标签: reactjs laravel guzzle paypal-rest-sdk