Struggling to handle dev, staging, demo, and other environments with a single Stripe Test Environment? Here's an easy and flexible solution!
This Cloudflare Worker forwards incoming Stripe webhook events to the appropriate environment based on the returnUrl
included in the event's metadata
property.
-
Create the Cloudflare Worker and upload the
worker.js
contents or use this Button: -
Create a Webhook in your Stripe Dashboard: https://dashboard.stripe.com/test/webhooks. Make sure to replace the original URL's Domain with the Worker Domain. In the end, you should have something like this:
https://smewh.worker.dev/<originalPath>
-
Add the
returnUrl
property in themetadata
of every Stripe request your Server sends. It should be the URL of the originating server (e.g.https://dev.your-server.com
) -
Optional: Cloudflare Access Environment Variables
CF_ACCESS_CLIENT_ID
: Set this environment variable if your forwarded requests require authentication withCF-Access-Client-Id
.CF_ACCESS_CLIENT_SECRET
: Set this environment variable if your forwarded requests require authentication withCF-Access-Client-Secret
.- Note: Both environment variables must be set for the headers to be added to the forwarded request.
Stripe sends a webhook event to your Worker, e.g., https://smewh.worker.dev/stripe/webhook
, then the Worker:
- Parses the body, extracts
metadata.returnUrl
(e.g.,https://dev.your-server.com
). - Appends the original request path to the
returnUrl
, forming thetargetUrl
. - Checks if the request is from an allowed IP address; if not, it denies access.
- Adds
CF-Access-Client-Id
andCF-Access-Client-Secret
headers if both environment variables are set. - Forwards the original request (including headers) to the
targetUrl
(e.g.,https://dev.your-server.com/stripe/webhook
). - Returns the response back to Stripe.
- IP Filtering: The Worker only allows incoming requests from specific IP addresses to prevent unauthorized access.
- Environment Variables: If
CF_ACCESS_CLIENT_ID
andCF_ACCESS_CLIENT_SECRET
are set, they are used to add authentication headers to the forwarded request.
Ensure you have the correct IP addresses and environment variables set to match your security requirements.