stripe-samples / stripe-node-cloudflare-worker-template

Use stripe-node in a Cloudflare Worker.
MIT License
74 stars 15 forks source link

Example not working with bun (locally) + cloudflare workers #16

Closed emilMircea closed 3 weeks ago

emilMircea commented 4 weeks ago

Bug report

Describe the bug

The code example does not work when trying to implement with hono and cloudflare workers. Simulating a checkout session with the stripe cli returns an error:

[wrangler:inf] POST /api/stripe/signature-success 400 Bad Request

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. in index.ts instantiate stripe for all routes and make a stripe success route
app.use("*", async (context, next) => {
  // Load the Stripe API key from context.
  const { STRIPE_API_KEY: stripeKey } = env(context);

  // Instantiate the Stripe client object
  const stripe = new Stripe(stripeKey, {
    appInfo: {
      // For sample support and debugging, not required for production:
      name: "stripe-samples/stripe-node-cloudflare-worker-template",
      version: "0.0.1",
      url: "https://github.com/stripe-samples",
    },
    maxNetworkRetries: 3,
    timeout: 30 * 1000,
  });

  // Set the Stripe client to the Variable context object
  context.set("stripe", stripe);

  await next();
});

// The route for the stripe webhook
app.route("/api/stripe/signature-success", stripe_success);
  1. in stripe/success.ts
app.post("/", async (c) => {

  // Load the Stripe API key from context.
  const { STRIPE_WEBHOOK_SECRET } = env(c);
  const rawBody = await c.req.text();
  const signature = c.req.raw.headers.get("stripe-signature");
  /**
   * Load the Stripe client from the context
   */
  const stripe = c.get("stripe");
  const eventBody = JSON.parse(rawBody);

  // verify stripe signature

  try {
    if (!signature) {
      return c.text("no signature found!", 400);
    }
    const body = await c.req.text();
    const event = await stripe.webhooks.constructEventAsync(
      body,
      signature,
      STRIPE_WEBHOOK_SECRET
    );
    switch (event.type) {
      case "checkout.session.completed": {
        console.log(event.data.object);
        break;
      }
      default:
        break;
    }
    return c.text("", 200);
  } catch (err) {
    const errorMessage = `⚠️  Webhook signature verification failed. ${
      err instanceof Error ? err.message : "Internal server error"
    }`;
    console.log(errorMessage);
    return c.text(errorMessage, 400);
  }
})

Expected behavior

The webhook request verification should verify and return a 200 response when coming from stripe.

Screenshots

Screenshot 2024-06-20 at 20 51 45

System information

prathmesh-stripe commented 3 weeks ago

Thanks for reporting this. We shipped a fix for this in the v16.0.0 release.