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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay