Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Request Body in Google Cloud Function Python

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)
like image 829
Anters Bear Avatar asked Sep 18 '25 02:09

Anters Bear


1 Answers

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.

like image 55
Dustin Ingram Avatar answered Sep 19 '25 17:09

Dustin Ingram