【发布时间】:2021-01-25 03:28:56
【问题描述】:
我正在尝试使用 Python 在 Google Cloud Functions 上设置 Stripe Webhooks。但是,我遇到了从函数获取请求正文的问题。请看看我的。代码如下。
基本上我怎样才能得到request.body?这是否以某种方式在 Cloud Functions 中提供?
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 对象将不包含完整的有效负载如果其内容无法解析。见this。 request.body 是一个 nodejs 构造,在 python/Flask 中不可用。
-
答案取决于您如何 POST 或 PUT 数据和 mimetype。这个答案可能会有所帮助:stackoverflow.com/a/16664376/8016720
-
你如何调用你的函数?你可以试试
request.get_data()吗?
标签: python google-cloud-platform google-cloud-functions stripe-payments