I want to get user id in payment_intent.payment_failed event and client_refrence_id isn't in request data in payment_failed event from stripe. I tried metadata={'user_id': user_id} but this too isn't showing in request data. Also tried this subscription_data.metadata = {"metadata": {"bar": "BAR", }}, but it is showing syntax error "SyntaxError: expression cannot contain assignment, perhaps you meant "=="? and even if I do this (==) it says SyntaxError: positional argument follows keyword argument Here is my code:
checkout_session = stripe.checkout.Session.create(
client_reference_id=user_id,
# metadata={'user_id': user_id},
subscription_data.metadata = {"metadata": {"bar": "BAR", }},
success_url="success_url",
cancel_url="cancel_url",
payment_method_types=["card"],
mode="subscription",
line_items=[
{
"price": price_id,
"quantity": 1,
}
],
)
Here's my webhook code
def webhook_received(self):
payload = request.data
endpoint_secret = 'my_secret_key'
sig_header = request.headers.get('stripe-signature')
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
data = event['data']
except:
pass
event_type = event['type']
if event_type == 'checkout.session.completed':
self.handle_checkout_session(data)
elif event_type == 'payment_intent.payment_failed':
self.saving_failed_subscription_data(data)
return "success"
CodePudding user response:
In order to pass the metadata through to the subscription in when creating the checkout session in Python, you need to use nested dictionaries instead of dot notation. So in your case you would revise the creation of the checkout session like so:
checkout_session = stripe.checkout.Session.create(
client_reference_id=user_id,
# metadata={'user_id': user_id},
# subscription_data.metadata = {"metadata": {"bar": "BAR", }}, <-- won't work
# This should work to get data to invoice/subscription
subscription_data = {
"metadata": {"user_id": user_id}
},
# This will get the metadata on to the related payment_intent
payment_intent_data={
"metadata": {"user_id": user_id}
},
success_url="success_url",
cancel_url="cancel_url",
payment_method_types=["card"],
mode="subscription",
line_items=[
{
"price": price_id,
"quantity": 1,
}
],
)
This approach of using dictionaries is required in Python to post data for any of the nested attributes that the Stripe APIs allow you to manipulate.
The Create a Session docs have a pretty long list of configurable parameters that it is worth reviewing, now that you've got the syntax for how to append nested data.
