MPESA API Reference

mpesa.kenya

Kenya MPESA SDK Implementation.

class mpesa.kenya.API(env: str = 'sandbox', app_key: Optional[str] = None, app_secret: Optional[str] = None)[source]

Bases: object

Kenya’s Daraja MPESA API.

Parameters:
  • env (str) – The target environment defaults "sandbox" "sandbox" or "production".

  • app_key (str) – The app_key from developers portal.

  • app_secret (str) – The app_secret from developers portal.

Attributes

sandbox_url

The sandbox environment host url “https://sandbox.safaricom.co.ke

live_url

The live/production environment host url “https://api.safaricom.co.ke

Methods.

authenticate()[source]

To make Mpesa API calls, you will need to authenticate your app.

This method is used to fetch the access token required by Mpesa. Mpesa supports client_credentials grant type.

To authorize your API calls to Mpesa, you will need a Basic Auth over HTTPS authorization token.

The Basic Auth string is a base64 encoded string of your app’s client key and client secret.

Returns:

access_token This token is to be used with the Bearer header for further API calls to Mpesa.

Return type:

str

property authentication_token

Return Authentication Token.

b2b(initiator: Optional[str] = None, security_credential: Optional[str] = None, command_id: Optional[str] = None, sender_identifier_type: Optional[str] = None, receiver_identifier_type: Optional[str] = None, amount: Optional[str] = None, party_a: Optional[str] = None, party_b: Optional[str] = None, remarks: Optional[str] = None, account_reference: Optional[str] = None, queue_timeout_url: Optional[str] = None, result_url: Optional[str] = None)[source]

Uses the B2B API to transact from one company to another.

Parameters:
  • initiator (str) – Username used to authenticate the transaction.

  • security_credential (str) – Generate from developer portal

  • command_id (str) –

    Options:

    • BusinessPayBill,

    • BusinessBuyGoods,

    • DisburseFundsToBusiness,

    • BusinessToBusinessTransfer,

    • BusinessTransferFromMMFToUtility,

    • BusinessTransferFromUtilityToMMF,

    • MerchantToMerchantTransfer,

    • MerchantTransferFromMerchantToWorking,

    • MerchantServicesMMFAccountTransfer,

    • AgencyFloatAdvance

  • sender_identifier_type (str) – 2 for Till Number, 4 for organization shortcode.

  • receiver_identifier_type (str) – 2 for Till Number, 4 for organization shortcode.

  • amount (str) – Amount.

  • party_a (str) – Sender shortcode.

  • party_b (str) – Receiver shortcode.

  • remarks (str) – Remarks.

  • account_reference (str) – Use if doing paybill to banks etc.

  • queue_timeout_url (str) – The url that handles information of timed out transactions.

  • result_url (str) – The url that receives results from M-Pesa api call.

Returns:

Dict object of

  • OriginatorConverstionID (str): The unique request ID for tracking a transaction.

  • ConversationID (str): The unique request ID returned by mpesa for each request made

  • ResponseDescription (str): Response Description message

Return type:

dict

b2c(initiator_name: Optional[str] = None, security_credential: Optional[str] = None, command_id: Optional[str] = None, amount: Optional[str] = None, party_a: Optional[str] = None, party_b: Optional[str] = None, remarks: Optional[str] = None, queue_timeout_url: Optional[str] = None, result_url: Optional[str] = None, occassion: Optional[str] = None)[source]

This method uses Mpesa’s B2C API to transact between an M-Pesa short code to a phone number registered on M-Pesa..

Parameters:
  • initiator_name (str) – Username used to authenticate the transaction.

  • security_credential (str) – Generate from developer portal

  • command_id (str) –

    Options:

    • SalaryPayment,

    • BusinessPayment,

    • PromotionPayment.

  • amount (str) – Amount.

  • party_a (str) –

    Organization/MSISDN making the transaction

    • Shortcode (6 digits)

    • MSISDN (12 digits).

  • party_b (str) – MSISDN receiving the transaction (12 digits).

  • remarks (str) – Comments that are sent along with the transaction(maximum 100 characters).

  • account_reference (str) – Use if doing paybill to banks etc.

  • queue_timeout_url (str) – The url that handles information of timed out transactions.

  • result_url (str) – The url that receives results from M-Pesa api call.

  • ocassion (str) – occasion.

Returns:

Dict object of

  • OriginatorConverstionID (str): The unique request ID for tracking a transaction.

  • ConversationID (str): The unique request ID returned by mpesa for each request made

  • ResponseDescription (str): Response Description message

Return type:

dict

Example:

{
"ConversationID": "AG_20180326_00005ca7f7c21d608166",
"OriginatorConversationID": "12363-1328499-6",
"ResponseCode": "0",
"ResponseDescription": "Accept the service request successfully."
}
balance(initiator: Optional[str] = None, security_credential: Optional[str] = None, command_id: Optional[str] = None, party_a: Optional[str] = None, identifier_type: Optional[str] = None, remarks: Optional[str] = None, queue_timeout_url: Optional[str] = None, result_url: Optional[str] = None)[source]

This method uses Mpesa’s Account Balance API to to enquire the balance on an M-Pesa BuyGoods (Till Number).

Parameters:
  • initiator (str) – Username used to authenticate the transaction.

  • security_credential (str) – Generate from developer portal.

  • command_id (str) – AccountBalance.

  • party_a (str) – Till number being queried.

  • identifier_type (str) –

    Type of organization receiving the transaction.

    Identifier Type sOptions

    identifier_type

    description

    1

    MSISDN

    2

    Till Number

    4

    Organization short code

  • remarks (str) – Comments that are sent along with the transaction(maximum 100 characters).

  • queue_timeout_url (str) – The url that handles information of timed out transactions.

  • result_url (str) – The url that receives results from M-Pesa api call.

Returns:

Dict object of

  • OriginatorConverstionID (str): The unique request ID for tracking a transaction.

  • ConversationID (str): The unique request ID returned by mpesa for each request made

  • ResponseDescription (str): Response Description message

Return type:

dict

c2b_register_url(shortcode: Optional[str] = None, response_type: Optional[str] = None, confirmation_url: Optional[str] = None, validation_url: Optional[str] = None)[source]

This method uses Mpesa’s C2B API to register validation and confirmation URLs on M-Pesa.

Parameters:
  • shortcode (str) – The short code of the organization.

  • response_type (str) – Default response type for timeout. Incase a tranaction times out, Mpesa will by default "Complete" or "Cancel" the transaction.

  • confirmation_url (str) – Confirmation URL for the client.

  • validation_url (str) – Validation URL for the client.

Returns:

Dict object of

  • OriginatorConversationID (str): The unique request ID for tracking a transaction.

  • ConversationID (str): The unique request ID returned by mpesa for each request made

  • ResponseDescription (str): Response Description message

Return type:

dict

Example:

{
  "ConversationID": "",
  "OriginatorCoversationID": "",
  "ResponseDescription": "success"
}
c2b_simulate(shortcode: Optional[str] = None, command_id: Optional[str] = None, amount: Optional[str] = None, msisdn: Optional[str] = None, bill_ref_number: Optional[str] = None)[source]

This method uses Mpesa’s C2B API to simulate a C2B transaction.

Parameters:
  • shortcode (str) – The short code of the organization.

  • command_id (str) –

    Unique command for each transaction type.

    • CustomerPayBillOnline

    • CustomerBuyGoodsOnline.

  • amount (str) – The amount being transacted

  • msisdn (str) – Phone number (msisdn) initiating the transaction MSISDN(12 digits)

  • bill_ref_number (str) – Optional

Returns:

Dict object of

  • OriginatorConverstionID (str): The unique request ID for tracking a transaction.

  • ConversationID (str): The unique request ID returned by mpesa for each request made

  • ResponseDescription (str): Response Description message

Return type:

dict

Example:

{
  "ConversationID": "AG_20180324_000066530b914eee3f85",
  "OriginatorCoversationID": "25344-885903-1",
  "ResponseDescription": "Accept the service request successfully."
}
lnmo_status(business_shortcode: Optional[str] = None, checkout_request_id: Optional[str] = None, passcode: Optional[str] = None)[source]

This method uses Mpesa’s Express API to check the status of a Lipa Na M-Pesa Online Payment..

Parameters:
  • business_shortcode (str) – This is organizations shortcode (Paybill or Buygoods - A 5 to 6 digit account number) used to identify an organization and receive the transaction.

  • checkout_request_id (str) – This is a global unique identifier of the processed checkout transaction request.

  • passcode (str) – Get from developer portal

Returns:

Dict object of

  • CustomerMessage (str):

  • CheckoutRequestID (str):

  • ResponseDescription (str):

  • MerchantRequestID (str):

  • ResponseCode (str):

Return type:

dict

lnmo_stkpush(business_shortcode: Optional[str] = None, passcode: Optional[str] = None, amount: Optional[str] = None, callback_url: Optional[str] = None, reference_code: Optional[str] = None, phone_number: Optional[str] = None, description: Optional[str] = None)[source]

This method uses Mpesa’s Express API to initiate online payment on behalf of a customer..

Parameters:
  • business_shortcode (str) – The short code of the organization.

  • passcode (str) – Get from developer portal

  • amount (str) – The amount being transacted

  • callback_url (str) – A CallBack URL is a valid secure URL that is used to receive notifications from M-Pesa API.

  • reference_code (str) – Account Reference: This is an Alpha-Numeric parameter that is defined by your system as an Identifier of the transaction for CustomerPayBillOnline transaction type.

  • phone_number (str) – The Mobile Number to receive the STK Pin Prompt.

  • description (str) – This is any additional information/comment that can be sent along with the request from your system. MAX 13 characters

Returns:

Dict object of

  • CustomerMessage (str):

  • CheckoutRequestID (str):

  • ResponseDescription (str):

  • MerchantRequestID (str):

  • ResponseCode (str):

Return type:

dict

Example:

{
   "MerchantRequestID": "25353-1377561-4",
   "CheckoutRequestID": "ws_CO_26032018185226297",
   "ResponseCode": "0",
   "ResponseDescription": "Success. Request accepted for processing",
   "CustomerMessage": "Success. Request accepted for processing"
}
reverse(initiator: Optional[str] = None, security_credential: Optional[str] = None, command_id='TransactionReversal', transaction_id: Optional[str] = None, amount: Optional[str] = None, receiver_party: Optional[str] = None, receiver_identifier_type: Optional[str] = None, queue_timeout_url: Optional[str] = None, result_url: Optional[str] = None, remarks: Optional[str] = None, occassion: Optional[str] = None)[source]

This method uses Mpesa’s Transaction Reversal API to reverse a M-Pesa transaction.

Parameters:
  • initiator (str) – Username used to authenticate the transaction.

  • security_credential (str) – Generate from developer portal

  • command_id (str) – TransactionReversal

  • transaction_id (str) – Unique identifier to identify a transaction on M-Pesa.

  • amount (str) – The amount being transacted

  • receiver_party (str) –

    Organization/MSISDN making the transaction

    • Shortcode (6 digits)

    • MSISDN (12 digits).

  • receiver_identifier_type (str) – MSISDN receiving the transaction (12 digits).

  • queue_timeout_url (str) – The url that handles information of timed out transactions.

  • result_url (str) – The url that receives results from M-Pesa api call.

  • remarks (str) – Comments that are sent along with the transaction(maximum 100 characters)

  • occassion (str) – Occassion

Returns:

Dict object of

  • OriginatorConverstionID (str): The unique request ID for tracking a transaction.

  • ConversationID (str): The unique request ID returned by mpesa for each request made

  • ResponseDescription (str): Response Description message

Return type:

dict

Example:

{
   "Result":
   {
    "ResultType":0,
    "ResultCode":0,
    "ResultDesc":"The service request has been accepted successfully.",
    "OriginatorConversationID":"10819-695089-1",
    "ConversationID":"AG_20170727_00004efadacd98a01d15",
    "TransactionID":"LGR019G3J2",
    "ReferenceData":
    {
     "ReferenceItem":
     {
       "Key":"QueueTimeoutURL",
       "Value":"https://internalsandbox.safaricom.co.ke/mpesa/reversalresults/v1/submit"
     }
    }
   }
 }
transaction_status(party_a: Optional[str] = None, identifier_type: Optional[str] = None, remarks: Optional[str] = None, initiator: Optional[str] = None, passcode: Optional[str] = None, result_url: Optional[str] = None, queue_timeout_url: Optional[str] = None, transaction_id: Optional[str] = None, occassion: Optional[str] = None, shortcode: Optional[str] = None)[source]

This method uses Mpesa’s Transaction Status API to check the status of a transaction.

Parameters:
  • party_a (str) –

    Organization/MSISDN receiving the transaction

    • MSISDN or

    • shortcode.

  • identifier_type (str) –

    Type of organization receiving the transaction

    identifier types

    identifier_type

    description

    1

    MSISDN

    2

    Till Number

    3

    Shortcode

  • remarks (str) – Comments that are sent along with the transaction(maximum 100 characters).

  • initiator (str) – This is the credential/username used to authenticate the transaction request.

  • passcode (str) – Get from developer portal

  • result_url (str) – The url that handles information from the mpesa API call.

  • transaction_id (str) – Unique identifier to identify a transaction on M-Pesa.

  • queue_timeout_url (str) – The url that stores information of timed out transactions.

  • shortcode (str) – The short code of the organization.

  • occassion (str) – Occasion

Returns:

Dict object of

  • ResultDesc: ,

  • CheckoutRequestID: ,

  • ResponseDescription: ,

  • MerchantRequestID: ,

  • ResponseCode: ,

  • ResultCode:

Return type:

dict

mpesa.tanzania

Tanzania MPESA SDK Implementation.

class mpesa.tanzania.API(public_key: str, api_key: str, env: str = 'sandbox')[source]

Bases: object

Tanzania Market API.

Parameters:
  • public_key (str.) – Public key from developers portal.

  • api_key (str.) – API key from developers portal.

  • env (str, optional.) – Environment either "sandbox" or "production", defaults "sandbox".

Attributes.

sandbox_path

The sandbox prefix path "/sandbox/ipg/v2/vodacomTZN/".

live_path

The live/openapi prefix path "/openapi/ipg/v2/vodacomTZN/".

Currency

The Currency used for this API. default "TZS".

Country

The Country used for this API. default "TZN".

Methods.

b2b(Amount: str, PrimaryPartyCode: str, ReceiverPartyCode: str, ThirdPartyConversationID: str, TransactionReference: str, PurchasedItemsDesc: str, **kwargs)[source]

B2B Single Stage.

The B2B API Call is used for business-to-business transactions.

Funds from the business’ mobile money wallet will be deducted and transferred to the mobile money wallet of the other business.

Use cases for the B2B includes:

  • Stock purchases

  • Bill payment

  • Adhoc payment

Parameters:
  • Amount (str.) – Amount.

  • ReceiverPartyCode (str.) – Receiver Party Code.

  • PrimaryPartyCode (str.) – Primary Party Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • TransactionReference (str.) – Transaction Reference.

  • PurchasedItemsDesc (str.) – Purchased Items Description.

Returns:

A dictionary object from the B2B API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}
b2c(Amount: str, CustomerMSISDN: str, ServiceProviderCode: str, ThirdPartyConversationID: str, TransactionReference: str, PaymentItemsDesc: str, **kwargs)[source]

B2C Single Stage.

The B2C API Call is used as a standard business-to-customer funds disbursement.

Funds from the business account’s wallet will be deducted and paid to the mobile money wallet of the customer.

Use cases for the B2C includes:

  • Salary payments

  • Funds transfers from business

  • Charity pay-out

Parameters:
  • Amount (str.) – Amount.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • TransactionReference (str.) – Transaction Reference.

  • PaymentItemsDesc (str.) – Payment Items Description.

Returns:

A dictionary object from the B2C API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}
c2b(Amount: str, CustomerMSISDN: str, ServiceProviderCode: str, ThirdPartyConversationID: str, TransactionReference: str, PurchasedItemsDesc: str, **kwargs)[source]

C2B Single Stage.

Parameters:
  • Amount (str.) – Amount.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • TransactionReference (str.) – Transaction Reference.

  • PurchasedItemsDesc (str.) – Purchased Items Description.

Returns:

A dictionary object from the C2B API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}
direct_debit_create(AgreedTC: str, CustomerMSISDN: str, ServiceProviderCode: str, ThirdPartyConversationID: str, ThirdPartyReference: str, StartRangeOfDays: str, EndRangeOfDays: str, ExpiryDate: str, FirstPaymentDate: str, Frequency: str, **kwargs)[source]

Direct Debit Create API.

Direct Debits are payments in M-Pesa that are initiated by the Payee alone without any Payer interaction, but permission must first be granted by the Payer.

The granted permission from the Payer to Payee is commonly termed a ‘Mandate’, and M-Pesa must hold details of this Mandate.

The Direct Debit API set allows an organisation to get the initial consent of their customers to create the Mandate that allows the organisation to debit customer’s account at an agreed frequency and amount for services rendered.

After the initial consent, the debit of the account will not involve any customer interaction.

The Direct Debit feature makes use of the following API calls:

  • Create a Direct Debit mandate

  • Pay a mandate

The customer is able to view and cancel the Direct Debit mandate from G2 menu accessible via USSD menu or the Smartphone Application.

Parameters:
  • AgreedTC (str.) – The customer agreed to the terms and conditions. Can only use 1 or 0.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • ThirdPartyReference (str.) – Third Party Reference.

  • StartRangeOfDays (str, optional.) – The start range of days in the month.

  • EndRangeOfDays (str, optional.) – The end range of days in the month.

  • ExpiryDate (str, optional.) – The expiry date of the Mandate.

  • FirstPaymentDate (str, optional.) – The Start date of the Mandate.

  • Frequency (str, optional.) – The frequency of the payments.

List of Possible Frequency Values.

Frequency

Description

01

Once off

02

Daily

03

Weekly

04

Monthly

05

Quarterly

06

Half Yearly

07

Yearly

08

On Demand

Returns:

A dictionary object from the DirectDebitCreation API.

Return type:

dict.

Example:

{
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionReference": "vgisfyn4b22w6tmqjftatq75lyuie6vc",
  "ConversationID": "51a1d9191acc4674ab1dfd321a24ba20",
  "ThirdPartyConversationID": "AAA6d1f9391a0052de0b5334a912jbsj1j2kk"
}
direct_debit_payment(Amount: str, CustomerMSISDN: str, ServiceProviderCode: str, ThirdPartyConversationID: str, ThirdPartyReference: str, **kwargs)[source]

Direct Debit Payment.

The Direct Debit API set allows an organisation to get the initial consent of their customers to create the Mandate that allows the organisation to debit customer’s account at an agreed frequency and amount for services rendered.

After the initial consent, the debit of the account will not involve any customer interaction.

The Direct Debit feature makes use of the following API calls:

  • Create a Direct Debit mandate

  • Pay a mandate

The customer is able to view and cancel the Direct Debit mandate from G2 menu accessible via USSD menu or the Smartphone Application.

Parameters:
  • Amount (str.) – Amount.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • ThirdPartyReference (str.) – Third Party Reference.

Returns:

A dictionary object from the DirectDebitPayment API.

Return type:

dict.

Example:

{
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionReference": "vgisfyn4b22w6tmqjftatq75lyuie6vc",
  "ConversationID": "51a1d9191acc4674ab1dfd321a24ba20",
  "ThirdPartyConversationID": "AAA6d1f9391a0052de0b5334a912jbsj1j2kk"

}
reverse(ReversalAmount: str, ServiceProviderCode: str, ThirdPartyConversationID: str, TransactionID: str, **kwargs)[source]

Reversal API.

The Reversal API is used to reverse a successful transaction. Using the Transaction ID of a previously successful transaction, the OpenAPI will withdraw the funds from the recipient party’s mobile money wallet and revert the funds to the mobile money wallet of the initiating party of the original transaction.

Parameters:
  • ReversalAmount (str.) – Reversal Amount.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • TransactionID (str.) – Transaction ID.

Returns:

A dictionary object from the Reversal API.

Return type:

dict.

Example:

{
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}
property session_id: str

Return session_id.

Returns:

The sessionID to be used in subsequent requests.

Return type:

str.

transaction_status(QueryReference: str, ServiceProviderCode: str, ThirdPartyConversationID: str, **kwargs)[source]

Query Transaction Status.

The Query Transaction Status API call is used to query the status of the transaction that has been initiated.

Parameters:
  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • QueryReference (str.) – Query Reference.

Returns:

A dictionary object from the QueryTransactionStatus API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "ResponseTransactionStatus": "Completed",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}

mpesa.ghana

Ghana MPESA SDK Implementation.

class mpesa.ghana.API(public_key: str, api_key: str, env: str = 'sandbox')[source]

Bases: object

Ghana Market API.

Parameters:
  • public_key (str.) – Public key from developers portal.

  • api_key (str.) – API key from developers portal.

  • env (str, optional.) – Environment either "sandbox" or "production", defaults "sandbox".

Attributes.

sandbox_path

The sandbox prefix path "/sandbox/ipg/v2/vodafoneGHA/".

live_path

The live/openapi prefix path "/openapi/ipg/v2/vodafoneGHA/".

Currency

The Currency used for this API. default "GHS".

Country

The Country used for this API. default "GHA".

Methods.

b2b(Amount: str, PrimaryPartyCode: str, ReceiverPartyCode: str, ThirdPartyConversationID: str, TransactionReference: str, PurchasedItemsDesc: str, **kwargs)[source]

B2B Single Stage.

The B2B API Call is used for business-to-business transactions.

Funds from the business’ mobile money wallet will be deducted and transferred to the mobile money wallet of the other business.

Use cases for the B2B includes:

  • Stock purchases

  • Bill payment

  • Adhoc payment

Parameters:
  • Amount (str.) – Amount.

  • ReceiverPartyCode (str.) – Receiver Party Code.

  • PrimaryPartyCode (str.) – Primary Party Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • TransactionReference (str.) – Transaction Reference.

  • PurchasedItemsDesc (str.) – Purchased Items Description.

Returns:

A dictionary object from the B2B API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}
b2c(Amount: str, CustomerMSISDN: str, ServiceProviderCode: str, ThirdPartyConversationID: str, TransactionReference: str, PaymentItemsDesc: str, **kwargs)[source]

B2C Single Stage.

The B2C API Call is used as a standard business-to-customer funds disbursement.

Funds from the business account’s wallet will be deducted and paid to the mobile money wallet of the customer.

Use cases for the B2C includes:

  • Salary payments

  • Funds transfers from business

  • Charity pay-out

Parameters:
  • Amount (str.) – Amount.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • TransactionReference (str.) – Transaction Reference.

  • PaymentItemsDesc (str.) – Payment Items Description.

Returns:

A dictionary object from the B2C API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}
c2b(Amount: str, CustomerMSISDN: str, ServiceProviderCode: str, ThirdPartyConversationID: str, TransactionReference: str, PurchasedItemsDesc: str, **kwargs)[source]

C2B Single Stage.

Parameters:
  • Amount (str.) – Amount.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • TransactionReference (str.) – Transaction Reference.

  • PurchasedItemsDesc (str.) – Purchased Items Description.

Returns:

A dictionary object from the C2B API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}
direct_debit_create(AgreedTC: str, CustomerMSISDN: str, ServiceProviderCode: str, ThirdPartyConversationID: str, ThirdPartyReference: str, StartRangeOfDays: str, EndRangeOfDays: str, ExpiryDate: str, FirstPaymentDate: str, Frequency: str, **kwargs)[source]

Direct Debit Create API.

Direct Debits are payments in M-Pesa that are initiated by the Payee alone without any Payer interaction, but permission must first be granted by the Payer.

The granted permission from the Payer to Payee is commonly termed a ‘Mandate’, and M-Pesa must hold details of this Mandate.

The Direct Debit API set allows an organisation to get the initial consent of their customers to create the Mandate that allows the organisation to debit customer’s account at an agreed frequency and amount for services rendered.

After the initial consent, the debit of the account will not involve any customer interaction.

The Direct Debit feature makes use of the following API calls:

  • Create a Direct Debit mandate

  • Pay a mandate

The customer is able to view and cancel the Direct Debit mandate from G2 menu accessible via USSD menu or the Smartphone Application.

Parameters:
  • AgreedTC (str.) – The customer agreed to the terms and conditions. Can only use 1 or 0.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • ThirdPartyReference (str.) – Third Party Reference.

  • StartRangeOfDays (str, optional.) – The start range of days in the month.

  • EndRangeOfDays (str, optional.) – The end range of days in the month.

  • ExpiryDate (str, optional.) – The expiry date of the Mandate.

  • FirstPaymentDate (str, optional.) – The Start date of the Mandate.

  • Frequency (str, optional.) – The frequency of the payments.

List of Possible Frequency Values.

Frequency

Description

01

Once off

02

Daily

03

Weekly

04

Monthly

05

Quarterly

06

Half Yearly

07

Yearly

08

On Demand

Returns:

A dictionary object from the DirectDebitCreation API.

Return type:

dict.

Example:

{
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionReference": "vgisfyn4b22w6tmqjftatq75lyuie6vc",
  "ConversationID": "51a1d9191acc4674ab1dfd321a24ba20",
  "ThirdPartyConversationID": "AAA6d1f9391a0052de0b5334a912jbsj1j2kk"
}
direct_debit_payment(Amount: str, CustomerMSISDN: str, ServiceProviderCode: str, ThirdPartyConversationID: str, ThirdPartyReference: str, **kwargs)[source]

Direct Debit Payment.

The Direct Debit API set allows an organisation to get the initial consent of their customers to create the Mandate that allows the organisation to debit customer’s account at an agreed frequency and amount for services rendered.

After the initial consent, the debit of the account will not involve any customer interaction.

The Direct Debit feature makes use of the following API calls:

  • Create a Direct Debit mandate

  • Pay a mandate

The customer is able to view and cancel the Direct Debit mandate from G2 menu accessible via USSD menu or the Smartphone Application.

Parameters:
  • Amount (str.) – Amount.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • ThirdPartyReference (str.) – Third Party Reference.

Returns:

A dictionary object from the DirectDebitPayment API.

Return type:

dict.

Example:

{
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionReference": "vgisfyn4b22w6tmqjftatq75lyuie6vc",
  "ConversationID": "51a1d9191acc4674ab1dfd321a24ba20",
  "ThirdPartyConversationID": "AAA6d1f9391a0052de0b5334a912jbsj1j2kk"

}
reverse(ReversalAmount: str, ServiceProviderCode: str, ThirdPartyConversationID: str, TransactionID: str, **kwargs)[source]

Reversal API.

The Reversal API is used to reverse a successful transaction. Using the Transaction ID of a previously successful transaction, the OpenAPI will withdraw the funds from the recipient party’s mobile money wallet and revert the funds to the mobile money wallet of the initiating party of the original transaction.

Parameters:
  • ReversalAmount (str.) – Reversal Amount.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • TransactionID (str.) – Transaction ID.

Returns:

A dictionary object from the Reversal API.

Return type:

dict.

Example:

{
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}
property session_id: str

Return session_id.

Returns:

The sessionID to be used in subsequent requests.

Return type:

str.

transaction_status(QueryReference: str, ServiceProviderCode: str, ThirdPartyConversationID: str, **kwargs)[source]

Query Transaction Status.

The Query Transaction Status API call is used to query the status of the transaction that has been initiated.

Parameters:
  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyConversationID (str.) – Third Party Conversation ID.

  • QueryReference (str.) – Query Reference.

Returns:

A dictionary object from the QueryTransactionStatus API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "ResponseTransactionStatus": "Completed",
  "ThirdPartyConversationID": "asv02e5958774f7ba228d83d0d689761"
}

mpesa.mozambique

Mozambique MPESA SDK Implementation.

class mpesa.mozambique.API(public_key: str, api_key: str, env: str = 'sandbox')[source]

Bases: object

Mozambique Market API.

Parameters:
  • public_key (str.) – Public key from developers portal.

  • api_key (str.) – API key from developers portal.

  • env (str, optional.) – Environment either "sandbox" or "production", defaults "sandbox".

Attributes.

sandbox_host

The sandbox api host "api.sandbox.vm.co.mz".

live_host

The live/openapi api host "api.vm.co.mz".

Methods.

b2b(Amount: str, PrimaryPartyCode: str, ReceiverPartyCode: str, ThirdPartyReference: str, TransactionReference: str, **kwargs)[source]

B2B Single Stage.

Parameters:
  • Amount (str.) – Amount.

  • ReceiverPartyCode (str.) – Receiver Party Code.

  • PrimaryPartyCode (str.) – Primary Party Code.

  • ThirdPartyReference (str.) – Third Party Reference.

  • TransactionReference (str.) – Transaction Reference.

Returns:

A dictionary object from the B2B API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyReference": "asv02e5958774f7ba228d83d0d689761"
}
b2c(Amount: str, CustomerMSISDN: str, ServiceProviderCode: str, TransactionReference: str, ThirdPartyReference: str, **kwargs)[source]

B2C Single Stage.

Parameters:
  • Amount (str.) – Amount.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyReference (str.) – Third Party Reference.

  • TransactionReference (str.) – Transaction Reference.

Returns:

A dictionary object from the C2B API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyReference": "asv02e5958774f7ba228d83d0d689761"
}
property bearer_token

Return Bearer Token.

c2b(Amount: str, CustomerMSISDN: str, ServiceProviderCode: str, TransactionReference: str, ThirdPartyReference: str, **kwargs)[source]

C2B Single Stage.

Parameters:
  • Amount (str.) – Amount.

  • CustomerMSISDN (str.) – Customer MSISDN.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyReference (str.) – Third Party Reference.

  • TransactionReference (str.) – Transaction Reference.

Returns:

A dictionary object from the C2B API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ThirdPartyReference": "asv02e5958774f7ba228d83d0d689761"
}
reverse(ReversalAmount: str, TransactionID: str, ServiceProviderCode: str, SecurityCredential: str, InitiatorIdentifier: str, ThirdPartyReference: str, **kwargs)[source]

Reversal API.

The Reversal API is used to reverse a successful transaction. Using the Transaction ID of a previously successful transaction, the OpenAPI will withdraw the funds from the recipient party’s mobile money wallet and revert the funds to the mobile money wallet of the initiating party of the original transaction.

Parameters:
  • ReversalAmount (str.) – Reversal Amount.

  • ServiceProviderCode (str.) – Service Provider Code.

  • SecurityCredential (str.) – Security Credentials.

  • InitiatorIdentifier (str.) – Initiator Identifier.

  • ThirdPartyReference (str.) – Third Party Reference.

  • TransactionID (str.) – Transaction ID.

Returns:

A dictionary object from the Reversal API.

Return type:

dict.

Example:

{
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "TransactionID": "49XCD123F6",
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ThirdPartyReference": "asv02e5958774f7ba228d83d0d689761"
}
transaction_status(QueryReference: str, ServiceProviderCode: str, ThirdPartyReference: str, **kwargs)[source]

Query Transaction Status.

The Query Transaction Status API call is used to query the status of the transaction that has been initiated.

Parameters:
  • QueryReference (str.) – Query Reference.

  • ServiceProviderCode (str.) – Service Provider Code.

  • ThirdPartyReference (str.) – Third Party Reference.

Returns:

A dictionary object from the QueryTransactionStatus API.

Return type:

dict.

Example:

{
  "ConversationID": "d3502e5958774f7ba228d83d0d689761",
  "ResponseCode": "INS-0",
  "ResponseDesc": "Request processed successfully",
  "ResponseTransactionStatus": "Completed",
  "ThirdPartyReference": "asv02e5958774f7ba228d83d0d689761"
}

mpesa.drc

Democratic Republic of Congo MPESA SDK Implementation.

Note

This API needs to be called from a Server/Computer whose Public IP Address has been WhiteListed by the Vodacom MPESA Team from the DRC.

Warning

Only WhiteListed IPs are able to access the Remote MPESA APIs.

Note

So Ensure your server IP is White Listed before Using this API.

class mpesa.drc.API(Username, Password, env: str = 'sandbox')[source]

Bases: object

DRC API.

Parameters:
  • Username – Username provided by Mpesa Team.

  • Password – Password provided by Mpesa Team.

  • env (str, optional.) – Environment either "sandbox" or "production", defaults "sandbox".

Attributes.

sandbox_host

The sandbox host "https://uatipg.m-pesa.vodacom.cd".

live_host

The live host "https://ipg.m-pesa.vodacom.cd".

login_path

The login path ":8091/insight/SOAPIn"

c2b_path

The c2b path ":8091/insight/SOAPIn"

b2c_path

The b2c path ":8094/iPG/B2C"

authenticate()[source]

Return Authentication Token.

authentication_token()[source]

Return Authentication Token.

b2c(Amount: str, CallBackChannel: str, CallBackDestination: str, CommandID: str, Currency: str, CustomerMSISDN, Language: str, ServiceProviderName: str, Shortcode: str, ThirdPartyReference: str, TransactionDateTime: str)[source]

B2C.

Parameters:
  • ThirdPartyReference (str.) – ThirdPartyReference.

  • TransactionDateTime (str.) – TransactionDateTime.

  • Token (str.) – Token.

  • Shortcode (str.) – Shortcode.

  • CustomerMSISDN (str.) – CustomerMSISDN.

  • ServiceProviderName (str.) – ServiceProviderName.

  • Language (str.) – Language.

  • CallBackChannel (str.) – CallBackChannel.

  • CallBackDestination (str.) – CallBackDestination.

  • Currency (str.) – Currency.

  • CommandID (str.) – CommandID.

  • Amount (str.) – Amount.

c2b(Amount: str, CallBackChannel: str, CallBackDestination: str, CommandId: str, Currency: str, CustomerMSISDN: str, Date: str, Initials: str, Language: str, ServiceProviderCode: str, Surname: str, ThirdPartyReference: str)[source]

C2B.

Parameters:
  • ThirdPartyReference (str.) – ThirdPartyReference.

  • Token (str.) – Token.

  • Initials (str.) – Initials.

  • Date (str.) – Date.

  • CustomerMSISDN (str.) – CustomerMSISDN.

  • CommandId (str.) – CommandId.

  • Language (str.) – Language.

  • CallBackDestination (str.) – CallBackDestination.

  • CallBackChannel (str.) – CallBackChannel.

  • Currency (str.) – Currency.

  • Surname (str.) – Surname.

  • Amount (str.) – Amount.

  • ServiceProviderCode (str.) – ServiceProviderCode.

classmethod parseB2C(xml_response: bytes)[source]

Parse B2C Callback XML Payload and return json.

classmethod parseC2B(xml_response: bytes)[source]

Parse C2B Callback XML Payload and return json.

w2b(Amount: str, BankShortCode: str, Currency: str, CustomerAccountNumber: str, CustomerMSISDN: str, ThirdPartyID: str, TransactionDateTime: str, TransactionID: str, TransactionType: str)[source]

Wallet To Bank.

Todo

To be Implemented In the Future once the API is documented.

mpesa.drc.data_items_to_map(data)[source]

Convert Data Items to map.

mpesa.drc.generate_b2c(context: dict) str[source]

Return generated template string using context.

mpesa.drc.generate_c2b(context: dict) str[source]

Return generated template string using context.

mpesa.drc.generate_login(context: dict) str[source]

Return generated template string using context.

mpesa.drc.prepare_callback(content: bytes) dict[source]

Prepare callback as dict.

mpesa.drc.prepare_content(content: bytes) dict[source]

Prepare Content for consumption.

mpesa.egypt

Egypt MPESA SDK Implementation.

Todo

To be Implemented when the Public API is made available.

mpesa.lesotho

Lesotho MPESA SDK Implementation.

Todo

To be Implemented when the Public API is made available.

mpesa.portalsdk

Portalsdk subpackage.

Note

This module provides an abstraction over the API mechanisms of three submodules. Namely:

It Provides the following classes which are used internally in the implementation of the respective API classes.

class mpesa.portalsdk.APIContext(api_key='', public_key='', ssl=False, method_type=APIMethodType.GET, address='', port=80, path='', headers={}, parameters={})[source]

Bases: dict

API Context Class.

Parameters:
  • api_key (str.) – API Key.

  • public_key (str.) – Public Key.

  • ssl (bool.) – Whether to use ssl, defaults False.

  • method_type – HTTP Method Type, defaults APIMethodType.GET.

  • address (str.) – Address, defaults "".

  • port (int.) – Port, defaults 80.

  • path (str.) – URL path, defaults "".

  • headers (dict.) – Headers, defaults {}.

  • parameters (dict.) – Parameters, defaults {}.

add_header(header, value)[source]

Update Headers dict with header,value.

add_parameter(key, value)[source]

Update Parameters dict with key,value.

property address: str

Return self address.

property api_key: str

Return self api_key.

get_headers()[source]

Return self headers.

get_parameters()[source]

Return self parameters.

get_url()[source]

Return formed url from context data.

property method_type: APIMethodType

Return self method_type.

property path: str

Return self path.

property port: int

Return self port.

property public_key: str

Return self public_key.

property ssl: bool

Return self ssl.

class mpesa.portalsdk.APIMethodType(value)[source]

Bases: Enum

API Method Type Class.

DELETE: int = 4
GET: int = 0
POST: int = 1
PUT: int = 3
class mpesa.portalsdk.APIRequest(context=None)[source]

Bases: object

API Request Class.

Parameters:

context (mpesa.portalsdk.APIContext.) – context under which to create the API Request.

create_bearer_token()[source]

Return encrypted context api_key using the context public_key.

create_default_headers()[source]

Add some default headers to self.context.

execute()[source]

Execute API Request using self.context.

Raises:

requests.exceptions.ConnectionError

Raises:

TypeError

Returns:

response object of mpesa.portalsdk.APIResponse.

Return type:

mpesa.portalsdk.APIResponse.

class mpesa.portalsdk.APIResponse(status_code, headers, body)[source]

Bases: dict

API Response Class.

Parameters:
  • status_code (str) – String representing HTTP Status Code.

  • headers (dict) – Dict object of key,value headers.

  • body (dict) – Dict object of key,value pairs.

property body: dict

Return HTTP Body.

property headers: dict

Return HTTP Headers.

property status_code: int

Return HTTP Status Code.