我通过 post 请求发送订单数据到 stripe 并创建会话,并在 line_items 中设置我的订单数据,问题是我希望此 line_items 数据扩展到 stripe webhook 视图,并通过此数据创建订单和付款历史记录,我首先尝试设置该数据到
metadata={"data": items}
但是我收到错误,因为键的数量有限,这意味着我的数据太大而无法放入元数据,之后我发现我可以将我的数据像这样展开
展开=['line_items']
但是什么也没发生,我没有在我的 webhook 视图中获取此数据,但我在 stripe 网站上获取了此数据
所以这是我的代码,我希望有人帮助我:p
from django.conf import settings
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt
import stripe
from rest_framework.decorators import api_view
from accounts.models import AppUser
stripe.api_key = settings.STRIPE_SECRET_KEY
class StripeCheckoutView(APIView):
def post(self, request):
try:
data = request.data['orderData']['orderItems']
items = []
for i in data.keys():
i = data[i]
desc = ', '.join([i.get('name') for i in i.get('extra').values()]) + i.get('extra_info')
name = ', '.join(
filter(None, [
i.get('name'),
i.get('pizzaDough', ''),
f"{str(i.get('size', ''))} size" if i.get('size') else '',
f"{str(i.get('grams', ''))} grams" if i.get('grams') else '',
])
)
items.append(
{
"price_data": {
"currency": "usd",
"unit_amount": int(i['price']),
"product_data": {
"name": name,
"description": f"+ {desc}" if len(desc) > 0 else " ",
"images": [i['img_modify'],],
},
},
"quantity": i['quantity'],
}
)
checkout_session = stripe.checkout.Session.create(
line_items=items,
mode='payment',
expand=['line_items'],
success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}',
cancel_url=settings.SITE_URL + '/?canceled=true',
automatic_tax={"enabled": True},
#discounts=[{"coupon": "promo_1PnWnuGKlfpQfnx9vj6v7cw9"}],
allow_promotion_codes=True,
shipping_options=[
{
"shipping_rate_data": {
"type": 'fixed_amount',
"fixed_amount": {
"amount": 500,
"currency": 'usd',
},
"display_name": 'Food Shipping',
"delivery_estimate": {
"maximum": {
"unit": 'hour',
"value": 1,
},
},
},
},
],
)
return Response({"url": checkout_session.url})
except:
return Response(
{'error': 'Something went wrong when creating stripe checkout session'},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@csrf_exempt
@api_view(['POST'])
def stripe_webhook_view(request):
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
print(request.POST)
try:
event = stripe.Webhook.construct_event(
payload,
sig_header,
settings.STRIPE_SECRET_WEBHOOK
)
except ValueError as e:
return HttpResponse({"error": 'Error parsing payload', 'payload': payload},status=400)
except stripe.error.SignatureVerificationError as e:
return HttpResponse({"error":'Error verifying webhook signature', 'sign_header': sig_header},status=400)
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
print(session, event['data'])
if event.type == 'payment_intent.succeeded':
payment_intent = event.data.object # contains a stripe.PaymentIntent
print(payment_intent)
elif event.type == 'payment_method.attached':
payment_method = event.data.object # contains a stripe.PaymentMethod
print(payment_method)
# ... handle other event types
else:
print('Unhandled event type {}'.format(event.type))
return HttpResponse(status=200)
line_items
是“可包含的”,意味着它们不包含在对象的基本视图中。 Webhooks 始终发送基本版本。
在处理 webhook 时,您应该向 stripe.checkout.Session.retrieve
发出 API 请求,并且可以在该检索调用中传递 expand=['line_items']
。
这是解释的相同示例 https://docs.stripe.com/expand#with-webhooks 并在https://docs.stripe.com/checkout/fulfillment