/mpesa

M-Pesa API Package for PHP

Primary LanguagePHPMIT LicenseMIT

M-PESA ONLINE CHECKOUT API Package

Codacy Badge Build Status Total Downloads Latest Stable Version Latest Unstable Version License

This is a PHP package for the Safaricom's M-Pesa API. The API allows a merchant to initiate C2B online checkout (paybill via web) transactions. The merchant submits authentication details, transaction details, callback url and callback method.

After request submission, the merchant receives instant feedback with validity status of their requests. The C2B API handles customer validation and authentication via USSD push. The customer then confirms the transaction. If the validation of the customer fails or the customer declines the transaction, the API makes a callback to merchant. Otherwise the transaction is processed and its status is made through a callback.

Installation

Pull in the package through Composer.

Native Addon

When using vanilla PHP, modify your composer.json file to include:

  "scripts": {
        "post-update-cmd": [
            "SmoDav\\Mpesa\\Support\\Installer::install"
        ]
  },

This script will copy the default configuration file to a config folder in the root directory of your project. Now proceed to require the package.

General Install

Run composer require smodav/mpesa to get the latest stable version of the package.

Migration from v1

v2 makes a change on the response of the transaction by adding a new SmoDav\Mpesa\Response object. When migrating from v1 change the consumption of the response since it no longer provides an instance of GuzzleHttp\Psr7\Stream but an instance of SmoDav\Mpesa\Response with two properties transactionId and response.

Laravel

When using Laravel 5, include the service provider and its alias within your config/app.php.

'providers' => [
    SmoDav\Mpesa\MpesaServiceProvider::class,
],

'aliases' => [
    'Mpesa' => SmoDav\Mpesa\Mpesa::class,
],

Publish the package specific config using:

php artisan vendor:publish

This will publish the M-Pesa configuration file into the config directory as mpesa.php. This file contains all the configurations required to use the package.

Other Frameworks

To implement this package, a configuration repository is needed, thus any other framework will need to create its own implementation of the ConfigurationStore interface.

Configuration

The mpesa.php file under the config directory should be modified to meet your needs. The following are the settings:

  • demo: boolean

Possible values: true | false

Default: true

This is a flag to set the API in demo mode and use the demo timestamp and password. When demo is set to true, set the paybill number to 898998.

  • endpoint: string

Default: "https://safaricom.co.ke/mpesa_online/lnmo_checkout_server.php?wsdl"

This is the default Safaricom API endpoint to be queried for transactional requests.

  • callback_url: string

This is a fully qualified http endpoint that will be be queried by Safaricom's API on completion or failure of the transaction. It should point to the notification endpoint for your application where you can finalize the checkout process.

  • callback_method: HTTP Request Method

Possible values: GET | POST

Default: POST

This is the request method to be used when communicating with the Callback endpoint

  • paybill_number: int

Default: 898998 (Safaricom Demo Paybill)

This is a registered Paybill Number that will be used as the Merchant ID on every transaction. This is also the account to be debited on every successful transaction.

  • passkey: string

This is the secret SAG Passkey generated by Safaricom on registration of the Merchant's Paybill Number.

  • transaction_id_handler: class

Default: '\SmoDav\Mpesa\Generator'

Provide a fully qualified class name of the Class that will be used to generate the transaction number. This class must implement the Transactable Interface. On every transaction, this class will be queried to provide a transaction number to be used. The default works fine.

Usage

Laravel

The package comes with a helper function mpesa() and its respective facade Mpesa. To initiate a transaction using the facade:

public function checkout()
{
    $repsonse = Mpesa::request(100)->from(254722000000)->usingReferenceId(115445)->transact();
}

When using the mpesa() helper function, you can directly initialize the Cashier or chain the methods just as you would when using the facade.

public function checkout()
{
    $repsonse = mpesa()->request(100)->from(254722000000)->usingReferenceId(115445)->transact();
}

public function checkout()
{
    // only initialize the amount
    
    $repsonse = mpesa(100)->from(254722000000)->usingReferenceId(115445)->transact();
}

public function checkout()
{
    // initialize the amount to be deducted and the number
    
    $repsonse = mpesa(100, 254722000000)->usingReferenceId(115445)->transact();
}

public function checkout()
{
    // initialize the amount to be deducted, the number and reference id
    
    $repsonse = mpesa(100, 254722000000, 115445)->transact();
}

Native PHP

When using Native PHP, all you need to do is use the Native Implementation of the Mpesa Class:

use SmoDav\Mpesa\Native\Mpesa;

public function checkout()
{
    $mpesa = new Mpesa;
    
    $repsonse = $mpesa->request(100)->from(254722000000)->usingReferenceId(115445)->transact();
}

For both Laravel and Native PHP, you can override the default paybill number and passkey that has been configured by the config file. Simply use the setPayBill($payBillNumber, $payBillPassKey) function.

Make sure the setPayBill($payBillNumber, $payBillPassKey) function is called before the transact() function.

Laravel
public function checkout()
{
    // initialize the amount to be deducted, the number and reference id
    
    $repsonse = mpesa(100, 254722000000, 115445)->setPayBill(898998, 'the SAG passkey')->transact();
}
Native
use SmoDav\Mpesa\Native\Mpesa;

public function checkout()
{
    $mpesa = new Mpesa;
    
    $repsonse = $mpesa->setPayBill(898998, 'the SAG passkey')
        ->request(100)
        ->from(254722000000)
        ->usingReferenceId(115445)
        ->transact();
}

Result

The result of any methods above will be an instance of SmoDav\Mpesa\Response. This will provide you with the merchant transaction id that was generated for the request and the response from the M-Pesa API.

Transaction Validation

To validate a transaction, you will be required to use the merchant transaction id. The response is an instance of SmoDav\Mpesa\Response and the response object is an stdClass instance with a success property that denotes the status of the transaction and the transaction_number property having the mpesa transaction number.

use SmoDav\Mpesa\Native\Mpesa;

$mpesa = new Mpesa;

$status = $mpesa->validate('h3E3N1zv7lIhSlX1i');

And on Laravel

$status = mpesa()->validate('h3E3N1zv7lIhSlX1i');

//or

$status = Mpesa::validate('h3E3N1zv7lIhSlX1i');

NOTE

The use of Safaricom's demo paybill number will actually deduct the amount from your M-Pesa account. For the testing purposes please use the minimum transaction amount which is KES 10.

License

The M-Pesa Package is open-sourced software licensed under the MIT license.