Getting started: MTN Mobile Money API with Python

Malende Fahad
4 min readNov 16, 2018

--

Screenshot of the momo developer website

Recently, MTN Uganda announced the official opening up of their mobile money platform to the developer community to foster innovation and improve financial inclusion. Developers will no longer need to go through painful bureaucracy with MTN headquarters or integrate with payment aggregators to leverage the power of MTN mobile money in their applications.

This is a step by step tutorial to show you how to integrate your python application with the MOMO api.

Steps summary:

  1. Sign up for an account
  2. Get a product subscription key
  3. Create an API user
  4. Create an API key
  5. Generate a JWT token
  6. Make authenticated API requests

1. Sign up for an account

Head over to https://momodeveloper.mtn.com/ and create your account. Once created, verify your account and sign in to the developer dashboard.

2. Get a product subscription key

The momo developer API is segmented into different products. Like; Collections, Remittances, Disbursement, and a collections widget. Find and Subscribe to the product that your application will be using. For the case of this tutorial, we shall subscribe to the collections product. It enables us to make a remote collection of fees and bills. Once subscribed, you shall be able to get a primary subscription key and a secondary subscription key in your developer dashboard.

3. Create an API user

The MOMO api relies heavily on uniquely identifying ID’s called UUIDs. python has a UUID library that can be used to generate random UUIDs. So you shall need to create one of those like this;

import uuidreference_id = str(uuid.uuid4())
print(reference_id)

To create an api user, you shall then have to make a POST request at this endpoint /v1_0/apiuser. Here is a sample python code snippet.

########### Python 2.7 #############
import httplib, urllib, base64, uuid,json
headers = {
# Request headers
'X-Reference-Id': '<put-your-reference-id-here>',
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '<put-your-primary-subscription-id here>',
}
params = urllib.urlencode({})body = json.dumps({
"providerCallbackHost": <your application domain> })
try:
conn = httplib.HTTPSConnection('ericssonbasicapi2.azure-api.net')
conn.request("POST", "/v1_0/apiuser?%s" % params, body, headers)
response = conn.getresponse()
print(response.status)
print(response.reason)
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################

This creates your api user, not your api key. We shall create an API key in the next step.

4. Create your API key.

Use the reference ID generated above when creating your API user to generate an API key. You shall need to make a POST request to /v1_0/apiuser/<put-your-reference-id-here>/apikey to generate your api key. Below is a sample python code snippet.

########### Python 2.7 #############
import httplib, urllib, base64, uuid,json
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '<put-your-primary-subscription-id here>'
}
params = urllib.urlencode({})body = json.dumps({
"providerCallbackHost": <your application domain> })
try:
conn = httplib.HTTPSConnection('ericssonbasicapi2.azure-api.net')
conn.request("POST", "/v1_0/apiuser/<put-your-reference-id-here>/apikey?%s" % params, body, headers)
response = conn.getresponse()
print(response.status)
print(response.reason)
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################

The response will be a JSON object with an api key.

201
Created
{"apiKey":"<api key string here>"}

5. Generate a secure JWT token

The last step in your authentication steps will be generating a JWT token. To know how these work, visit jwt.io. To generate your token you shall need to make an authenticated POSTrequest to the /colection/token endpoint.

Your request needs basic auth. that implies that you should create a string with api user and api key like this uuid-string-for-api-user:api-key-string and then encode it with the base64 library. The encoded string is attached to the Authorization header of your request.

Below is a sample python code snippet.

########### Python 2.7 #############
import httplib, urllib, base64
api_user = <replace with api user>api_key = <replace with api key>api_user_and_key = api_user+':'+api_keyencoded = base64.b64encode(api_user_and_key)headers = {
# Request headers
'Authorization': 'Basic '+encoded,
'Ocp-Apim-Subscription-Key': '<put-your-primary-subscription-id-here>',
}
params = urllib.urlencode({
})
try:
conn = httplib.HTTPSConnection('ericssonbasicapi2.azure-api.net')
conn.request("POST", "/collection/token/?%s" % params, "{body}", headers)
response = conn.getresponse()
print(response.status)
print(response.reason)
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################s################

The response will contain your secure token that can be used to interact with other parts of the API. It will look something like this

200
OK
{"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSMjU2In0.eyJjbGllbnRJZCI6IjQ2MmU1MzNmLTZkYjYtNDk4Ci04OTljLTBhNmRkY2E2ZDE5NSIsImV4cGlyZXMiOiIyMDE4LTExLTE2VDEzOjA1OjByLjExNyIsInNlc3Npb25JZCI6IjAxZGZlZDdlLTI5OGUtNDA5YS05NmI0LWJmODA0OWVkMzA5NCJ9.CureJ3-LnPCUpUAlB9oknqukQalqO1milbh4kBT3L6QTC7EJLApB46sEFszQ53hazvz_HvPIbAO20SxMQtrHN-VVGl8tZN92cAzO-nNdqts8s0LCdGY_Cjjk81ZL3v2cqv9bPxrzB8dp1i-YE6UePRSEqzROmzaywqazEntVYvQ66--uraaV1kdVp-1Gjo658ATu1uJtkWx6tvDD0j227a24gu5_3OoluAErcni3ziKtbKtk5Evu-WAPjcr6FyZrvfmMbkCYvN8NCem2VUe8RV5zL5K-1EKrSsHhsinsYZrS3kTblxPz8Z5t9OHgwH2HRZO_ITCYeiyVFwYMVFJktg","token_type":"access_token","expires_in":3600}

6. Make Authenticated API requests

With a valid JWT token at hand. you now wield the power to interact with most of the api endpoints. you can now interact with all endpoints of the product such as. collecting a payment from a mobile subscriber, sending out remittances, etc

Below is a simple use case for collecting an amount of UGX 5000 from a mobile subscriber.

########### Python 2.7 #############
import httplib, urllib, base64, uuid,json
token = <replace with token>
reference_id = str(uuid.uuid4())
headers = {
# Request headersi
'Authorization': 'Bearer '+token,
'X-Callback-Url': <replace with own http://myapp.com/momoapi/callback>,
'X-Reference-Id': refrence_id,
'X-Target-Environment': 'sandbox',
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '<put-your-primary-subscription-id-here>',
}
params = urllib.urlencode({})body = json.dumps({
"amount": "5000",
"currency": "UGX",
"externalId": "12345",
"payer": {
"partyIdType": "MSISDN",
"partyId": "0780123456"
},
"payerMessage": "test message",
"payeeNote": "test note"
})
try:
conn = httplib.HTTPSConnection('ericssonbasicapi2.azure-api.net')
conn.request("POST", "/collection/v1_0/requesttopay?%s" % params, body, headers)
response = conn.getresponse()
print(response.status)
print(response.reason)
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################

And that’s it. Hope this guide becomes the first step to you building something wonderful. Please clap and leave your feedback below.

--

--