Issue
I'm integrating Stripe Checkout with my django website. I have 2 products and everytime a PaymentIntent is successful, I want to fetch the Price related (the product that was bought).
I have 2 checkouts, one for each product, and a webhook to listen.
views.py - Create a purchase session (exist twice for product 1 & 2)
@csrf_exempt
def create_checkout_session_product1(request):
if request.method == 'GET':
domain_url = 'example.com'
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + 'paiement_ok/',
cancel_url=domain_url + 'paiement_ko/',
payment_method_types=['card'],
line_items=[
{
"price" : "price_1...", <----- What I want to fetch
"quantity": 1,
},
],
mode='payment',
customer_email=request.user.get_username(),
)
return JsonResponse({'sessionId': checkout_session['id']})
views.py - Webhook to trigger a process after a purchase
@csrf_exempt
def webhook(request):
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
#then I'd want to do something like :
line_items = stripe.checkout.Session.list_line_items(session.id)
price = line_items.data.price.id
if price == product1:
activate_process_product1(session.customer_email)
elif price == product2:
activate_process_product2(session.customer_email)
# Passed signature verification
return HttpResponse(status=200)
So the webhook works since I get the money.
But I don't get how to fetch the product once the purchase is complete ?
Solution
If you have a Payment Intent that was created from a Checkout Session, you need to go back and retrieve the associated Checkout Session to get price/product information.
- Get the ID of the Payment Intent.
- Make a request to list Checkout Sessions [0] while setting
payment_intent
and havingdata.line_items
expanded [1]. The call in python should look like this:sessions = stripe.checkout.Session.list(payment_intent='pi_xxx', expand=['data.line_items'])
- If the call was successful and returned a non-empty list of Checkout Sessions, take the first one and check
line_items
for information on the price and product.
[0] https://stripe.com/docs/api/checkout/sessions/list#list_checkout_sessions-payment_intent
[1] https://stripe.com/docs/expand#lists
Answered By - karbi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.