#yen6305

1 messages · Page 1 of 1 (latest)

oblique prairieBOT
lapis sage
#

My code:

import Stripe from 'stripe';
// import { buffer } from "node:stream/consumers";
import { json } from 'micro';


// const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;

export default async function handler(req, res) {
    // let event = req.body; 
  
    // const rawBody = await buffer(req);
    let event = req.body;


    if(webhookSecret) {
        // Get signature send by Stripe
        // const signature = req.headers.get('stripe-signature');

        const signature = req.headers['stripe-signature'];
        try {
            event = stripe.webhooks.constructEvent(
                req.body,
                signature,
                webhookSecret
            );
        } catch (err) {
            console.log(`Webhook signature verification failed.`, err.message);
        }
    }

    // Handle the event 
    switch (event.type) {
        case 'charge.succeed':
            const charge = event.data.object;
            console.log(`Charge succeeded for ${charge.amount}`);
        break;


        // Add more cases to handle other event types as needed
        default:
        // Unexpected event type
        console.log(`Unhandled event type ${event.type}.`);

    }

    // Return a 200 response to acknowledge receipt of the event
    res.send();
}

stuck lion
#

So the two causes of this error are:

  1. The webhook secret being unset or set incorrectly
  2. Your framework changing the raw request body before it gets to your call to the constructEvent method
#

So to knock out #1, can you double check that your webhookSecret is being properly set to the specific secret for the endpoint that you are sending these event to?

lapis sage
#

When logging the webhook secret I get to see this: whsec_rC0tLa.....

#

So I believe that's correct, because that's the secret I've stored in my .env file

stuck lion
#

Sounds like it is properly set. So it sounds like your framework may be changing the request body before you get it in your handler function. This is often useful but in this specific context even changing the whitespace in the response body will throw off our signature calculations