Django MPESA integration with C2B Till Number Payment and STK Push

1.4k views Asked by At

I would like to be able to integrate MPESA API C2B Till Number Payment capabilities with STK push into a Django Web app I am working on such that the user of the platform gets an STK Push notification to pay to the till number and the transaction is stored in the database through a model.

I have seen some frameworks people have developed online but most seem to cater for paybill and not till. any help with frameworks that can help me do this will be appreciated.

I am finding the official documentation bulky and kind of difficult to work with from django.

1

There are 1 answers

2
Kiarie Henry On

There is no huge difference between Paybill number and Till number. According to Safaricom documentation, for C2B Safaricom C2B API The command ID for paybill shortcode is CustomerPayBillOnline and for Buy Good and services is CustomerBuyGoodsOnline

With that said you can do something like this in Django for STK push:

def lipa_na_mpesa_online(request):
    access_token = MpesaAccessToken.validated_mpesa_access_token
    api_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
    headers = {"Authorization": "Bearer %s" % access_token}
    request = {
        "BusinessShortCode": LipanaMpesaPpassword.Business_short_code,
        "Password": LipanaMpesaPpassword.decode_password,
        "Timestamp": LipanaMpesaPpassword.lipa_time,
        "TransactionType": "CustomerBuyGoodsOnline",
        "Amount": 1,
        "PartyA": 254708374149,  # replace with your phone number to get stk push
        "PartyB": LipanaMpesaPpassword.Business_short_code,
        "PhoneNumber": 254708374149,  # replace with your phone number to get stk push
        "CallBackURL": "https://sandbox.safaricom.co.ke/mpesa/",
        "AccountReference": "Henry",
        "TransactionDesc": "Testing stk push"
     }

     response = requests.post(api_url, json=request, headers=headers)
     return HttpResponse('success')