Django: byte indices must be integers or slices, not str error

I am trying to get some data from a payload using a webhook, in the response that i sent along side i added the meta data that should return with the payload and this is how i did it (code below), if you take a close look at the keys, there i one called meta, now i am trying to get some of the data that is in the meta from my webhook view like this

views.py webhook

@csrf_exempt
@require_http_methods(['POST', 'GET'])
def webhook(request):
    payload = request.body
    order_id = payload['meta']['order_id']
    print(order_id)
    return HttpResponse("testing...")

Sending the reponse to the payment gateway

@csrf_exempt
def process_payment(request, name, email, amount, order_id):
    auth_token = "FLWSECK_TEST-9efb9ee17d8afe40c6c890294a1163de-X"
    hed = {'Authorization': 'Bearer ' + auth_token}
    data = {
            "tx_ref":''+str(math.floor(1000000 + random.random()*9000000)),
            "amount":amount,
            "currency":"USD",
            "order_id":order_id,
            "redirect_url":f"http://localhost:3000/service-detail/booking/confirmation/{order_id}",
            "payment_options":"card",
            "meta":{
                "order_id":order_id,
                "consumer_id":23,
                "consumer_mac":"92a3-912ba-1192a"
            },
            "customer":{
                "email":email,
                "name":name,
                "order_id":order_id
            },
            "customizations":{
                "title":"ForecastFaceoff",
                "description":"Leading Political Betting Platform",
                "logo":"https://i.im.ge/2022/08/03m/FELzix.stridearn-high-quality-logo-circle.jpg"
                }
            }
    url = ' https://api.flutterwave.com/v3/payments'
    response = requests.post(url, json=data, headers=hed)
    response=response.json()
    link=response['data']['link']
    return redirect(link)

payload

{
  "event": "charge.completed",
  "data": {
    "id": 4136234873,
    "tx_ref": "6473247093",
    "flw_ref": "FLW-MOCK-b33e86ab2342316fec664110e8eb842a3c2f956",
    "device_fingerprint": "df38c8854324598c54e16feacc65348a5e446",
    "amount": 152,
    "currency": "USD",
    "charged_amount": 152,
    "app_fee": 5.78,
    "merchant_fee": 0,
    "processor_response": "Approved. Successful",
    "auth_model": "VBVSECUREertrCODE",
    "ip": "52.209.154.143",
    "narration": "CARD Transaction ",
    "status": "successful",
    "payment_type": "card",
    "created_at": "2023-02-06T11:19:45.000Z",
    "account_id": 685622,
    "customer": {
      "id": 1970338,
      "name": "destiny ",
      "phone_number": null,
      "email": "******@gmail.com",
      "created_at": "2023-02-06T11:19:45.000Z"
    },
    "card": {
      "first_6digits": "653188",
      "last_4digits": "2340",
      "issuer": "MASTERCARD  CREDIT",
      "country": "NG",
      "type": "MASTERCARD",
      "expiry": "49/32"
    }
  },
  "event.type": "CARD_TRANSACTION"
}

The metadata is not even showing in the payload, must it show up there in the payload before i can grab the data that is sent with it?

request.body is byte not a dict, so you need to load the string as JSON.

payload = json.loads(request.body)

The meta data is not in the payload dictionary. At first try to extract the data key from the payload like this:

@csrf_exempt
@require_http_methods(['POST', 'GET'])
def webhook(request):
    payload = json.loads(request.body.decode("utf-8"))
    data = payload.get("data")
    if data:
        order_id = data.get("meta", {}).get("order_id")
        print(order_id)
    return HttpResponse("just testing")

Edit:

The error message as you described above in comment JSONDecodeError: Expecting value: line 1 column 1 (char 0) indicates that json.loads() is expecting a JSON string as input.

It may be possible that request body is empty. You can check that by printing the request.body before in the view before calling json.loads().

Back to Top