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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With