I have integrated my app with a third-party app for payments, regarding successful payments the app is able to receive the complete API response (shared below) and also insert successfully into the database table, the issue is noted for the unsuccessful payments where the response is different than the successful payment response and I am not able to correctly format the API response and also insert into the database table as it happens for the successful payments. So, what I am trying to do is:
- Get the complete unsuccessful API response on the Laravel logs;
- Remove the backslashes to get the response structure as the successful structure;
- Insert the unsuccessful response into the DB table.
Successful API response
{"output_ResponseCode":"INS-0","output_ResponseDesc":"Request processed successfully","output_TransactionID":"vmo3kg298v4l","output_ConversationID":"99b0efe0007648eb96fd03aa1b2a4e1f","output_ThirdPartyReference":"FT15112023131748"}
Unsuccessful API response
{\"output_ResponseCode\":\"INS-10\",\"output_ResponseDesc\":\"Duplicate Transaction\",\"output_TransactionID\":\"N/A\",\"output_Conve (truncated...)
"}
I have already tried to change the Laravel logging config to set the 'max' option to '5000', remove the backslashes but seems like the method I have implemented is not working correctly, so I am out of ideas. If someone could share some light I would appreciate it.
Method to format the unsuccessful API response
private function formatApiResponse($originalResponse)
{
// Remove backslashes from the original response
$formattedResponse = stripslashes($originalResponse);
// Decode the formatted JSON response
$decodedResponse = json_decode($formattedResponse, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Log::channel('logs')->info('Failed to decode formatted API response JSON');
throw new \Exception('Failed to decode formatted API response JSON');
}
return json_encode($decodedResponse);
}
Method to insert into the database table the unsuccessful API response
private function insertUnsuccessfulApiResponse($response, $apiResponse, $id)
{
// Insert API response into the database for unsuccessful transactions
ApiResponsesMpesa::create([
'status_code' => $response->getStatusCode(),
'output_ConversationID' => 'N/A',
'output_TransactionID' => 'N/A',
'output_ResponseDesc' => $apiResponse['output_ResponseDesc'],
'output_ResponseCode' => $apiResponse['output_ResponseCode'],
'output_ThirdPartyReference' => 'N/A',
'transformed_request_id' => $id,
]);
Log::channel('logs')->info('API Response for Unsuccessful Transaction inserted successfully');
}