Rave Francophone charge KeyError: 'flwRef'

Hi flutterwave, I’m getting this error:

return {“error”: False, “status”: responseJson[“status”],“validationRequired”: True, “txRef”: txRef, “flwRef”: responseJson[“data”][“flwRef”], “chargeResponseMessage”: responseJson[“data”][“chargeResponseMessage”]}
~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^
KeyError: ‘flwRef’

when charging the payment is taking place successfully but the view still generate that error so there is no return.

this my code bellow:


def process_payment(request, *args, **kwargs):
    res = {}
    if request.method == 'POST':
        body = request.body.decode('utf-8')  # Decode the byte string into a Unicode string
        data = urllib.parse.parse_qs(body)  # Parse the form data into a dictionary
        # Access the form data using the parameter names as keys
        csrf_token = data.get('csrfmiddlewaretoken', [''])[0]
        promo_code = data.get('promo_code', [''])[0]
        payment_method = data.get('payment_method', [''])[0]
        country = data.get('country', [''])[0]
        card_number = data.get('card_number', [''])[0]
        cvv = data.get('cvv', [''])[0]
        expired_month = data.get('expired_month', [''])[0]
        expired_year = data.get('expired_year', [''])[0]
        mobile_phone = data.get('mobile_phone', [''])[0]
        ip = get_client_ip(request)
        firstname = request.user.first_name
        lastname = request.user.last_name
        currency = 'XAF'
        order = Order.objects.get(customer=request.user.customer, complete=False)
        email = request.user.email
        if payment_method.upper() == "MOBILE":
            print('payment in processing mode just wait a bit.')
            payment = Payment.objects.create(
                order=order,
                mobile_phone=mobile_phone,
                country=country,
                total_transaction=order.get_cart_total_price,
                currency=currency,
                payment_method=payment_method,
                ip_address=ip
            )
            payload = {
                "currency": currency,
                "country": country,
                "expirymonth": expired_month,
                "expiryyear": expired_year,
                "amount": order.get_cart_total_price,
                "email": email,
                "phonenumber": mobile_phone,
                "IP": ip,
                'lastname': lastname,
                "firstname": firstname,
                "txRef": payment.transaction_id,
                "redirect_url": "http://localhost:8000/receivepayment",
            }
    
            try:
                res = rave.Francophone.charge(payload) # this is where the error is taking place
                if "flwRef" in res and "txRef" in res:
                    flwRef = res["flwRef"]
                    txRef = res["txRef"]
                    print(f"flwRef: {flwRef}, txRef: {txRef}")
                else:
                    print("Error: 'flwRef' or 'txRef' not found in responseJson")
    
                res = rave.Francophone.verify(res["txRef"])
                print(res)
    
            except RaveExceptions.TransactionChargeError as e:
                print(e.err)
                print(e.err["flwRef"])
    
            except RaveExceptions.TransactionVerificationError as e:
                print(e.err["errMsg"])
                print(e.err["txRef"])

    return JsonResponse({'detail': res}, safe=False)

Thank in advanced for helping.

Hi @Donald_Programmeur :wave:

I noticed that you are attempting to charge a customer using the Francophone mobilemoney charge method by calling “rave.Francophone.charge(payload)” in your code snippet. However, the request payload you have provided is for a Direct card charge.

To successfully charge your customers in “XAF” via the Direct card charge method, you need to call the “rave.Card.charge(payload)” method instead.

If your intention is to charge your customers via the Francophone Mobilemoney method, the developer documentation provides the appropriate payload for that method. You can access it here.

THANKS @Adekunle In fact this my completed code I didn’t cut well:

import json
from django.shortcuts import render, redirect
import requests

import urllib.parse
from rave_python import Rave, RaveExceptions, Misc
from django.conf import settings
from django.http import HttpResponse, JsonResponse
from .models import *

from product.utils import get_client_ip

# Instantiate rave
RAVE_PUBLIC_KEY = settings.RAVE_PUBLIC_KEY
RAVE_SECRET_KEY = settings.RAVE_SECRET_KEY
rave = Rave(RAVE_PUBLIC_KEY, RAVE_SECRET_KEY, production=True, usingEnv=True)


def process_payment(request, *args, **kwargs):
    if request.method == 'POST':
        body = request.body.decode('utf-8')  # Decode the byte string into a Unicode string
        data = urllib.parse.parse_qs(body)  # Parse the form data into a dictionary
        # Access the form data using the parameter names as keys
        csrf_token = data.get('csrfmiddlewaretoken', [''])[0]
        promo_code = data.get('promo_code', [''])[0]
        payment_method = data.get('payment_method', [''])[0]
        country = data.get('country', [''])[0]
        card_number = data.get('card_number', [''])[0]
        cvv = data.get('cvv', [''])[0]
        expired_month = data.get('expired_month', [''])[0]
        expired_year = data.get('expired_year', [''])[0]
        mobile_phone = data.get('mobile_phone', [''])[0]
        ip = get_client_ip(request)
        firstname = request.user.first_name
        lastname = request.user.last_name
        currency = 'XAF'
        order = Order.objects.get(customer=request.user.customer, complete=False)
        email = request.user.email
        if payment_method.upper() == 'CARD':
            try:
                payment = Payment.objects.create(
                    order=order,
                    card_number=card_number,
                    cvv=cvv,
                    expired_date=f"{expired_month}/{expired_year}",
                    country=country,
                    total_transaction=order.get_cart_total_price,
                    currency=currency,
                    payment_method=payment_method,
                    ip_address=ip
                )
                payload = {
                    "cardno": card_number,
                    "cvv": cvv,
                    "currency": currency,
                    "country": country,
                    "expirymonth": expired_month,
                    "expiryyear": expired_year,
                    "amount": order.get_cart_total_price,
                    "email": email,
                    "phonenumber": '691435485',
                    "IP": ip,
                    'lastname': lastname,
                    "firstname": firstname,
                    "txRef": payment.transaction_id,
                    "flwRef": payment.transaction_id,
                }

                res = rave.Card.charge(payload)

                if res["validationRequired"]:
                    rave.Card.validate(res["flwRef"], "")

                if "flwRef" in res["data"] and "chargeResponseMessage" in res["data"]:
                    flwRef = res["data"]["flwRef"]
                    chargeResponseMessage = res["data"]["chargeResponseMessage"]
                    print(f"flwRef: {flwRef}, chargeResponseMessage: {chargeResponseMessage}")
                else:
                    print("Error: 'flwRef' or 'chargeResponseMessage' not found in responseJson")

                res = rave.Card.verify(res["txRef"])
                print(res)
                print(res["transactionComplete"])

            except RaveExceptions.CardChargeError as e:
                print(e.err["errMsg"])
                print(e.err["flwRef"])

            except RaveExceptions.TransactionValidationError as e:
                print(e.err)
                print(e.err["flwRef"])

            except RaveExceptions.TransactionVerificationError as e:
                print(e.err["errMsg"])
                print(e.err["txRef"])

            except Exception as e:
                print(e)

        else:
            # mobile payload
            print('payment in processing mode just wait a bit.')
            payment = Payment.objects.create(
                order=order,
                mobile_phone=mobile_phone,
                country=country,
                total_transaction=order.get_cart_total_price,
                currency=currency,
                payment_method=payment_method,
                ip_address=ip
            )
            payload = {
                "currency": currency,
                "country": country,
                "amount": order.get_cart_total_price,
                "email": email,
                "phonenumber": mobile_phone,
                "IP": ip,
                'lastname': lastname,
                "firstname": firstname,
                "txRef": payment.transaction_id,
                "redirect_url": "http://localhost:8000/receivepayment",
            }

            try:
                res = rave.Francophone.charge(payload)
                print(res)
                res = rave.Francophone.verify(res["txRef"])
                print(res)

            except RaveExceptions.TransactionChargeError as e:
                print(e.err)
                print(e.err["flwRef"])

            except RaveExceptions.TransactionVerificationError as e:
                print(e.err["errMsg"])
                print(e.err["txRef"])

    return JsonResponse({'detail': 'response'}, safe=False)

and I was using rave python I’m going to try this one you gave me flutterwave

thanks