You are on page 1of 2

private function parseResponse(

$response_body,
$response_code,
$response_headers
) {
$resp = null;
if ($response_body) {
$resp = json_decode($response_body, true);
$jsonError = json_last_error();
if ($resp === null && $jsonError !== JSON_ERROR_NONE) {
$msg = "Invalid response body: $response_body "
. "(HTTP response code: $response_code, json_last_error:
$jsonError)";
throw new Lunar_Exception_ApiException($msg, $response_code,
$response_body);
}
}

if ($response_code < 200 || $response_code >= 300) {


$this->handleApiError($response_body, $response_code,
$response_headers, $resp);
}

return $resp;
}

private function handleCurlError($url, $errno, $message)


{
switch ($errno) {
case CURLE_SSL_CACERT:
case CURLE_SSL_PEER_CERTIFICATE:
$msg
= "Could not verify Lunar's SSL certificate."; // highly
unlikely
break;
case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_OPERATION_TIMEOUTED:
$msg
= "Could not connect to Lunar ($url). Please check your
internet connection and try again.";
break;
default:
$msg = "Unexpected error communicating with Lunar.";
}

$msg .= "\n\n(Network error [errno $errno]: $message)";


throw new Lunar_Exception_ApiConnection($msg);
}

private function handleApiError(


$response_body,
$response_code,
$response_headers,
$json_resp
) {
switch ($response_code) {
case 400:
// format for the errors:
// - [{"field":"amount","message":"Can refund at most GBP 0"}]
// - [{"code":2,"text":"Invalid card details", "client": true,
"merchant": false}]
$message = "Bad (invalid) request";
// @TODO - extract error parsing logic
if ($json_resp && is_array($json_resp) && ! empty($json_resp)) {
if (isset($json_resp[0]['message'])) {
$message = $json_resp[0]['message'];
} else if (isset($json_resp[0]['text'])) {
$message = $json_resp[0]['text'];
}
}
throw new Lunar_Exception_InvalidRequest($message,
$response_code, $response_body, $json_resp,
$response_headers);
case 401:
throw new Lunar_Exception_Unauthorized("You need to provide
credentials (an app's API key).",
$response_code,
$response_body, $json_resp,
$response_headers);
case 403:
throw new Lunar_Exception_Forbidden("You are correctly
authenticated but do not have access.",
$response_code, $response_body,
$json_resp,
$response_headers);
case 404:
throw new Lunar_Exception_NotFound("Endpoint not found.",
$response_code, $response_body,
$json_resp,
$response_headers);
case 409:
throw new Lunar_Exception_Conflict("Everything you submitted was
fine at the time of validation, but something changed in the meantime and came into
conflict with this (e.g. double-capture).",
$response_code, $response_body,
$json_resp,
$response_headers);
default:
throw new Lunar_Exception_ApiException("Unknown api error",
$response_code,
$response_body,
$json_resp,
$response_headers);
}
}

You might also like