Stripe

For implementing a payment mechanism, we’ll be using the third party service Stripe. This is the simplest approach: a product with a price, Stripe’s hosted Checkout page, and a webhook so Stripe can tell the application about payments.

Create Account#

First, head over to https://dashboard.stripe.com/register, and register for an account with Stripe.

Everything here uses Stripe’s test mode (or a “sandbox”), where no real money moves. Make sure you’re in test mode before going further.

Create Product#

Under Product catalogue, add a new Product. There are many options to experiment with, such as recurring or one-off pricing. In this case, we’ll keep it simple, with a one-off price of £5.

From the product’s page, copy the price ID, for example price_1Msm7kLNikjwd8AtKSTrjwm4. (It’s the price, not the product, that Checkout needs.)

Promotion codes#

To offer a discount, create a Coupon, for example 50% off, and then a customer-facing Promotion code for it, such as HALFPRICE. Customers type the promotion code on Stripe’s checkout page, so the application doesn’t need to know about it at all.

API keys#

Under Developers, API keys, copy your secret key. In test mode it starts sk_test_. Keep it secret: it can do anything with your Stripe account. (The publishable key is only needed for Stripe’s JavaScript, which this guide doesn’t use.)

Webhooks#

After a payment, Stripe sends the customer back to your site. But they might close the browser first, or lose their connection, so Stripe also sends your application a message directly, called a webhook, which is the reliable way to know a payment succeeded.

Stripe can’t reach localhost, so in development use the Stripe CLI to forward webhooks to your application. After installing it and running stripe login:

stripe listen --forward-to localhost:8000/stripe/webhook

It prints a webhook signing secret, starting whsec_, which you’ll need in the next section. For production, add an endpoint under Developers, Webhooks, pointing at https://www.your-domain.com/stripe/webhook, for the events checkout.session.completed and checkout.session.async_payment_succeeded. It has its own signing secret.

note

Earlier versions of this guide also created a Payment Link in the Stripe dashboard. It isn’t needed: the application creates a Checkout session for each purchase instead.