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'); } }
- 1 . Setting up M-PESA developer account 345 words
- 2 . Setting Up Laravel for M-Pesa Integration 345 words
- 3 . Generating an Access Token 345 words
- 4 . Initiating a Payment Request (STK Push) 345 words
- 5 . Handling Callbacks and Storing Transactions 345 words