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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay