我正在尝试在Python中的Google Cloud函数上设置Stripe Webhook。但是,我在从函数中获取请求正文时遇到了一个问题。请看一下我下面的代码。
从本质上讲,我如何获得request.body
?这是在云功能中以某种方式提供的吗?
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)
request
对象是flask.Request
的一个实例。
根据您想对请求体执行的操作,在请求体尚未解析的情况下,可以调用request.args
、request.form
、request.files
、request.values
、request.json
或request.data
。