This SDK provides for an easy way to connect to MTN MoMo API.
Please refer to the following documentation for installation instructions and usage information.
This document contains the following sections:
- Java JDK-1.8 or higher
- Apache Maven 3 or higher
- Build the jar file with tests using 'mvn clean package' command or without running tests using 'mvn clean package -Dmaven.test.skip=true'
- Import 'momoapi-java-sdk' jar file to your project's classpath
In order to build the SDK from the source code you need to use Apache Maven and Java 1.8+
- Tests for the SDK are in the src/test/java package.
- Rename
config.properties.sample
file insrc\test\resources
toconfig.properties
and replace placeholders with values for yourreference id
(also known asapi user
) ,api key
and for each of thesubscription keys
. - From the test package, run JUnit test for each test classes
All Java code snippets are listed here. Assumes that you have initialized the Java SDK before using them in your Development Environment. This section details the initialization of the Java SDK.
To initialize the Java SDK, we need to create an instance for the corresponding subscription.
When developing in the sandbox
environment, Sandbox User Provisioning
need to be completed to get an API User
(also known as referenceId) and API Key
, which are later used in a subscription for making requests.
Following is the code for initialising the UserProvisioningConfiguration
which can be used for creating UserProvisioningRequest
.
UserProvisioningConfiguration userProvisioningConfiguration = new UserProvisioningConfiguration("<place your SUBSCRIPTION_KEY>");
In the production
environment the provisioning is done through the Merchant Portal.
For Collection create an instance of CollectionConfiguration
with the respective subscription key
, reference id
(also known as api user
) and apiKey
. These are the default parameters and will point to sandbox environement
. Parameters required for production environement
are discussed in a later steps.
CollectionConfiguration collectionConfiguration = new CollectionConfiguration("<place your COLLECTION_SUBSCRIPTION_KEY>", "<place your REFERENCE_ID>", "<place your API_KEY>");
For Disbursement create an instance of DisbursementConfiguration
.
DisbursementConfiguration disbursementConfiguration = new DisbursementConfiguration("<place your DISBURSEMENT_SUBSCRIPTION_KEY>", "<place your REFERENCE_ID>", "<place your API_KEY>");
For Remittance create an instance of RemittanceConfiguration
.
RemittanceConfiguration remittanceConfiguration = new RemittanceConfiguration("<place your REMITTANCE_SUBSCRIPTION_KEY>", "<place your REFERENCE_ID>", "<place your API_KEY>");
You are required to create the corresponding <SUBSCRIPTION_TYPE>Configuration
instance as mentioned above, before making an API request with the SDK.
Following are the default parameters required in the SANDBOX mode
SUBSCRIPTION_KEY
(can be obtained from the developer portal for each product)referenceId
or theAPI User
(can be obtained throughSandbox User Provisioning
or from Merchant Portal for production)apiKey
the API Key (can be obtained throughSandbox User Provisioning
or from Merchant Portal for production)
Optional parameters available for <SUBSCRIPTION_TYPE>Configuration
class are:
Environment
value can be one of the followingEnvironment.SANDBOX
for SandboxEnvironment.PRODUCTION
for Production
targetEnvironment
value can be one of the following- A String that starts with
mtn
and followed by thecountry name
Eg:- mtnuganda
for Production Environment sandbox
for Sandbox Environment
- A String that starts with
Alternately, you can override the default configuration by using the following, explained here with an example using CollectionConfiguration
:
CollectionConfiguration collectionConfiguration = new CollectionConfiguration("<COLLECTION_SUBSCRIPTION_KEY>", "<REFERENCE_ID>", "<API_KEY>", "<mode>", "<targetEnvironment>");
For example:
CollectionConfiguration collectionConfiguration = new CollectionConfiguration("<COLLECTION_SUBSCRIPTION_KEY>", "<REFERENCE_ID>", "<API_KEY>", Environment.SANDBOX, TargetEnvironment.sandbox.getValue());
<SUBSCRIPTION_TYPE>Configuration
class has one optional method addCallBackUrl()
:
addCallBackUrl()
- Can be used in your application where you want MoMo API to push data as aPUT
request. This option is only available for API calls that acceptsX-Callback-Url
as a header. You can use this if you wish to specify different callback urls for different use cases. You can pass the callback url with each request seperately.
One important thing to keep in mind is that the CallBackUrl
is required to have a host address which is specified during the initial phase of user creation. In the sandbox environment, a CallBackHost
is passed in as a parameter during API User
creation. The CallBackUrl
must have the same host address as the CallBackHost
. In production, it needs to be specified in the Merchant Portal.
Eg:- If http://webhook.site/b6491e9b-8068-4703-8e21-ede56749c28a
is the CallBackUrl
, then webhook.site
is the CallBackHost
.
CallBackUrl
can be used in the following methods
Method 1 addCallBackUrl
method called with parameter CallBackUrl
during the configuration will act as a global value and can be used for all requests.
CollectionConfiguration collectionConfiguration = new CollectionConfiguration("<COLLECTION_SUBSCRIPTION_KEY>", "<REFERENCE_ID>", "<API_KEY>", Environment.SANDBOX, TargetEnvironment.sandbox.getValue()).addCallBackUrl("<CallBackUrl>");
Method 2 addCallBackUrl
method called with parameter CallBackUrl
on the collectionRequest
object will override the global value and all subsequent calls with collectionRequest
object will have this custom CallBackUrl
.
CollectionConfiguration collectionConfiguration = new CollectionConfiguration("<COLLECTION_SUBSCRIPTION_KEY>", "<REFERENCE_ID>", "<API_KEY>", Environment.SANDBOX, TargetEnvironment.sandbox.getValue()).addCallBackUrl("<CallBackUrl>");
CollectionRequest collectionRequest = collectionConfiguration.createCollectionRequest();
collectionRequest.addCallBackUrl("<CallBackUrl>").requestToPay(<requestPayObject>)
Method 3 addCallBackUrl
method called with parameter CallBackUrl
on the collectionConfiguration.createCollectionRequest()
object will override the global value, but here only this request is using the custom url, since we have not initialised any object of CollectionRequest
during the request.
CollectionConfiguration collectionConfiguration = new CollectionConfiguration("<COLLECTION_SUBSCRIPTION_KEY>", "<REFERENCE_ID>", "<API_KEY>", Environment.SANDBOX, TargetEnvironment.sandbox.getValue()).addCallBackUrl("<CallBackUrl>");
CollectionRequest collectionRequest = collectionConfiguration.createCollectionRequest();
collectionConfiguration.createCollectionRequest().addCallBackUrl("<CallBackUrl>").requestToPay(<requestPayObject>)
Error handling is a crucial aspect of software development. Both expected and unexpected errors should be handled by your code.
This Java SDK provides a MoMoException
class that is used for common scenarios where exceptions are thrown. The getMessage()
method can provide useful information to understand the cause of errors.
Payer payer = new Payer();
payer.setPartyId("<MSISDN_NUMBER>");
payer.setPartyIdType("<MSISDN>");
RequestPay requestPay = new RequestPay();
requestPay.setAmount("6.0");
requestPay.setCurrency("EUR");
requestPay.setExternalId("6353636");
requestPay.setPayeeNote("payer note");
requestPay.setPayerMessage("Pay for product a");
requestPay.setPayer(payer);
CollectionConfiguration collectionConfiguration = new CollectionConfiguration("<COLLECTION_SUBSCRIPTION_KEY>", "<REFERENCE_ID>", "<API_KEY>", Environment.SANDBOX, TargetEnvironment.sandbox.getValue()).addCallBackUrl(CALLBACK_URL);
CollectionRequest collectionRequest = collectionConfiguration.createCollectionRequest();
try {
collectionRequest.requestToPay(null);
} catch (MoMoException e) {
System.out.println(e.getMessage());
}
Sample Response:
{
"errorCategory": "Validation",
"errorCode": "MandatoryValueNotSupplied",
"errorDescription": "Request to Pay object is not initialized",
"errorDateTime": "2023-02-20 19:51:39 IST"
}
Scenarios | API | Function | Parameters |
---|---|---|---|
Sandbox User Provisioning | Creating an API user | createUser | CallbackHost callbackHost |
Get user details with referenceId | getUserDetails | String referenceId | |
Create ApiKey for a user | createApiKey | String referenceId |
Scenarios | API | Function | Parameters |
---|---|---|---|
Request To Pay | Request To Pay | requestToPay | RequestPay requestPay |
Request To Pay Transaction Status | requestToPayTransactionStatus | String referenceId | |
Request To Pay Delivery Notification | requestToPayDeliveryNotification | String referenceId, DeliveryNotification deliveryNotification, (optional)String deliveryNotificationHeader | |
Request To Withdraw | Request To Withdraw-V1 | requestToWithdrawV1 | Withdraw withdraw |
Request To Withdraw-V2 | requestToWithdrawV2 | Withdraw withdraw | |
Request To Withdraw Transaction Status | requestToWithdrawTransactionStatus | String referenceId | |
Get UserInfo With Consent | Get UserInfo With Consent | getUserInfoWithConsent | AccountHolder accountHolder, String scope, AccessType accessType |
Get Basic Userinfo | Get Basic Userinfo | getBasicUserinfo | String msisdn |
Validate Account Holder Status | Validate Account Holder Status | validateAccountHolderStatus | AccountHolder accountHolder |
Get Account Balance | Get Account Balance | getAccountBalance | NA |
Get Account Balance In Specific Currency | Get Account Balance In Specific Currency | getAccountBalanceInSpecificCurrency | String currency |
Scenarios | API | Function | Parameters |
---|---|---|---|
Transfer | Transfer | transfer | Transfer transfer |
Get Transfer Status | getTransferStatus | String referenceId | |
Request To Pay Delivery Notification | Request To Pay Delivery Notification | requestToPayDeliveryNotification | String referenceId, DeliveryNotification deliveryNotification, (optional)String deliveryNotificationHeader |
Deposit | Deposit-V1 | depositV1 | Deposit deposit |
Deposit-V2 | depositV2 | Deposit deposit | |
Get Deposit Status | getDepositStatus | String referenceId | |
Refund | Refund-V1 | refundV1 | Refund refund |
Refund-V2 | refundV2 | Refund refund | |
Get Refund Status | getRefundStatus | String referenceId | |
Get UserInfo With Consent | Get UserInfo With Consent | getUserInfoWithConsent | AccountHolder accountHolder, String scope, AccessType accessType |
Get Basic Userinfo | Get Basic Userinfo | getBasicUserinfo | String msisdn |
Validate Account Holder Status | Validate Account Holder Status | validateAccountHolderStatus | AccountHolder accountHolder |
Get Account Balance | Get Account Balance | getAccountBalance | NA |
Get Account Balance In Specific Currency | Get Account Balance In Specific Currency | getAccountBalanceInSpecificCurrency | String currency |
Scenarios | API | Function | Parameters |
---|---|---|---|
Transfer | Transfer | transfer | Transfer transfer |
Get Transfer Status | getTransferStatus | String referenceId | |
Request To Pay Delivery Notification | Request To Pay Delivery Notification | requestToPayDeliveryNotification | String referenceId, DeliveryNotification deliveryNotification, (optional)String deliveryNotificationHeader |
Get UserInfo With Consent | Get UserInfo With Consent | getUserInfoWithConsent | AccountHolder accountHolder, String scope, AccessType accessType |
Get Basic Userinfo | Get Basic Userinfo | getBasicUserinfo | String msisdn |
Validate Account Holder Status | Validate Account Holder Status | validateAccountHolderStatus | AccountHolder accountHolder |
Get Account Balance | Get Account Balance | getAccountBalance | NA |
The test
package contains the test cases. These are logically divided into unit and integration tests. The test commands(Eg:- mvn test
) must be run from the directory where pom.xml
file is located.
Those tests are located in src/test/java/com/momo/api/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 our testing harness.
To run unit tests,
mvn test -Dtest=com.momo.api.unit.**
Those tests are located in src/test/java/com/momo/api/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.
For integration test:
- You will need a valid
subscription key
,reference id
(also known asapi user
) andapiKey
. - Copy the config.properties.sample file to config.properties and enter your credentials in the appropriate fields.
To run the integration tests,
mvn test -Dtest=com.momo.api.integration.**
To run tests individually:
mvn test -Dtest=path/to/test/class/file
For example:
mvn test -Dtest=com.momo.api.unit.CollectionRequestTest.java
mvn test
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 https://github.com/gsmainclusivetechlab/momoapi-java-sdk.git
- Import
momoapi-java-sdk-samples
project into your IDE - Import 'momoapi-java-sdk' jar file into your
momoapi-java-sdk-samples
project's classpath - Rename
config.properties.sample
file insrc\test\resources
toconfig.properties
and replace placeholders with values for yourconsumer key
,consumer secret
andapi key
.
For example:
COLLECTION_SUBSCRIPTION_KEY=<your_collection_subscription_key_here>
DISBURSEMENT_SUBSCRIPTION_KEY=<your_disbursement_subscription_key_here>
REMITTANCE_SUBSCRIPTION_KEY=<your_remittance_subscription_key_here>
CONSUMER_SECRET=<your_consumer_secret_here>
REFERENCE_ID=<your_api_user/referenceId_value _here>
API_KEY=<your_api_key_here>
CALLBACK_URL=<your_callback_url_here>
You are now ready to run your sample codes.
- Run individual samples