我将 Stripe Checkout 集成到 Django 应用程序中,并处理 Webhooks 以根据支付事件更新用户信息。但是,在处理
Checkout Session
对象时,我在访问与 payment_method
相关的元数据时遇到了问题。
我对 Stripe Checkout 有以下设置:
StripeCheckoutMonthlyView
和 StripeCheckoutYearlyView
:两者都使用元数据创建 Checkout Session
(例如,user_id
、plan_type
)。stripe_webhook
):处理来自 Stripe 的不同事件类型。在
payment_method.attached
事件中,我需要访问 Checkout Session
中包含的元数据。但是,payment_method
对象不包含元数据,并且不直接引用Checkout Session
。
这是我的 webhook 处理程序的外观:
@csrf_exempt
def stripe_webhook(request):
payload = request.body
event = None
print('Stripe Webhook Received!')
try:
event = stripe.Event.construct_from(
json.loads(payload), stripe.api_key
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
if event.type == 'payment_intent.succeeded':
# Handle payment_intent.succeeded event
pass
elif event.type == 'payment_method.attached':
payment_method = event.data.object
# Issue: Payment method does not include metadata or session_id
pass
elif event.type == 'checkout.session.completed':
session = event.data.object
# Retrieve session metadata here
pass
else:
print('Unhandled event type {}'.format(event.type))
return HttpResponse(status=200)
我需要根据
Checkout Session
中包含的元数据更新用户信息。具体来说:
payment_method.attached
事件中访问元数据。Checkout Session
事件时从 payment_method
检索元数据。我尝试使用
payment_intent_data
:
class StripeCheckoutMonthlyView(APIView):
def post(self, request, *args, **kwargs):
# try:
checkout_session = stripe.checkout.Session.create(
line_items=[
{
'price': settings.STRIPE_PRICE_ID_MONTHLY,
'quantity': 1,
},
],
payment_method_types=['card'],
mode='subscription',
success_url=settings.SITE_URL + '/pagamento/?success=true&session_id={CHECKOUT_SESSION_ID}',
cancel_url=settings.SITE_URL + '/?canceled=true',
metadata={'user_id': request.user.id,
'plan_type': 'monthly'},
payment_intent_data={
'metadata': {
'user_id': request.user.id,
}
}
)
return Response({'url': checkout_session.url,
'id': checkout_session.id,
}, status=status.HTTP_200_OK)
然后在适当的函数中使用它:
def add_info_card(payment_method):
"""
Update the user's card details and payment date based on the payment intent.
Args:
payment_method: The payment intent object from Stripe containing card and charge details.
user: The user object retrieved from the database.
"""
print('Payment Method: ', payment_method)
user = get_object_or_404(User, id=payment_method.metadata.user_id)
last4 = payment_method['card']['last4']
payment_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
brand_card = payment_method['card']['brand']
print('Last 4: ', last4)
print('Payment Date: ', payment_date)
# Update the user with card details and payment date
user.card_last4 = last4
user.brand_card = brand_card
user.payment_date = payment_date
user.save()
print(f"User {user.id} updated with card details and payment date.")
但收到错误:
stripe._error.InvalidRequestError: Request req_td3acLmE4ziQqi: You can not pass `payment_intent_data` in `subscription` mode.
Checkout Session
事件时如何访问 payment_method
元数据?payment_method
链接到 webhook 中的 Checkout Session
元数据的最佳方式是什么?对于具有
subscription
模式的结帐会话,应在 subscription_data.metadata
下设置元数据。
元数据将在以下位置提供:
customer.subscription.*
事件中的订阅对象subscription_details.metadata
invoice.*
活动元数据在付款方式或付款意图对象上不可用。