Initiating a Payment Request (STK Push)

 
Objective: Set up an endpoint for processing STK Push requests.
  1. Add the stkPush method to the MpesaService:
 public function stkPush($phone, $amount, $accountReference, $description)
{
    $url = config('services.mpesa.base_url') . '/mpesa/stkpush/v1/processrequest';

    $response = Http::withToken($this->getAccessToken())->post($url, [
        'BusinessShortCode' => '174379',
        'Password' => base64_encode('174379' . 'passkey' . now()->format('YmdHis')),
        'Timestamp' => now()->format('YmdHis'),
        'TransactionType' => 'CustomerPayBillOnline',
        'Amount' => $amount,
        'PartyA' => $phone,
        'PartyB' => '174379',
        'PhoneNumber' => $phone,
        'CallBackURL' => route('mpesa.callback'),
        'AccountReference' => $accountReference,
        'TransactionDesc' => $description,
    ]);

    return $response->json();
}


2.  Create the controller and route: 
php artisan make:controller MpesaController

<?php

namespace App\Http\Controllers;

use App\Services\MpesaService;
use Illuminate\Http\Request;

class MpesaController extends Controller
{
    protected $mpesaService;

    public function __construct(MpesaService $mpesaService)
    {
        $this->mpesaService = $mpesaService;
    }

    public function stkPush(Request $request)
    {
        $data = $request->validate([
            'phone' => 'required|regex:/^254\d{9}$/',
            'amount' => 'required|numeric',
        ]);

        $response = $this->mpesaService->stkPush(
            $data['phone'],
            $data['amount'],
            'Ref001',
            'Payment for Order'
        );

        return response()->json($response);
    }
}

 Route: 
Route::post('mpesa/stkpush', [MpesaController::class, 'stkPush'])->name('mpesa.stkpush');