Oliver
Oliver

Reputation: 119

Checking if values are in JSON received via API (Python / Django)

I am trying to check if certain values are within data sent by stripe to a webhook in my Django application. The data received has been received by my application using the DJ Stripe package, which constructed an event object from the json received - the model has a field called 'body' (removed some irrelevant fields) which contains the received json:

Body = {
    "id": "evt_1IX2nQHiJcStEaySS5pgOO4l",
    "object": "event",
    "api_version": "2020-03-02",
    "created": 1616239004,
    "data": {
        "object": {
            "id": "cs_test_a1ZHPGoSfEreDQhdioGxpWgYc1y5lhnwuo5qdeOsBqpio764yk0caFIBwg",
            "object": "checkout.session",
            "amount_subtotal": 1000,
            "amount_total": 1000,
            "currency": "gbp",
            "customer": "cus_1234",
            "customer_details": {
                "email": "[email protected]",
            },
            "customer_email": null,
            "mode": "payment",
            "payment_intent": "pi_1234",
            "payment_method_types": [
                "card"
            ],
            "payment_status": "paid",
            "total_details": {
                "amount_discount": 0,
                "amount_tax": 0
            }
        }
    },
    "type": "checkout.session.completed"
}

I'm trying to see if certain values are in the json data as follows, although I receive errors with this code such as 'Unsupported lookup 'data' for TextField or join on the field not permitted':

Values I am checking:

chargeamount = 1000
chargecustomer = cus_1234
chargetimestamp = str(1616239004)
chargetimestamp = chargetimestamp[:-3] #cut last 3 digits of timestamp as seconds will vary

Code to check if values exist:

checkoutsession = WebhookEventTrigger.objects.get(body__data__object__customer=chargecustomer, body__data__object__amount_total=chargeamount, body__created__icontains=chargetimestamp)
checkoutsessionid = checkoutsession.body['data']['object']['id']

Upvotes: 0

Views: 589

Answers (2)

Nolan H
Nolan H

Reputation: 7419

You can use stripe-python (github) and construct_from to get a real Stripe object you can traverse:

# Using Django
@csrf_exempt
def my_webhook_view(request):
  payload = request.body
  event = None

  try:
    event = stripe.Event.construct_from(
      json.loads(payload), stripe.api_key
    )
  except ValueError as e:
    # Invalid payload
    return HttpResponse(status=400)

  # Handle the event
  # ...

See the example in the docs here (see Python snippet).

Upvotes: 0

Ярига Олег
Ярига Олег

Reputation: 341

Do not try to check or validate values manually. Use Django REST framework serializers instead: https://www.django-rest-framework.org/api-guide/serializers/

If you want to validate nested objects like

{"user": {"name": "some_name", "id": 1, ...}, ...}

then use nested serializers:

class UserSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=200)
    ...

class RequestSerializer(serializers.Serializer):
    user = UserSerializer()
    ...

Upvotes: 1

Related Questions