4

I'm trying to setup Stripe Webhooks on Google Cloud Functions in Python. However, I'm running into an issue with getting the request body from the function. Please have a look at my. code below.

Essentially how can I get the request.body? Is this provided in Cloud Functions somehow?

import json
import os
import stripe
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

stripe.api_key = 'XXXX'

# Using Django
@csrf_exempt
def my_webhook_view(request):
  payload = request.body # This doesn't work!
  event = None
  print(payload)

  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
  if event.type == 'payment_intent.succeeded':
    payment_intent = event.data.object # contains a stripe.PaymentIntent
    # Then define and call a method to handle the successful payment intent.
    # handle_payment_intent_succeeded(payment_intent)
    print(payment_intent)
  elif event.type == 'payment_method.attached':
    payment_method = event.data.object # contains a stripe.PaymentMethod
    # Then define and call a method to handle the successful attachment of a PaymentMethod.
    # handle_payment_method_attached(payment_method)
    # ... handle other event types
    print(payment_intent)
  else:
    print('Unhandled event type {}'.format(event.type))

  return HttpResponse(status=200)
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Anters Bear
  • 1,816
  • 1
  • 15
  • 41
  • It looks like the Request object won't contain a full payload *if its contents can NOT be parsed*. See [this](https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request). request.body is a nodejs construct, which is not available in python/Flask. – Doug Stevenson Oct 10 '20 at 05:57
  • The answer depends on how you POST or PUT the data and the mimetype. This answer might help: https://stackoverflow.com/a/16664376/8016720 – John Hanley Oct 10 '20 at 06:36
  • 1
    How do you call your functions? And can you try with `request.get_data()`? – guillaume blaquiere Oct 10 '20 at 12:37

1 Answers1

2

The request object is an instance of flask.Request.

Depending on what you want to do with the request body, you could call request.args, request.form, request.files, request.values, request.json, or request.data in the event that the request body hasn't been parsed.

Dustin Ingram
  • 20,502
  • 7
  • 59
  • 82