Using the Stripe CLI with with Docker Compose
One of the projects that I’m working on at the moment uses Stripe which means that we need to handle web hooks in order to ascertain what’s happened as that’s how Stripe communicates back to us.
For production and staging, it’s easy enough to register a url on Stripe’s dashboard, but when developing, it’s a little more complicated as our computers are generally isolated from receiving incoming web requests from the public internet, along with a changing IP address if we work remotely.
The easiest way to handle this is to use Stripe’s CLI which is excellent. The instructions show you how to run it locally and you can then use `stripe listen` to receive web hooks locally.
Receiving webhooks using the Stripe CLI docker container
I’m not a fan of locally installing project tools as that makes it harder to keep the tooling consistent between team members and onboarding is that much harder too, so I turned to Docker as Stripe provides a CLI Docker image.
We use Compose, so I updated our compose.yaml file:
stripe-cli:
image: stripe/stripe-cli:latest
env_file:
- .env
- .env.local
command: |
listen --api-key $$STRIPE_API_KEY
--device-name $$STRIPE_DEVICE_NAME
--skip-verify
--forward-to https://store.example.com/stripe
This is a pretty standard Compose configuration. The important thing is the options to the listen command.
- --api-key $$STRIPE_API_KEY: Your API key is in the Stripe Dashboard and needs to be in .env.local as it’s not something that belongs in git
- --device-name $$STRIPE_DEVICE_NAME: Invent an device name for each installation. I use STRIPE_DEVICE_NAME=${USER}_dev in our .env file
- --skip-verify: While we are using https for our development endpoints, it’s self-signed, so we skip verification
- --forward-to https://store.example.com/stripe: The endpoint to forward webhooks to
The Stripe CLI does all the communication work with Stripe, and webhooks are now received by our development app.
Running the Docker CLI from the command line
As the CLI binary in the container already has our API key, we want to use use it in development at our local command line. We can do this using docker compose run --rm stripe-cli {arguments here}.
I created bin/stripe to make it easier:
#!/usr/bin/env bash
# Run the Docker Stripe CLI using the container as that already has our API key
docker compose run --rm stripe-cli "$@"
Now, I can can use bin/stripe {arguments here}
All in all, I’ve found this an easy way to receive Stripe webhooks while developing and enjoy the benefit that isolation in containers brings.