Process Payment
NotesCheckout#
When the Checkout button is pressed, the application asks Stripe to create a Checkout session, and sends the user to Stripe’s payment page:
def create_membership_checkout_api(user: User) -> str:
"""Start a Stripe Checkout for membership. Returns the URL of Stripe's payment page."""
checkout = stripe_client().v1.checkout.sessions.create(params={
"mode": "payment",
"line_items": [{"price": settings.CONF_STRIPE_PRICE, "quantity": 1}],
"customer_email": user.email,
# Who is paying, so the payment can be matched to the user afterwards
"client_reference_id": str(user.id),
# Lets customers enter promotion codes on Stripe's page
"allow_promotion_codes": True,
"success_url": settings.CONF_MAIN_DOMAIN + "/member/success?session_id={CHECKOUT_SESSION_ID}",
"cancel_url": settings.CONF_MAIN_DOMAIN + "/member/cancel",
})
return checkout.url@router.post('/member/purchase')
def member_purchase_view(*, request: Request, session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
if current_user.is_member:
return RedirectResponse(url='/member', status_code=status.HTTP_303_SEE_OTHER)
return RedirectResponse(create_membership_checkout_api(current_user), status_code=status.HTTP_303_SEE_OTHER)The parameters are:
mode: "payment"for a one-off payment ("subscription"would be for recurring prices).line_items: the price to charge, from the settings.customer_emailfills in the user’s email on Stripe’s page.client_reference_idis the user’sid. Stripe keeps it with the payment, and it’s how the payment is matched to the user afterwards.allow_promotion_codesshows a field for promotion codes, such asHALFPRICE, on Stripe’s page. Stripe checks the code and applies the discount.success_urlandcancel_urlare where Stripe sends the user afterwards. Stripe replaces{CHECKOUT_SESSION_ID}with the session’s id.
Fulfilment#
Granting membership happens in one function, used both by the success page and by the webhook:
def fulfil_membership_api(checkout: stripe.checkout.Session, session: Session) -> User | None:
"""Make the buyer a member, if the checkout was paid. Safe to call more than once."""
if checkout.payment_status != "paid" or not checkout.client_reference_id:
return None
user = session.get(User, uuid.UUID(checkout.client_reference_id))
if user and not user.is_member:
user.is_member = True
session.add(user)
session.commit()
return user
def get_checkout_api(checkout_id: str) -> stripe.checkout.Session | None:
try:
return stripe_client().v1.checkout.sessions.retrieve(checkout_id)
except stripe.StripeError:
return NoneIt only makes the user a member if Stripe says the checkout was paid. It’s safe to call twice, which matters because both the success page and the webhook will call it for the same payment.
The success page#
After paying, Stripe sends the user to /member/success?session_id=...:
@router.get('/member/success', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def member_success_view(*, request: Request, session_id: str = "", session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
# Ask Stripe, rather than trusting the URL: was it paid, and by this user?
checkout = get_checkout_api(session_id) if session_id else None
if checkout and checkout.client_reference_id == str(current_user.id) \
and fulfil_membership_api(checkout, session):
return member_page(request, current_user, "Purchase Successful",
"Thank you for purchasing. Your membership is active.")
return member_page(request, current_user, "Purchase Unsuccessful",
"We couldn't confirm this payment. If you were charged, your membership "
"will be activated shortly, or please contact us.")The session_id in the URL can’t be trusted on its own: anyone can type a URL. So the view asks Stripe for the checkout, and checks that it was paid, and that it belongs to the logged-in user.
An earlier version of this guide made the user a member if the checkout had been created in the last five minutes, without checking it had been paid, or by whom. Anyone could have started a checkout, abandoned it, and visited the success URL to become a member for free.
The webhook#
The webhook is the reliable route: Stripe calls it even if the user never comes back to the site.
@router.post('/stripe/webhook', include_in_schema=False)
async def stripe_webhook_api(request: Request, session: Session = Depends(get_session_db)):
"""Stripe calls this when a checkout completes, even if the buyer never returns to the site."""
payload = await request.body()
try:
event = stripe_client().construct_event(payload, request.headers.get("stripe-signature", ""),
settings.CONF_STRIPE_WEBHOOK_SECRET)
except (ValueError, stripe.SignatureVerificationError):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid webhook.")
if event.type in ("checkout.session.completed", "checkout.session.async_payment_succeeded"):
# The handler is async (to read the raw body), so run the database work in the thread pool
await run_in_threadpool(fulfil_membership_api, event.data.object, session)
return {"received": True}Anyone could send a request to /stripe/webhook, so construct_event checks the Stripe-Signature header: a signature of the request body, made with the webhook signing secret that only you and Stripe know. If it doesn’t match, the request is rejected. It needs the body exactly as it arrived, which is why the handler reads request.body() itself, and is async. The database work runs in the thread pool, as FastAPI does for plain def functions.
Cancelling#
If the user cancels on Stripe’s page, they’re sent to /member/cancel:
@router.get('/member/cancel', response_class=HTMLResponse, status_code=status.HTTP_200_OK)
def member_cancel_view(*, request: Request, session: Session = Depends(get_session_db)):
current_user = is_user(request, session)
if current_user is None:
return RedirectResponse(url='/auth/login', status_code=status.HTTP_303_SEE_OTHER)
return member_page(request, current_user, "Purchase Cancelled", "Your purchase was cancelled.")Trying it out#
All being well, the payment flow should work: go to the /member page with a user who isn’t a member, press Checkout, and you’re sent to Stripe’s payment page. In test mode, you can pay with the card number 4242 4242 4242 4242, any future expiry date and any CVC.
After paying, you’re sent back to the success page, and you’re a member. With stripe listen running, you’ll also see the webhook arrive.
You can now restrict other features to members, for example only letting members create blog posts, by adding a check to the blog views:
if not current_user.is_member:
return RedirectResponse(url='/member', status_code=status.HTTP_303_SEE_OTHER)