DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

Handling Callbacks in Laravel

Option 1: replace existing callbacks
public function stkCallback()
{
try {
$data = file_get_contents('php://input');

        // Append data to the file instead of overwriting
        Storage::disk('local')->append('stk.json', $data);

        $response = json_decode($data, true);
        if (isset($response['Body']['stkCallback'])) {
            $callback = $response['Body']['stkCallback'];
            $CheckoutRequestID = $callback['CheckoutRequestID'];
            $ResultCode = $callback['ResultCode'];
            $ResultDesc = $callback['ResultDesc'];

            $payment = Stkrequest::where('CheckoutRequestID', $CheckoutRequestID)->first();
            if ($payment) {
                if ($ResultCode == 0) {
                    $metadata = collect($callback['CallbackMetadata']['Item'])->keyBy('Name');
                    $payment->update([
                        'status' => 'Paid',
                        'TransactionDate' => $metadata->get('TransactionDate')['Value'] ?? null,
                        'MpesaReceiptNumber' => $metadata->get('MpesaReceiptNumber')['Value'] ?? null,
                        'ResultDesc' => $ResultDesc,
                    ]);
                } else {
                    $payment->update([
                        'status' => 'Failed',
                        'ResultCode' => $ResultCode,
                        'ResultDesc' => $ResultDesc,
                    ]);
                }
            }
        } else {
            throw new Exception('Invalid callback data structure');
        }
    } catch (Exception $e) {
        Storage::disk('local')->append('stk_error.json', $e->getMessage());
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)