mpesa api integration in laravel 7
Laravel

Mpesa API integration in laravel 7 part 1

M-pesa API integration in laravel 7

Mpesa api integration .MPESA is the most convenient way to send and receive money in kenya. In addition, customers can be able to make business payments, business can make payments to customers or other businesses.

MPESA released their new API(Application Programming Interface)to enable developers to access MPESA services. Such services included in the API are B2B, B2C, C2B, and reversals.

In this tutorial I will be taking you through the various aspects and new answers of M-pesa Integration using Laravel web framework and PHP 7.3. Laravel is one the most popular php framework and can help you build php application from ground up with expressive, elegant syntax.

Setting up Laravel application.

Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.

Via Laravel Installer

First, download the Laravel installer using Composer:

composer global require laravel/installer

Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new laravel_mpesa_integration  will create a directory named laravel_mpesa_integration containing a fresh Laravel installation with all of Laravel’s dependencies already installed:

Create Our project

laravel new laravel_mpesa_integration 

Via Composer Create-Project

Alternatively, you may also install Laravel by issuing the Composer create-project command in your terminal:

composer create-project --prefer-dist laravel/laravel laravel_mpesa_integration

Here is the screenshot:

You can learn more about Laravel Installation visit Laravel official Installation.  

Now that we have a new Laravel application, the next step is to make sure that we have an account with Safaricom Developers Account. To create an account visit Daraja Safaricom website, create an account if you don’t have one and if you have an account proceed and login to your account.

When you log in to your Daraja account, you get the following dashboard which may contain some apps created or for the new users the account will not have any app. here is the screenshot:

The next step we are going to create a new sandbox app by clicking on the Add a New App button. In this tutorial, I am going to create an app called Laravel Mpesa Integration. Here is a screenshot:

Ensure you select both Lipa na Mpesa Sandbox and Mpesa Sandbox and hit Create App button. You will get the following success message.

Next Click on your newly created app and you will get the following screenshot.

We now have  Consumer Key and Consumer Secret, the two should always be kept as a secret.

NB: Never Share Your Consumer Key or Consumer Secret with anyone

Safaricom M-pesa API uses OAuth 2.0 Access token, to invoke M-pesa API we need to generate OAuth 2.0 Access Token and Use Bearer as the keyword.So we are going to generate m-pesa access token in our laravel application.Now open your laravel project using your preffered IDE or Editor. In my case i will use visual code.

The next step is to create a controller, we are going to create a controller called MpesaController by running the following command:

php artisan make:controller MpesaController
MpesaController

The above command has created our basic controller in the app/Http/Controllers directory. By default, the Laravel store controllers in app/Http/Controllers directory. Now open our MpesaController.php and make sure it has the following code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MpesaController extends Controller
{
    public function generateAccessToken()
    {
        $consumer_key="sMpgnYW62glBlxPXbyTBEGdPib8eJLOL";
        $consumer_secret="IcK2PkAFArVVVffU";
        $credentials = base64_encode($consumer_key.":".$consumer_secret);

        $url = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Authorization: Basic ".$credentials));
        curl_setopt($curl, CURLOPT_HEADER,false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $curl_response = curl_exec($curl);
        $access_token=json_decode($curl_response);
        return $access_token->access_token;
    }
}

From our code:

public function generateAccessToken()-we created a method for generating our access token.

$consumer_key-we define our consumer key and we get the value from the app we created in the Daraja account.

$consumer_secret-we define consumer secret we get the value from the app we created in the Daraja account.

$credentials-we use Base64 to combine our consumer key and consumer secret. Base64 is simply a group of binary-to-text encoding schemes that represent binary data in an ASCII string format.

$url-we define a URL to generate access token provided to us by Safaricom Mpesa API.

$curl-we use curl_setopt to set our options for our curl transfer. Learn more about curl option.

$curl_response-we create a variable in which we pass the response from Safaricom M-pesa API.

$acces_token-we use json_decode to convert a JSON object to a php object.

return $acces_token->acces_token;-we access our generated M-pesa access token.

The next step is to define a URL that maps to this method. In our routes folder, open the api.php file and make sure it has the following code.

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('v1/access/token', 'MpesaController@generateAccessToken');

on the last line ,we have defined a URL that goes to MpesaController and maps to generateAccessToken method. Remember this is a post method.

Next create an empty database for local development you can create in localhost/phpmyadmin. Then edit your .env file your database name and credentials.

Test Our Generating Mpesa token Method

Run your application using the following command

php artisan serve

Once you have your development server up and running, launch postman. If you don’t have a postman, you can get it from here. Here is a screenshot of my postman:

using postman to test

We have generated our mpesa access token ,next we are going to create an STK push.

Next part 2

Similar Posts

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *