Generating an Access Token

 
Objective: Implement the method to generate and cache the M-Pesa API access token.
Code: MpesaService.php 
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class MpesaService
{
    public function getAccessToken()
    {
        $url = config('services.mpesa.base_url') . '/oauth/v1/generate?grant_type=client_credentials';

        $response = Http::withBasicAuth(
            config('services.mpesa.consumer_key'),
            config('services.mpesa.consumer_secret')
        )->get($url);

        if ($response->successful()) {
            return $response->json()['access_token'];
        }

        throw new \Exception('Unable to fetch access token');
    }
}