I am currently working on a project where we are using PayMongo as our payment gateway. I am facing an issue with retrieving the failed payment response using the PayMongo webhook.
Whenever I select the ‘Fail Test Payment’ option on the payment or checkout page, the webhook does not detect it, and the payment process does not stop; instead, it redirects back to the payment page to select a payment method.
ini_set('display_errors', 1);
error_reporting(E_ALL);
function logWithTimestamp($message) {
$timestamp = date('Y-m-d H:i:s');
if (is_array($message) || is_object($message)) {
$message = print_r($message, true); // Convert array/object to string
}
file_put_contents("webhook_log.txt", "[$timestamp] $message" . PHP_EOL, FILE_APPEND);
}
$payload = file_get_contents("php://input");
if (!$payload) {
logWithTimestamp("No payload received.");
http_response_code(400);
echo json_encode(["message" => "No payload received"]);
exit;
}
$data = json_decode($payload, true);
if (json_last_error() !== JSON_ERROR_NONE) {
logWithTimestamp("JSON Decode Error: " . json_last_error_msg());
http_response_code(200);
echo json_encode(["message" => "Invalid JSON format"]);
exit;
}
function searchArray($array, $keys) {
$result = [];
$recursiveSearch = function ($array, $key, &$found) use (&$recursiveSearch) {
if (is_array($array)) {
foreach ($array as $k => $v) {
if ($k === $key) {
$found[] = $v;
} elseif (is_array($v)) {
$recursiveSearch($v, $key, $found);
}
}
}
};
foreach ($keys as $key) {
$found = [];
$recursiveSearch($array, $key, $found);
$result[$key] = count($found) === 1 ? $found[0] : $found;
}
return $result;
}
$jsonResponse = $data;
$keysToFind = ['id', 'status', 'source'];
$values = searchArray($jsonResponse, $keysToFind);
$paymentId = $values['id'] ?? null; // PayMongo payment ID is usually the second 'id' found
$paymentSource = $values['source'] ?? null;
$status = $values['status'] ?? null;
$test = [$paymentId, $paymentSource, $status];
logWithTimestamp($test);
http_response_code(200);
exit
I hope to gain insights into why the webhook is not receiving the failed payment response