I am trying to intergrate mpesa payment api to dynamically pass the store price and the correct response

434 Views Asked by At

I have been trying to intergrate mpesa API and make my payment dynamically I manage to see the correct value in my cart on my phone stk push but on the web browser I get an error local variable 'order' referenced before assignment and the console gives me a success message without me incorrectly putting in my pin, thank you.

Please please help me solve this I am still a newbie in PYTHON.

def mpesaToken(request):
    ckey = 'hOdosm1nU1tXMsT0yPTGjnHDgIUSxx8z'
    csecret = 'mrgGSIdbDOZaVrZl'
    apiurl = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials'

    r = requests.get(apiurl, auth=HTTPBasicAuth(ckey, csecret))
    mptoken = json.loads(r.json)
    valida = mptoken['access_token']
    return HttpResponse(valida)
    

def lipaOnline(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
        cartItems = order.get_cart_items
    else:
        items = []
    accesstoken = MpesaToken.valida
    apiurl = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest"
    headers = {"Authorization":"Bearer %s" % accesstoken}
    request = {
                "BusinessShortCode": Lipa.bscode,
                "Password": Lipa.decode_pass,
                "Timestamp": Lipa.lipatime,
                "TransactionType": "CustomerPayBillOnline",
                "Amount": order.get_cart_total,
                "PartyA": 25471234567,
                "PartyB": Lipa.bscode,
                "PhoneNumber": 25471234567,
                "CallBackURL": "https://sandbox.safaricom.co.ke/mpesa/",
                "AccountReference": "HAC",
                "TransactionDesc": "testeltd"}
    response = requests.post(apiurl, json=request, headers=headers)
    
    return HttpResponse('Success')
    print(request)
1

There are 1 best solutions below

0
On

The problem is you are trying to pick a value from a computed value, it doesn't understand that it's supposed to retrieve that query(order.get_cart_total) before it assigns that value into your other variable Amount so what works for me is that I set the variable first before invoking it and to be sure you can also put it as a global variable. so simply do

global totalcart = order.get_cart_total

first then

"Amount" : totalcart'
...