首页 > 解决方案 > 在 Google Cloud Function Python 中获取请求正文

问题描述

我正在尝试在 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)

标签: pythongoogle-cloud-platformgoogle-cloud-functionsstripe-payments

解决方案


request对象是 的一个实例flask.Request

根据您要对请求正文执行的操作,您可以调用request.argsrequest.formrequest.filesrequest.valuesrequest.json,或者request.data在请求正文尚未被解析的情况下调用。


推荐阅读