MPESA API Reference — tekmpesa 1.0.0 documentation

# MPESA API Reference

## mpesa.kenya

Kenya MPESA SDK Implementation.

class `mpesa.kenya.` `API`(env: str = 'sandbox', app_key: str = None, app_secret: str = None)

  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`()

    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: str = None, security_credential: str = None, command_id: str = None, sender_identifier_type: str = None, receiver_identifier_type: str = None, amount: str = None, party_a: str = None, party_b: str = None, remarks: str = None, account_reference: str = None, queue_timeout_url: str = None, result_url: str = None)

    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: str = None, security_credential: str = None, command_id: str = None, amount: str = None, party_a: str = None, party_b: str = None, remarks: str = None, queue_timeout_url: str = None, result_url: str = None, occassion: str = None)

    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: str = None, security_credential: str = None, command_id: str = None, party_a: str = None, identifier_type: str = None, remarks: str = None, queue_timeout_url: str = None, result_url: str = None)

    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: str = None, response_type: str = None, confirmation_url: str = None, validation_url: str = None)

    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: str = None, command_id: str = None, amount: str = None, msisdn: str = None, bill_ref_number: str = None)

    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: str = None, checkout_request_id: str = None, passcode: str = None)

    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: str = None, passcode: str = None, amount: str = None, callback_url: str = None, reference_code: str = None, phone_number: str = None, description: str = None)

    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: str = None, security_credential: str = None, command_id='TransactionReversal', transaction_id: str = None, amount: str = None, receiver_party: str = None, receiver_identifier_type: str = None, queue_timeout_url: str = None, result_url: str = None, remarks: str = None, occassion: str = None)

    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: str = None, identifier_type: str = None, remarks: str = None, initiator: str = None, passcode: str = None, result_url: str = None, queue_timeout_url: str = None, transaction_id: str = None, occassion: str = None, shortcode: str = None)

    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')

  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)

    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)

    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)

    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)

    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)

    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)

    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`

    Return session_id.

    Returns

      The sessionID to be used in subsequent requests.

    Return type

      str.

  `transaction_status`(QueryReference: str, ServiceProviderCode: str, ThirdPartyConversationID: str, **kwargs)

    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')

  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)

    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)

    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)

    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)

    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)

    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)

    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`

    Return session_id.

    Returns

      The sessionID to be used in subsequent requests.

    Return type

      str.

  `transaction_status`(QueryReference: str, ServiceProviderCode: str, ThirdPartyConversationID: str, **kwargs)

    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')

  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)

    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)

    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)

    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)

    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)

    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')

  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"`

  `authentication_token`()

    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)

    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)

    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.

  `w2b`(Amount: str, BankShortCode: str, Currency: str, CustomerAccountNumber: str, CustomerMSISDN: str, ThirdPartyID: str, TransactionDateTime: str, TransactionID: str, TransactionType: str)

    Wallet To Bank.

    Todo

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

## 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:

- `mpesa.tanzania`

- `mpesa.ghana`

- `mpesa.mozambique`

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

- `mpesa.portalsdk.APIContext`

- `mpesa.portalsdk.APIMethodType`

- `mpesa.portalsdk.APIRequest`

- `mpesa.portalsdk.APIResponse`

class `mpesa.portalsdk.` `APIContext`(api_key='', public_key='', ssl=False, method_type=<APIMethodType.GET: 0>, address='', port=80, path='', headers={}, parameters={})

  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)

    Update Headers dict with header,value.

  `add_parameter`(key, value)

    Update Parameters dict with key,value.

  property `address`

    Return self address.

  property `api_key`

    Return self api_key.

  `get_headers`()

    Return self headers.

  `get_parameters`()

    Return self parameters.

  `get_url`()

    Return formed url from context data.

  property `method_type`

    Return self method_type.

  property `path`

    Return self path.

  property `port`

    Return self port.

  property `public_key`

    Return self public_key.

  property `ssl`

    Return self ssl.

class `mpesa.portalsdk.` `APIMethodType`(value)

  Bases: `enum.Enum`

  API Method Type Class.

  `DELETE`: int = 4
  `GET`: int = 0
  `POST`: int = 1
  `PUT`: int = 3

class `mpesa.portalsdk.` `APIRequest`(context=None)

  Bases: `object`

  API Request Class.

  Parameters

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

  `create_bearer_token`()

    Return encrypted context api_key using the context public_key.

  `create_default_headers`()

    Add some default headers to `self.context`.

  `execute`()

    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)

  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`

    Return HTTP Body.

  property `headers`

    Return HTTP Headers.

  property `status_code`

    Return HTTP Status Code.