Welcome to the MoMoPSBAPI Python SDK! This SDK enables developers to integrate with the MTN MoMo API for managing API users, API keys, OAuth 2.0 tokens, and payment processing in a seamless manner. Below, you'll find a comprehensive guide on installation, usage, and functionality.
- Create and manage API Users
- Generate API Keys for secure communication
- Obtain OAuth 2.0 tokens for authentication
- Initiate and manage payment requests
- Validate API responses
- MTN MoMo Developer Account: # Here
- Collection and Disbursement subscription keys
- Collection and Disbursement subscription keys
- API User ID and API Key
Install the required dependencies:
pip install momo-psb
from momo_psb import MoMoPSBAPI
# Replace with your details
BASE_URL = "https://sandbox.momodeveloper.mtn.com"
SUBSCRIPTION_KEY = "your_subscription_key"
# Initialize the API client
api = MoMoPSBAPI(base_url=BASE_URL, subscription_key=SUBSCRIPTION_KEY)
Generate a unique API User.
import uuid
reference_id = str(uuid.uuid4()) # Generate a unique reference ID
callback_host = "https://your-callback-host.com"
response = api.create_api_user(reference_id, callback_host)
print("Status Code:", response.status_code)
print("Response:", response.json())
Create an API Key for the generated API User.
api_user = "your_api_user_id"
response = api.create_api_key(api_user)
print("Status Code:", response.status_code)
print("API Key:", response.json().get("apiKey"))
Fetch details of an API User.
response = api.get_api_user_details(api_user)
print("Status Code:", response.status_code)
print("User Details:", response.json())
Generate an access token for authorization.
api_key = "your_api_key"
response = api.get_oauth_token(api_user, api_key)
print("Status Code:", response.status_code)
token_data = response.json()
access_token = token_data.get("access_token")
print("Access Token:", access_token)
Initiate a payment request from a consumer.
payer_info = {
"partyIdType": "MSISDN",
"partyId": "+2348056042384"
}
reference_id = str(uuid.uuid4())
response = api.request_to_pay(
reference_id=reference_id,
access_token=access_token,
amount="100.00",
currency="EUR",
external_id=str(uuid.uuid4()),
payer=payer_info,
payer_message="Payment for services",
payee_note="Thank you for your payment"
)
print("Status Code:", response.status_code)
print("Response:", response.json())
Use the validate_response
method to handle errors gracefully.
try:
data = api.validate_response(response)
print("Success:", data)
except Exception as e:
print("Error:", e)
- Environment Setup:
- Default environment is
sandbox
. Update the base URL for production use.
- Default environment is
- Status Codes:
200
,201
,202
: Successful operations.- Other codes indicate errors and should be handled appropriately.
- Unique Identifiers:
- Use
uuid.uuid4()
to generate reference IDs for requests.
- Use