Webhook Error: Unable to extract timestamp and signatures from header - Netlify Functions and Stripe

2.3k Views Asked by At

I am trying to console log the Stripe customerID once the checkout.session.completed event is complete. but I am getting this 400 status code error "Unable to extract timestamp and signatures from header". I can't seem to figure out a solution to get the Stripe customer ID to console log.

Any help or pointers are appreciated. Here is my code:

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

exports.handler = async ({ body, headers }) => {
  try {
    const stripeEvent = stripe.webhooks.constructEvent(
      body,
      headers['stripe-signature'],
      process.env.STRIPE_WEBHOOK_SECRET
    );

    if (stripeEvent.type === 'checkout.session.completed') {
      const eventObject = stripeEvent.data.object;
      const customerID = eventObject.customer;
      console.log(customerID);
      console.log(headers);
    }
    return {
      statusCode: 200,
      body: JSON.stringify(customerID),
    };
  } catch (err) {
    console.log(`Stripe webhook failed with ${err}`);
    return {
      statusCode: 400,
      body: `Webhook Error: ${err.message}`,
    };
  }
};

When I console log the headers as suggested from a comment in get this in the terminal: console.log(headers)

I can now see the customer ID (cus_JOqbW95ulF3zx0) in the terminal, but what do I need to log it as customerID? When the terminal is saying customerID is not defined.

1

There are 1 best solutions below

0
On

I was able to figure it out. My return after the IF statement was the reason for the 400 status code error. the customerID shows up in the console and I changed the return in the body stats code to a string "success".

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

exports.handler = async ({ body, headers }) => {
  try {
    const stripeEvent = stripe.webhooks.constructEvent(
      body,
      headers['stripe-signature'],
      process.env.STRIPE_WEBHOOK_SECRET
    );

    if (stripeEvent.type === 'checkout.session.completed') {
      const eventObject = stripeEvent.data.object;
      const customerID = eventObject.customer;
      console.log(customerID);
    }
    return {
      statusCode: 200,
      body: 'success',
    };
  } catch (err) {
    console.log(`Stripe webhook failed with ${err}`);
    return {
      statusCode: 400,
      body: `Webhook Error: ${err.message}`,
    };
  }
};