Python Daraja


Python Wrapper for handling payment requests through the Daraja MPESA API




pip install python-daraja

Initial Setup

  • Set the following constants first before proceeding

from python_daraja import payment

payment.ACCOUNT_TYPE = "PAYBILL"  # Set to TILL to use BuyGoods instead of Pay Bill
  • The first function to call is one which would trigger an automatic STK Push on your customer’s phone. There is no
    simpler way of knowing whether the customer has successfully paid or not (failures such as inputting the wrong PIN or
    just cancelling the request altogether). You are therefore advised to set up a simple server with an endpoint that
    will accept POST requests from Daraja API with the details of the transaction.
  • For the server, it must be secure (https instead of http), it must not be localhost nor$PORT.
  • You can use services like ngrok to tunnel localhost to live secure server.
  • Your server’s endpoint should also accept a POST request hence you may need to disable constraints such as CSRF
    (outside the scope of this project).
  • If at all you must have CSRF Protection in your server, then you need to allow requests originating from the following
    IP addresses (whitelisting):

  • You can now proceed by triggering the payment process; you should expect a Python Dict object with the results of the
    process. This will only tell you whether it was successful and not whether the customer has actually paid.

from python_daraja import payment

details = payment.trigger_stk_push(phone_number=2547123456, amount=1, callback_url='https://your-domain/callback/',
                                   description='Payment for services rendered',
                                   account_ref='Python Good PHP Bad and Co.')
  • The MPESA Gateway will then send some POST data to your endpoint if the customer pays, otherwise, you will not
    receive any data showing that your customer hasn’t paid a dime.

  • It is advisable to save the details received from the previous method call to a DB of your choice. Some of those
    details are used for other subsequent method calls especially in getting the transaction status of your payment requests.

  • In order to query the details of a payment request made through the automatic STK Push above:-

from python_daraja import payment

details = payment.query_stk_push(checkout_request_id='ws_CO_DMZ_123212312_2342347678234')
  • Getting a 0 as the Response Code or Result Code generally means that the transaction was successful, any other digit
    signifies otherwise.


  • Unfortunately as of the moment of release of this package, Safaricom has internal problems with other types of
    transactions such as C2B. Maintainers of the project will work on implementing more features when the issues are addressed.


View Github