#views
@transaction.atomic
def booking_form(request, id):
franchise_id = id
form = BookingForm(franchise_id=franchise_id)
if request.method == 'POST':
form = BookingForm(request.POST, franchise_id=franchise_id)
if 'paynow-btn' in request.POST:
if form.is_valid():
instance = form.save(commit=False)
instance.payment_status = 'due'
instance.booking_status = 'unconfirmed'
instance.franchise_id = franchise_id
#other code
#stripe connect [standard account] direct charges
connected_account_id = create_or_get_connected_account(franchise_id)
success_urlpattern = reverse('booking:booking_successful', kwargs={'id': franchise_id})
success_urlpath = request.build_absolute_uri(success_urlpattern)
# Create a Stripe checkout session
print("Before checkout session creation")
checkout_session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
"price_data": {
"currency": "gbp",
"unit_amount": int(instance.total_amount * 100),
"product_data": {
"name": f'Booking for {instance.full_name}',
},
},
"quantity": 1,
}],
payment_intent_data={
'metadata': {
'booking_id': instance.id,
},
'application_fee_amount': int(instance.total_amount * (franchise.payout_percentage / 100) * 100),
},
mode='payment',
# Create a Stripe checkout session
success_url=success_urlpath,
cancel_url=settings.PAYMENT_CANCEL_URL,
stripe_account=connected_account_id,
)
print("After checkout session creation")
print(checkout_session)
# Check if the checkout session was successfully created
if checkout_session and checkout_session.status == 'completed':
# Save the instance only if the checkout session is completed
instance.save()
return redirect(checkout_session.url)
else:
# Handle the case where the checkout session creation failed
messages.error(request, 'Failed to create the checkout session. Please try again.')
return redirect(reverse('booking:booking_form', kwargs={'id': franchise_id}))
Hi, I'm trying to save the booking object instance after all the processes are completed! It doesn't work and leaves me with Failed to create the checkout session. Please try again.
Printing the session shows me this {"status": "open",}
. I tried doing @transaction.atomic
without the stripe checkout_session.status
check and saving the instance after all the processes, and that just saves the instance as soon as I hit the paynow-btn
and then redirects me to stripe for payment. Is there a way to solve this??
If the purpose is to update your DB when a customer has completed a checkout session, you should set up a webhook endpoint and register it to listen to
checkout.session.completed
events. Refer to this guide for implementation details.