#Adi-webhook-respnose

1 messages ยท Page 1 of 1 (latest)

lean girder
#

Hi ๐Ÿ‘‹ it's going to be really hard to get any insight into what's going on if there is not visibility to the logs on the server running that code.

golden cloud
#

console.log(payload) log is visible but after that nothing is logged

lean girder
#

Hm, I'm not seeing that log statement in the snippet provided.

golden cloud
#

just below payload I have logged it

lean girder
#

To take a step back, if you're seeing 500s returned when we send you a webhook event, then something in the event handling code is crashing/erroring.

golden cloud
#

after this line:
event = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
I dont see any logs

lean girder
#

Then you'll probably want to add more logging statements to get a better idea of what is happening.

golden cloud
#

sorry mistake from my side
i saw this

error StripeSignatureVerificationError: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
lean girder
#

Ah, so that error is thrown whenever the checksum calculated for the event verification process doesn't match the expected value. Typical causes are the webhook signing secret being unset/incorrect, or the body has been manipulated from the original raw request body.

golden cloud
#

not sure what is wrong but I am usign correct wsh secret and also added bodyParser
router.post('/stripe-webhook', bodyParser.raw({ type: 'application/json' }), (request, response) => {

#

I already have added this in server.js

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
lean girder
#

Are you using Stripe CLI to forward events to your event handler? Or are these being sent directly to your endpoint via webhooks?

golden cloud
#

I am forwarding it

#

see payload log

payload {
  id: 'evt_1KYAzHSHwqe5CPMIvgeieDCM',
  object: 'event',
  api_version: '2020-08-27',
  created: 1646061489,
  data: {
    object: {
      id: 'sub_1KYAzESHwqe5CPMIufPAJUWN',
      object: 'subscription',
      application_fee_percent: null,
      automatic_tax: [Object],
      billing_cycle_anchor: 1646666288,
      billing_thresholds: null,
      cancel_at: null,
      cancel_at_period_end: false,
      canceled_at: null,
      collection_method: 'charge_automatically',
      created: 1646061488,
      current_period_end: 1646666288,
      current_period_start: 1646061488,
      customer: 'cus_LEeHNxVse3n5te',
      days_until_due: null,
      default_payment_method: 'pm_1KYAzBSHwqe5CPMIseH92S0q',
      default_source: null,
      default_tax_rates: [],
      discount: null,
      ended_at: null,
      items: [Object],
      latest_invoice: 'in_1KYAzESHwqe5CPMI5MT0ttQl',
      livemode: false,
      metadata: {},
      next_pending_invoice_item_invoice: null,
      pause_collection: null,
      payment_settings: [Object],
      pending_invoice_item_interval: null,
      pending_setup_intent: null,
      pending_update: null,
      plan: [Object],
      quantity: 1,
      schedule: null,
      start_date: 1646061488,
      status: 'trialing',
      transfer_data: null,
      trial_end: 1646666288,
      trial_start: 1646061488
    }
  },
  livemode: false,
  pending_webhooks: 2,
  request: { id: null, idempotency_key: null },
  type: 'customer.subscription.created'
}
#

code:

router.post('/stripe-webhook', express.raw({ type: 'application/json' }), (request, response) => {
    const payload = request.body;
    const sig = request.headers['stripe-signature'];
    console.log("payload", payload)

    const endpointSecret = ''

    let event;

    try {
        event = stripe.webhooks.constructEvent(payload, sig, endpointSecret);
        console.log("event", event)
    } catch (err) {
        console.error("error", err)
        return response.status(400).send(`Webhook Error: ${err.message}`);
    }

    if (event.type === 'checkout.session.completed') {
        console.log("hello")
    }

    switch (event.type) {
        case 'checkout.session.completed': {
            const session = event.data.object;
            // Save an order in your database, marked as 'awaiting payment'
            console.log("session", session)
            createOrder(session);

            // Check if the order is paid (for example, from a card payment)
            //
            // A delayed notification payment will have an `unpaid` status, as
            // you're still waiting for funds to be transferred from the customer's
            // account.
            if (session.payment_status === 'paid') {
                fulfillOrder(session);
            }

            break;
        }

        case 'checkout.session.async_payment_succeeded': {
            const session = event.data.object;

            // Fulfill the purchase...
            fulfillOrder(session);

            break;
        }

        case 'checkout.session.async_payment_failed': {
            const session = event.data.object;

            // Send an email to the customer asking them to retry their order
            emailCustomerAboutFailedPayment(session);

            break;
        }
    }

    response.status(200);
});
lean girder
#

If you're forwarding it then you need to make sure that you're using the webhook signing secret that is generated by the CLI.

golden cloud
#

yes also using that

#

Your webhook signing secret is whsec_XXXXXXXXXXXXXX

hybrid pelican
#

Have you confirm that the correct signing secret is being passed into constructEvent?

#

The most common issues here are either the wrong signing secret, or not using the raw request body

#

Commonly, the request body is mutated earlier in request handling

#

ie, in Node+Express cases, there is often a general body parser applied to all incoming requests

golden cloud
#

but from express v4+ I think body parser is not required right?

#

currently I am doing like this:

router.post('/stripe-webhook', express.raw({ type: 'application/json' }), (request, response) => {
    const payload = request.body;
    const sig = request.headers['stripe-signature'];
    console.log("payload", payload)

also tried this

router.post('/stripe-webhook', bodyParser.raw({ type: 'application/json' }), (request, response) => {
    const payload = request.body;
    const sig = request.headers['stripe-signature'];
    console.log("payload", payload)
#

and in main server.js file I have only these middlewares:

app.disable('x-powered-by');
app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
app.use(helmet());
```before all the routes
hybrid pelican
#

Right, these lines are going to be mutating the body:

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
#

You need to exclude your webhook endpoint from this

#

or temporarily disable them to test

golden cloud
#

yes it worked after disabling them

#

Thanks a lot for helping ๐Ÿ™‚ ๐Ÿ™

hybrid pelican
#

NP!

#

To fix this more permanently, you should have that middleware exclude your webhook endpoint, or otherwise preserve the raw body

golden cloud