Mpesa Online payment in your php app

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).
Prerequisites :
Composer Installed on your machine.
HTTPS enabled urls on your server.

<?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\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGenerator;
 
class TestController extends AbstractController
{
 
 
 
    /**
     *
     * @Route("/mpesa-stk-test")
     * https://<site-name>/mpesa-stk-test/ will be the url to initiate this
     * request
     * 
     */
    public function mpesaTest()
    {
 
        $passKey = ' ';
        $consumerKey = ' ';
        $consumerSecret = ' ';
 
        /** get the url string to our callback url /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('00000');
        $mpesaItem->setTransactionType('CustomerPayBillOnline');
        $mpesaItem->setAmount('1');
        $mpesaItem->setPartyA('254722*****0'); #254722*****0
        $mpesaItem->setPartyB($mpesaItem->getBusinessShortCode());
        $mpesaItem->setPhoneNumber('254722*****0');
        $mpesaItem->setCallBackURL($callBackUrl);
        $mpesaItem->setAccountReference('Product Title');
        $mpesaItem->setTransactionDesc('Product EntityID 111');
 
        $mpesaRequest = new stkPush($mpesaConfigs, $mpesaItem);
 
        try {
 
            $mpesaRequest->mpesaSTKPush();
 
        } catch (\Throwable $error) {
            echo 'Failed to send stkPush request! '.$error->getMessage();
        }
 
        $logger = new MpesaLogger();
        $logger->logResponse('stkresponse.log', $mpesaRequest->mpesaSTKPush());
 
 
        return new Response('Request sent');
    }
 
    /**
     * @Route("/stk-callback", name="stk_callback")
     * use this as the call back url
     */
    public function stkPushCallBackUrl()
    {
 
        $mpesaResponse = new stkPushResponse();
        $stkCallbackResponse = $mpesaResponse->stkPushResponseData();
        $logger = new MpesaLogger();
        $logger->logResponse('stkResponseCallBack.log', $stkCallbackResponse);
 
 
        return new Response('Return for Stk Push');
    }
}