Skip to content

gsmainclusivetechlab/mmapi-php-sdk

Repository files navigation

mmapi-php-sdk

The MMAPI SDK for PHP enables PHP developers to easily work with GSMA Mobile Money API Specification 1.2.0.

The SDK provides separate use cases to handle necessary MMAPI functionality including Merchant Payments, Disbursements, International Transfers, P2P Transfers, Recurring Payments, Account Linking, Bill Payments and Agent Services (including Cash-In and Cash-Out). 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",
        "mmpsdk/mmpsdk": "<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. $consumerKey the API consumer key (can be obtained from developer portal)
  3. $counsumerSecret the API consumer secret (can be obtained from developer portal)
  4. $apiKey the API Key (can be obtained from developer portal)

Other optional functions available for MobileMoney class are:

  • setCallbackUrl() - URL for your application where you want MobileMoney API to push data as a PUT request. 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.
  • setSecurityLevel() - When making API requests, this property is used to specify the type of authentication to be used. If not set the default SecurityLevel::DEVELOPMENT will be used. Value can be one of the following
    • SecurityLevel::DEVELOPMENT - Uses Basic authentication for requests.
    • SecurityLevel::STANDARD - Uses OAuth2 authentication for requests.
<?php
//require the autoload file
require 'path/to/sdk/autoload.php';

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

use mmpsdk\Common\Constants\MobileMoney;
use mmpsdk\Common\Enums\SecurityLevel;
use mmpsdk\Common\Exceptions\MobileMoneyException;

//Initialize SDK
try {
    MobileMoney::initialize(
        MobileMoney::SANDBOX,
        $consumerKey,
        $counsumerSecret,
        $apiKey
    );
} 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 Transaction object as an example. The amount property is an example of a string that is part of the Transaction class that has both a public getter and a public setter. To set the amount property of a Transaction object, use this code:

$transaction = new Transaction();
$transaction->setAmount($amount);

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

$transaction->getAmount();

PHP SDK models also provide a method called hydrate() that enables developers to initialize many of the object’s properties by passing raw json string to the method as parameter. Instead of using the getter and setter methods, you could set property values by using the hydrate() method.

$transaction->hydrate(
    '{"amount":"200.00","currency":"RWF","creditParty":[{"key":"accountid","value":"2000"}],"debitParty":[{"key":"accountid","value":"2999"}],"type":"transfer"}'
);

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 mmpsdk\Common\Models\Transaction;
use mmpsdk\Common\Exceptions\MobileMoneyException;
use mmpsdk\MerchantPayment\MerchantPayment;

$transaction = new Transaction();
$transaction
    ->setAmount('-16.00')
    ->setCurrency('USD')
    ->setCreditParty(['walletid' => '1'])
    ->setDebitParty(['msisdn' => '+44012345678']);
try {
    /**
     * Construct request object and set desired parameters
     */
    $request = MerchantPayment::createMerchantTransaction($transaction);

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

Sample Response:

400: Invalid JSON Field

mmpsdk\Common\Models\Error Object
(
    [errorCategory:mmpsdk\Common\Models\Error:private] => validation
    [errorCode:mmpsdk\Common\Models\Error:private] => formatError
    [errorDescription:mmpsdk\Common\Models\Error:private] => Invalid JSON Field
    [errorDateTime:mmpsdk\Common\Models\Error:private] => 2022-01-10T07:46:56.529Z
    [errorParameters:mmpsdk\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

Merchant Payments

Scenarios API Function Parameters
Payee-Initiated Merchant Payment Payee Initiated Merchant Payment createMerchantTransaction Transaction $transaction, string $callBackUrl = null
Payee-Initiated Merchant Payment using the Polling Method Payee Initiated Merchant Payment createMerchantTransaction Transaction $transaction, string $callBackUrl = null
Poll to Determine the Request State viewRequestState string $serverCorrelationId
Optional Retrieve a Transaction viewTransaction string $transactionReference
Payer-Initiated Merchant Payment Payer Initiated Merchant Payment createMerchantTransaction Transaction $transaction, string $callBackUrl = null
Payee-Initiated Merchant Payment using a Pre-authorised Payment Code Obtain an Authorisation Code createAuthorisationCode array $accountIdentifier, AuthorisationCode $authorisationCode
Perform a Merchant Payment createMerchantTransaction Transaction $transaction, string $callBackUrl = null
Optional View An Authorisation Code viewAuthorisationCode string $accountIdentifier, string $authorisationCode
Merchant Payment Refund Perform a Merchant Payment Refund createRefundTransaction Transaction $transaction, string $callBackUrl=null
Merchant Payment Reversal Perform a Merchant Payment Reversal createReversal string $transactionReference, Reversal $reversal=null, string $callBackUrl=null
Obtain a Merchant Balance Get an Account Balance viewAccountBalance array $accountIdentifier
Retrieve Payments for a Merchant Retrieve a Set of Transactions for an Account viewAccountTransactions array $accountIdentifier, array $filter=null
Check for Service Availability Check for Service Availability viewServiceAvailability NA
Retrieve a Missing API Response Retrieve a Missing Response viewResponse string $clientCorrelationId, Object $objRef=null

Disbursements

Scenarios API Function Parameters
Individual Disbursement Create a Individual Disbursement request createDisbursementTransaction Transaction $transaction, string $callBackUrl = null
Bulk Disbursement Create A Transaction Batch createBatchTransaction BatchTransaction $batchTransaction, $callBackUrl = null
View A Transaction Batch viewBatchTransaction string $batchId
View Batch Completions viewBatchCompletions string $batchId, array $filter = null
View Batch Rejections viewBatchRejections string $batchId, array $filter = null
Bulk Disbursement with Maker / Checker Create A Transaction Batch createBatchTransaction BatchTransaction $batchTransaction, $callBackUrl = null
Update A Transaction Batch updateBatchTransaction array $patchData, string $batchId, string $callBackUrl = null
View A Transaction Batch viewBatchTransaction string $batchId
View Batch Completions viewBatchCompletions string $batchId, array $filter = null
View Batch Rejections viewBatchRejections string $batchId, array $filter = null
Individual Disbursement Using the Polling Method Create a Individual Disbursement request createDisbursementTransaction Transaction $transaction, string $callBackUrl = null
Poll to Determine the Request State viewRequestState string $serverCorrelationId
Retrieve a Transaction viewTransaction string $transactionReference
Disbursement Reversal Perform a Disbursement Reversal createReversal string $transactionReference, Reversal $reversal=null, string $callBackUrl=null
Obtain a Disbursement Organisation Balance Get an Account Balance viewAccountBalance array $accountIdentifier
Retrieve Transactions for a Disbursement Organisation Retrieve a Set of Transactions for an Account viewAccountTransactions array $accountIdentifier, array $filter=null
Check for Service Availability Check for Service Availability viewServiceAvailability NA
Retrieve a Missing API Response Retrieve a Missing Response viewResponse string $clientCorrelationId, Object $objRef=null

International Transfers

Scenarios API Function Parameters
International Transfer via Hub Request a International Transfer Quotation createQuotation Quotation quotation, string $callBackUrl = null
Perform an International Transfer createInternationalTransaction Transaction $transaction, string $callBackUrl = null
Optional View A Quotation viewQuotation String quotationReference
Bilateral International Transfer Request a International Transfer Quotation createQuotation Quotation quotation, string $callBackUrl = null
Perform an International Transfer createInternationalTransaction Transaction $transaction, string $callBackUrl = null
Optional View A Quotation viewQuotation String quotationReference
International Transfer Reversal Perform a Transaction Reversal createReversal string $transactionReference, Reversal $reversal=null, string $callBackUrl=null
Obtain an FSP Balance Get an Account Balance viewAccountBalance array $accountIdentifier
Retrieve Transactions for an FSP Retrieve a Set of Transactions for an Account viewAccountTransactions array $accountIdentifier, array $filter=null
Check for Service Availability Check for Service Availability viewServiceAvailability NA
Retrieve a Missing API Response Retrieve a Missing Response viewResponse string $clientCorrelationId, Object $objRef=null

P2P Transfers

Scenarios API Function Parameters
P2P Transfer via Switch Retrieve the Name of the Recipient viewAccountName array $accountIdentifier
Request a P2P Quotation createQuotation Quotation quotation, string $callBackUrl = null
Perform a P2P Transfer createTransferTransaction Transaction $transaction, string $callBackUrl = null
Bilateral P2P Transfer Retrieve the Name of the Recipient viewAccountName array $accountIdentifier
Perform a P2P Transfer createTransferTransaction Transaction $transaction, string $callBackUrl = null
‘On-us’ P2P Transfer Initiated by a Third Party Provider Retrieve the Name of the Recipient viewAccountName array $accountIdentifier
Request a P2P Quotation createQuotation Quotation quotation, string $callBackUrl = null
Perform a P2P Transfer createTransferTransaction Transaction $transaction, string $callBackUrl = null
P2P Transfer Reversal Perform a Transaction Reversal createReversal string $transactionReference, Reversal $reversal=null, string $callBackUrl=null
Obtain an FSP Balance Get an Account Balance viewAccountBalance array $accountIdentifier
Retrieve Transactions for an FSP Retrieve a Set of Transactions for an Account viewAccountTransactions array $accountIdentifier, array $filter=null
Check for Service Availability Check for Service Availability viewServiceAvailability NA
Retrieve a Missing API Response Retrieve a Missing Response viewResponse string $clientCorrelationId, Object $objRef=null

Recurring Payments

Scenarios API Function Parameters
Setup a Recurring Payment Setup a Recurring Payment createAccountDebitMandate array $accountIdentifier, DebitMandate $debitMandate, $callBackUrl = null
Take a Recurring Payment Take a Recurring Payment createMerchantTransaction NA
Take a Recurring Payment using the Polling Method Take a Recurring Payment createMerchantTransaction Transaction $transaction, string $callBackUrl = null
Poll to Determine the Request State viewRequestState string serverCorrelationId
Retrieve a Transaction viewTransaction string $transactionReference
Recurring Payment Refund Perform a Recurring Payment Refund createRefundTransaction Transaction $transaction, string $callBackUrl=null
Recurring Payment Reversal Perform a Merchant Payment Reversal createReversal string $transactionReference, Reversal $reversal=null, string $callBackUrl=null
Payer sets up a Recurring Payment using MMP Channel Setup a Recurring Payment createAccountDebitMandate array $accountIdentifier, DebitMandate $debitMandate, $callBackUrl = null
Obtain a Service Provider Balance Get an Account Balance viewAccountBalance array $accountIdentifier
Retrieve Payments for a Service Provider Retrieve a Set of Transactions for an Account viewAccountTransactions array $accountIdentifier, array $filter=null
Check for Service Availability Check for Service Availability viewServiceAvailability NA
Retrieve a Missing API Response Retrieve a Missing Response viewResponse string $clientCorrelationId, Object $objRef=null

Account Linking

Scenarios API Function Parameters
Setup an Account Link Establish an Account to Account Link createAccountLink array $accountIdentifier, Link $link
Perform a Transfer for a Linked Account Use a Link to make a Transfer createTransferTransaction Transaction $transaction, string $callBackUrl = null
Perform a Transfer using an Account Link via the Polling Method Use a Link to make a Transfer createTransferTransaction Transaction $transaction, string $callBackUrl = null
Poll to Determine the Request State viewRequestState string $serverCorrelationId
Retrieve a Transaction viewTransaction string $transactionReference
Perform a Transfer Reversal Perform a Transaction Reversal createReversal string $transactionReference, Reversal $reversal=null, string $callBackUrl=null
Obtain a Financial Service Provider Balance Get an Account Balance viewAccountBalance array $accountIdentifier
Retrieve Transfers for a Financial Service Provider Retrieve a Set of Transactions for an Account viewAccountTransactions array $accountIdentifier, array $filter=null
Check for Service Availability Check for Service Availability viewServiceAvailability NA
Retrieve a Missing API Response Retrieve a Missing Response viewResponse string $clientCorrelationId, Object $objRef=null

Bill Payments

Scenarios API Function Parameters
Successful Retrieval of Bills Retrieve a Set of Bills viewAccountBills array $accountIdentifier, array $filter = null
Make a Successful Bill Payment with Callback Create a Bill Transaction createBillTransaction Transaction $transaction, string $callBackUrl = null
Make a Bill Payment createBillPayment array $accountIdentifier, string $billReference, BillPay $billPay, string $callBackUrl = null
Make a Bill Payment with Polling Make a Bill Payment createBillPayment array $accountIdentifier, string $billReference, BillPay $billPay, string $callBackUrl = null
Poll to Determine the Request State viewRequestState string $serverCorrelationId
Retrieve Bill Payments for a Given Bill viewBillPayment array $accountIdentifier, string $billReference, array $filter=null
Retrieval of Bill Payments Retrieve a Set of Bill Payments viewBillPayment array $accountIdentifier, string $billReference, array $filter=null
Check for Service Availability Check for Service Availability viewServiceAvailability NA
Retrieve a Missing API Response Retrieve a Missing Response viewResponse string $clientCorrelationId, Object $objRef=null

Agent Services

Scenarios API Function Parameters
Agent-initiated Cash-out Agent Initiated Cash-Out createWithdrawalTransaction Transaction $transaction, string $callBackUrl = null
Agent-initiated Cash-out using the Polling Method Agent Initiated Cash-out createWithdrawalTransaction Transaction $transaction, string $callBackUrl = null
Poll to Determine the Request State viewRequestState string $serverCorrelationId
Retrieve a Transaction viewTransaction string $transactionReference
Customer-initiated Cash-out Customer Initiated Cash-Out createWithdrawalTransaction Transaction $transaction, string $callBackUrl = null
Customer Cash-out at an ATM using an Authorisation Code Obtain an Authorisation Code createAuthorisationCode array $accountIdentifier, AuthorisationCode $authorisationCode
ATM Initiated Cash-Out createWithdrawalTransaction Transaction $transaction, string $callBackUrl = null
Retrieve Authorisation Code viewAuthorisationCode string $accountIdentifier, string $authorisationCode
Agent-initiated Customer Cash-in Retrieve the Name of the Depositing Customer viewAccountName array $accountIdentifier
Agent Initiated Cash-in createDepositTransaction Transaction $transaction, string $callBackUrl = null
Cash-out Reversal Perform a Transaction Reversal createReversal string $transactionReference, Reversal $reversal=null, string $callBackUrl=null
Register a Customer Mobile Money Account Create a Mobile Money Account createAccount Account $account, string $callBackUrl = null
Verify the KYC of a Customer Retrieve Account Information viewAccount array $accountIdentifier
Update KYC Verification Status updateAccountIdentity array $accountIdentifier, String identityId, array $patchData, string $callBackUrl=null
Obtain an Agent Balance Obtain an Agent Balance viewAccountBalance array $accountIdentifier
Retrieve Transactions for an Agent Retrieve a Set of Transactions for an Account viewAccountTransactions array $accountIdentifier, array $filter=null
Check for Service Availability Check for Service Availability viewServiceAvailability NA
Retrieve a Missing API Response Retrieve a Missing Response viewResponse string $clientCorrelationId, Object $objRef=null

Tests

The tests folder contains the test cases. These are logically divided in unit and integration tests. Integration tests require an active consumer key, consumer secret and api key.

  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-tests

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

composer run unit-tests 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/mmapi-php-sdk.git
cd mmapi-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.

    consumer_key = <your_consumer_key_here>
    consumer_secret = <your_consumer_secret_here>
    api_key = <your_api_key_here>
    callback_url = <your_callback_url_here>
  • Run each sample directly from the command line. For example:
php sample/MerchantPayment/InitiatePayment.php

About

Repository for PHP SDKs

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages