Handling Callbacks and Storing Transactions

 
Lesson 5: Handling Callbacks and Storing Transactions 
In this lesson, you will learn how to capture M-Pesa API callbacks and store transaction details in your Laravel application. Follow these steps to implement the callback functionality.  
Step 1: Add a Callback Route 
Open your routes/web.php file and add the following route to handle M-Pesa callbacks: 
Route::post('mpesa/callback', [MpesaController::class, 'callback'])->name('mpesa.callback');


 
Step 2: Handle Callbacks in the Controller
 
In your MpesaController, add the callback method to process the callback data:
 
public function callback(Request $request)
{
    // Log callback for debugging purposes
    \Log::info('M-Pesa Callback', $request->all());

    $callbackData = $request->all();

    // Example: Handle and store the transaction data in the database
    if (isset($callbackData['Body']['stkCallback'])) {
        $stkCallback = $callbackData['Body']['stkCallback'];

        // Save transaction details to the database
        \DB::table('transactions')->insert([
            'transaction_id' => $stkCallback['CheckoutRequestID'] ?? null,
            'status' => $stkCallback['ResultCode'] == 0 ? 'Success' : 'Failed',
            'amount' => $stkCallback['CallbackMetadata']['Item'][0]['Value'] ?? 0,
            'phone' => $stkCallback['CallbackMetadata']['Item'][1]['Value'] ?? null,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    // Send a success response to M-Pesa
    return response()->json(['ResultCode' => 0, 'ResultDesc' => 'Success']);
}


 
Step 3: Create a Migration for the Transactions Table
 
Run the following command to create a migration for the transactions table:
 
php artisan make:migration create_transactions_table


Edit the generated migration file as follows:
 
public function up(): void
{
    Schema::create('transactions', function (Blueprint $table) {
        $table->id();
        $table->string('transaction_id')->unique();
        $table->string('status');
        $table->decimal('amount', 10, 2);
        $table->string('phone');
        $table->timestamps();
    });
}


Run the migration to create the table:
 
php artisan migrate


 
Step 4: Test Your Callback

Use tools like Postman to send a POST request to your callback URL. Ensure that the callback data is properly logged and stored in the database.