Mpesa Online payment in your php app

Submitted by Nicholas on Wed, 02/27/2019 - 19:23

In this blog, I will demonstrate how you could integrate M-pesa payments (Online payment) in your php app. I will be extending an mpesa php library of choice on a php framework of choice (symfony (4 latest version)).
Prerequisites :

  • Create an app with safaricom, here.
  • Composer Installed on your machine.
  • Php v7.1 or above.

Assuming you have your symfony project folder ready (or whatever framework you're using just change the logic to fit your case) . Download the php library we will be extending via composer by running:  

composer require flaircore/mpesa

to have the library downloaded in your project's vendor/ directory.

Finally create your Controller class in src/Controller/ and name the file(class) StkPushController.php.

<?php
 
namespace App\Controller;
 
use Flaircore\Mpesa\Logger\MpesaLogger;
use Flaircore\Mpesa\MpesaConfigs;
use Flaircore\Mpesa\MpesaItem;
use Flaircore\Mpesa\Requests\stkPush;
use Flaircore\Mpesa\Responses\stkPushResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGenerator;
 
class StkPushController extends AbstractController
{
 
 
 
    /**
     *
     * @Route("/mpesa-stk-test")
     * https://<site-name>/mpesa-stk-test/ will be the url you go to,
     * to initiate this request
     *
     */
    public function stkRequest()
    {
        // Define our variables maybe
        $passKey = '';
        $consumerKey = '';
        $consumerSecret = '';
 
        /**
         *
         * $callBackUrl         *
         * get the url string to our callback url /stk_callback below
         *  will return 'https://<app home>/stk-callback'
         */
 
 
        $callBackUrl = $this->generateUrl('stk_callback', [],UrlGenerator::ABSOLUTE_URL);
 
        $mpesaConfigs = new MpesaConfigs();
        $mpesaConfigs->setConsumerKey($consumerKey);
        $mpesaConfigs->setConsumerSecret($consumerSecret);
        $mpesaConfigs->setPassKey($passKey);
        $mpesaConfigs->setEnviroment('sandbox');
 
        $mpesaItem = new MpesaItem($mpesaConfigs);
        $mpesaItem->setBusinessShortCode('');#Your business short code
        $mpesaItem->setTransactionType('CustomerPayBillOnline');
        $mpesaItem->setAmount('1');#Amount in Ksh
        $mpesaItem->setPartyA('2547****'); #2547********
        $mpesaItem->setPartyB($mpesaItem->getBusinessShortCode());
        $mpesaItem->setPhoneNumber('2547********');#2547********
        $mpesaItem->setCallBackURL($callBackUrl);
        $mpesaItem->setAccountReference('Product Title');
        $mpesaItem->setTransactionDesc('Product EntityID 111');
 
        $mpesaRequest = new stkPush($mpesaConfigs, $mpesaItem);
 
        try {
 
            $request = $mpesaRequest->mpesaSTKPush();
 
        } catch (\Throwable $error) {
            echo 'Failed to send stkPush request! '.$error->getMessage();
        }
 
        /**
         * log mpesa response
         */
        $logger = new MpesaLogger();
        $logger->logResponse('stkresponse.log', $request);
 
 
        return new Response('Request sent');
    }
}

Now implement our call back url and the logic required to receive/process the mpesa response 

Below our stkRequest method add the code below.

/**
     * @Route("/stk-callback", name="stk_callback")
     * use this as the call back url (referenced by name above)
     */
    public function stkPushCallBackUrl(Request $request)
    {
 
        $mpesaResponse = new stkPushResponse();
        $stkCallbackResponse = $mpesaResponse->stkPushResponseData();
 
        /**
         * log mpesa response
         */
        $logger = new MpesaLogger();
        $logger->logResponse('stkResponseCallBack.log', $stkCallbackResponse);
 
        return new JsonResponse('Return for Stk Push');
 
    }

Fill in the required information in our request object above with the info at safaricom developer, and the test credentials of your specific app.

Now, for our app to send requests to safaricom, it's required to have https(ssl enabled) urls. If you're developing on localhost, the easiest way
am aware of towards achieving this, is to download ngrok  and extract the file in the root of your project folder. Open a command window in
your project directory and run:

 

./ngrok http 8000

Assuming you're accessing your app via localhost:8000, you will get something like this.

image|missing

To send our first request, we will go to https://d32bfc6c.ngrok.io/mpesa-stk-test (Your home page url will be different though). If you filled the
information correctly you should receive a prompt on your phone to enter pin and proceed with this request.

Likes
0