Skip to content

MTN-Group/MoMoAPIs_Php_sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

momoapi-php-sdk

The MOMOAPI SDK for PHP enables PHP developers to easily work with MTN Mobile Money API.

The SDK provides separate use cases to handle necessary MOMOAPI functionality including Collections,Disbursements,Remittance and Sandbox User Provisioning(For sandbox). Each use case exposes use case scenarios to customize your application integrations as needed. The SDK also includes a Samples, so you can test interactions before integration.

Index

This document contains the following sections:

Requirements

  • PHP 5.4+
  • cURL PHP Extension
  • JSON PHP Extension

Getting Started

Installation

Composer

Update your composer.json file as per the example below and then run for this specific release composer update.

{
    "require": {
        "php": ">=5.4",
        "momopsdk/momopsdk": "<version_number_here>"
    }
}

After installation through Composer, don't forget to require its autoloader in your script or bootstrap file:

require 'vendor/autoload.php';

Manual Installation

If you prefer not to use Composer, you can manually install the SDK.

  • Download the latest stable release of php-sdk
  • Extract php-sdk into your projects vendor folder
  • Require autoloader in your script or bootstrap file:
    require 'path/to/sdk/autoload.php';

Setting Up

Initialization of PHP SDK

All PHP code snippets presented here assumes that you have initialized the PHP SDK before using them in your Development Environment. This section details the initialization of the PHP SDK.

To initialize the PHP SDK, the static method initialize() of MobileMoney class is used. initialize() has the following required parameters:

  1. Environment value can be one of the following
    • MobileMoney::SANDBOX for Sandbox
    • MobileMoney::PRODUCTION for Production
  2. $env['reference_id'] the reference id or user Id (can be obtained from partner gateway.In Sandbox account it can be generated using user provisioning APIs.)
  3. $env['momo_api_key'] the API key of the user (can be obtained from partner gateway or sandbox user provisioning APIs).

Other optional functions available for MobileMoney class are:

  • setCallbackUrl() - URL for your application where you want MobileMoney API to push data. This is optional; if you wish to specify different callback urls for different use cases, you can pass the callback url with each request seperately. Otherwise you can use setCallbackUrl() to set and getCallbackUrl() function to get the callback url.
<?php
//require the autoload file
require 'path/to/sdk/autoload.php';

// or if you are using composer
// require 'vendor/autoload.php';

use momopsdk\Common\Constants\MobileMoney;
use momopsdk\Common\Exceptions\MobileMoneyException;

//Initialize SDK
try {
    MobileMoney::initialize(
        MobileMoney::SANDBOX,
        $env['reference_id'],
        $env['momo_api_key']
    );
} catch (MobileMoneyException $exception) {
    print_r($exception->getMessage());
}

Instantiating the models

When making a specific API call using the PHP SDK, you usually have to include a specific class used for the data sent or returned as part of that API request. The PHP classes used to pass data to and from API endpoints are called models. We will use the DepositModel object as an example. The amount property is an example of a string that is part of the DepositModel class that has both a public getter and a public setter. To set the amount property of a DepositModel object, use this code:

$deposit = new DepositModel();
$deposit->setAmount($amount);

To get the value of the amount property, you can simply use the string that it returns, like this:

$deposit->getAmount();

Handling errors

Error handling is a crucial aspect of software development. Both expected and unexpected errors should be handled by your code.

The PHP SDK provides an MobileMoneyException class that is used for common scenarios where exceptions are thrown. The getErrorObj() and getMessage() methods can provide useful information to understand the cause of errors.

<?php
require_once __DIR__ . './../bootstrap.php';
use momopsdk\Common\Models\DepositModel;
use momopsdk\Common\Exceptions\MobileMoneyException;
use momopsdk\Disbursement\DisbursementTransaction;

$payee = [
        'partyIdType' => 'MSISDN',
        'partyId' => '222222'
    ];

    $oReqDataObject = new DepositModel();

    $oReqDataObject
        ->setAmount('2000')
        ->setCurrency('EUR')
        ->setExternalId('12345678')
        ->setPayerMessage('Payer message here')
        ->setPayeeNote('Payee note here')
        ->setPayee($payee);
    $callbackUrl = "http://webhook.site/c84cd23c-062b-49bb-b206-909bc8625207";
try {
    /**
     * Construct request object and set desired parameters
     */
    $request = DisbursementTransaction::depositV1(
        $oReqDataObject,
        $sDisbursementSubKey,
        $targetEnvironment,
        $callbackUrl
    );

    /**
     *Execute the request
     */
    $response = $request->execute();
} catch (MobileMoneyException $ex) {
    print_r($ex->getMessage());
    print_r($ex->getErrorObj());
}

In the above code the variables $sDisbursementSubKey is the subscription key of disbursement product that is getting from the user profile and $targetEnvironment is the target environment. In sandbox environment use sandbox.

Sample Response:

400: Invalid JSON Field

momopsdk\Common\Models\Error Object
(
    [errorCategory:momopsdk\Common\Models\Error:private] => validation
    [errorCode:momopsdk\Common\Models\Error:private] => formatError
    [errorDescription:momopsdk\Common\Models\Error:private] => Invalid JSON Field
    [errorDateTime:momopsdk\Common\Models\Error:private] => 2022-01-10T07:46:56.529Z
    [errorParameters:momopsdk\Common\Models\Error:private] => Array
        (
            [0] => stdClass Object
                (
                    [key] => amount
                    [value] => must match "^([0]|([1-9][0-9]{0,17}))([.][0-9]{0,3}[0-9])?$"
                )

        )
)

Use Cases

Collection

Scenarios API Function Parameters
Get Account Balance Get Account Balance getAccountBalance string $sCollectionSubKey, string $targetEnvironment
Get Account Balance In Specific Currency Get Account Balance In Specific Currency getAccountBalanceInSpecificCurrency string $sSubsKey, string $sTargetEnvironment, string $sCurrency
Get Basic User Info Get Basic User Info getBasicUserinfo string $accountHolderMSISDN, string $sCollectionSubKey, string $targetEnvironment
Get User Info With Consent Get User Info With Consent getUserInfoWithConsent string $sCollectionSubKey, string $targetEnvironment
Request To Pay Request To Pay requestToPay Transaction $transaction, string $sCollectionSubKey, string $targetEnvironment, string $callBackUrl=null, string $contentType=null
Request To Pay Delivery Notification Request To Pay Delivery Notification requestToPayDeliveryNotification string $referenceId, string $notificationMessage, string $sCollectionSubKey, string $targetEnvironment,DeliveryNotification $deliveryNotification, string $callbackUrl, string $contentType
Request To Pay Transaction Status Request To Pay Transaction Status requestToPayTransactionStatus string $referenceId, string $sCollectionSubKey, string $targetEnvironment
Request To Withdraw Transaction Status Request To Withdraw Transaction Status requestToWithdrawTransactionStatus string $referenceId, string $sCollectionSubKey, string $targetEnvironment
Request To Withdraw V1 Request To Withdraw V1 requestToWithdrawV1 Transaction $transaction, string $sCollectionSubKey, string $targetEnvironment, string $sCallbackUrl, string $sContentType
Request To Withdraw V2 Request To Withdraw V2 requestToWithdrawV2 Transaction $transaction, string $sCollectionSubKey, string $targetEnvironment, string $sCallbackUrl, string $sContentType
Validate Account Holder Status Validate Account Holder Status validateAccountHolderStatus string $accountHolderId, string $accountHolderIdType, string $sCollectionSubKey, string $targetEnvironment

Disbursements

Scenarios API Function Parameters
Deposit V1 Deposit V1 depositV1 DepositModel $oReqDataObject, string $sDisbursementSubKey, string targetEnvironment, string $callbackUrl
Deposit V2 Deposit V2 depositV2 DepositModel $oReqDataObject, string $sDisbursementSubKey, string targetEnvironment, string $callbackUrl
Get Account Balance Get Account Balance getAccountBalance string $sDisbursementSubKey, string $targetEnvironment
Get Account Balance In Specific Currency Get Account Balance In Specific Currency getAccountBalanceInSpecificCurrency string $sDisbursementSubKey, string $targetEnvironment, 'EUR'
Get Basic User Info Get Basic User Info getBasicUserinfo string $accountHolderMSISDN, string $sDisbursementSubKey, string $targetEnvironment
Get Deposit Status Get Deposit Status getDepositStatus string $sDisbursementSubKey, string $targetEnvironment, string $sRefId
GetRefundStatus GetRefundStatus getRefundStatus string $sDisbursementSubKey, string $targetEnvironment, string $sRefId
Get Transfer Status Get Transfer Status getTransferStatus string $sDisbursementSubKey, string $targetEnvironment, string $sRefId
Get User Info With Consent Get User Info With Consent getUserInfoWithConsent string $sDisbursementSubKey, string $targetEnvironment
Refund V1 Refund V1 refundV1 RefundModel $oReqDataObject, string $sDisbursementSubKey, string $targetEnvironment, string $callbackUrl
Refund V2 Refund V2 refundV2 RefundModel $oReqDataObject, string $sDisbursementSubKey, string $targetEnvironment, string $callbackUrl
Request To Pay Delivery Notification Request To Pay Delivery Notification requestToPayDeliveryNotification string $referenceId, string $notificationMessage, string $sDisbursementSubKey, string $targetEnvironment, DeliveryNotification $deliveryNotification, string $language, string $contentType
Transfer Transfer transfer DepositModel $oReqDataObject, string $sDisbursementSubKey, string $targetEnvironment, string $callbackUrl
Validate Account Holder Status Validate Account Holder Status validateAccountHolderStatus

Remittance

Scenarios API Function Parameters
Get Account Balance Get Account Balance getAccountBalance string $sRemittanceSubKey, string $targetEnvironment
Get Basic User Info Get Basic User Info getBasicUserinfo string $accountHolderMSISDN, string $sRemittanceSubKey, string $targetEnvironment
Get Transfer Status Get Transfer Status getTransferStatus string $sRemittanceSubKey, string $targetEnvironment, string $sRefId
Get User Info With Consent Get User Info With Consent getUserInfoWithConsent string $sRemittanceSubKey, string $targetEnvironment
Request To Pay Delivery Notification Request To Pay Delivery Notification requestToPayDeliveryNotification string $referenceId, string $notificationMessage, string $sRemittanceSubKey, string $targetEnvironment, DeliveryNotification $deliveryNotification, string $language, string $contentType
Transfer Transfer transfer DepositModel $oReqDataObject, string $sRemittanceSubKey, string $targetEnvironment, string $callbackUrl
Validate Account Holder Status Validate Account Holder Status validateAccountHolderStatus string $validateAccountHolderStatus, string $accountHolderIdType, string $sRemittanceSubKey, string $targetEnvironment

Sandbox User Provisioning

Scenarios API Function Parameters
Create user Create Api User createUser array $aData, string $sCollectionSubKey
Get User Details Get User Details getUserDetails string $sCollectionSubKey, string $sRefId
Create API key Create API key createApiKey string $sCollectionSubKey, string $sRefId

Tests

The tests folder contains the test cases. These are logically divided in unit and integration tests. Integration tests require an active user id, api key, subscription keys. To run tests provide necessary permission to the system user in the root folder to create the cache file. Auth cache will be created in the path /var/auth.cache.

  1. Install Composer
  2. From the root of the sdk-php project, run composer install --dev to install the dependencies
  3. Copy config.env.sample to config.env and replace the template values by actual values

Unit tests

These tests are located in tests/Unit and are responsible for ensuring each class is behaving as expected, without considering the rest of the system. Unit tests heavily leverage mocking and are an essential part of the testing harness.

To run unit tests,

composer run unit-test

To run tests individually (be sure not to be pointing to an integration test file):

composer run unit-test path/to/class/file

Integration tests

These tests are located in tests/Integration and are responsible for ensuring a proper communication with server/simulator. With the integration tests, we ensure all communications between the SDK and the server/simulator are behaving accordingly.

To run the integration tests,

composer run integration-tests

To run tests individually (be sure not to be pointing to an unit test file):

composer run integration-tests path/to/class/file

Execute all tests (unit + integration)

composer run tests

Samples

The sample code snippets are all completely independent and self-contained. You can analyze them to get an understanding of how a particular method can be implemented in your application. Sample code snippets can be found here. Steps to run the sample code snippets are as follows:

  • Clone this repository:
git clone git@github.com:gsmainclusivetechlab/momoapi-php-sdk.git
cd momoapi-php-sdk
  • Create config.env file for API credentials:
cp config.env.sample config.env
  • Set the API credentials in the config.env file:

e.g.

    reference_id = <User Id here>
    collection_subscription_key = <Collection subscription key obtained from user profile>
    disbursement_subscription_key = <Disbursement subscription key obtained from user profile>
    remittance_subscription_key = <Remittance subscription key obtained from user profile>
    momo_api_key = <User API key>
    target_environment = <Your Target environment here>
  • Run each sample directly from the command line. For example:
php -f Sample/Disbursements/DepositV1.php

Folder Permissions

If needed, provide permission to the server user in the root folder of the SDK inorder to create authorization cache file. Authorization cache would be created in path 'var/auth.cache'.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published