#Jacques-rawBody-webhook

1 messages · Page 1 of 1 (latest)

marsh gust
#

Hello 👋
Not sure I fully understand the question
Can you provide an example?

surreal dust
#

I would like to give in parameter to my module verifyWebhook(req.rawBody, signature);, only when I log req.rawBody I have an undefined

marsh gust
#

Ah okay
When you log req, what do you see?

surreal dust
#

we see "body": {} with data inside

marsh gust
#

do you have a middleware or anything that parses the request before it hits your method?

surreal dust
#

when stripe hits our api, it hits a route we have defined

surreal dust
#

do you have an idea for this probleme @marsh gust ?

marsh gust
#

hmm still thinking

surreal dust
#

okay !

marsh gust
#

does your server use bodyParser?

turbid epoch
#

👋 stepping in here.

#

The body that hits your end point is the raw body

#

The important thing is that you don't manipulate it before you construct the event

#

There won't be any rawBody property in the request

surreal dust
turbid epoch
surreal dust
#

no not yet I'm looking at it thank you!

surreal dust
#

I tried the method that is in the doc but I always get the same error :/

turbid epoch
#

What is the error?

surreal dust
turbid epoch
#

Are you forwarding events from the CLI?

surreal dust
#

that is?

#

for require i use this

surreal dust
turbid epoch
#

Gotcha

#

Can you share your full code? What is your router doing?

#

Like does it affect the body at all?

#

If you don't pass the body untouched then the verification will fail

surreal dust
#
    async (req, res, next) => {
        // const signature = req.headers['stripe-signature'];
        // const transaction = await databaseAdapter.sequelize.transaction();
        try {
            let event = req.body;
            if (process.env.STRIPE_WEBHOOK) {
                // Get the signature sent by Stripe
                const signature = req.headers['stripe-signature'];
                try {
                    event = stripeTest.webhooks.constructEvent(
                        req.body,
                        signature,
                        process.env.STRIPE_WEBHOOK
                    );
                } catch (err) {
                    console.log(`⚠️  Webhook signature verification failed.`, err.message);
                    return res.sendStatus(400);
                }
            }
            // Handle the event
            switch (event.type) {
                case 'payment_intent.succeeded':
                    const paymentIntent = event.data.object;
                    console.log(`PaymentIntent for ${paymentIntent.amount} was successful!`);
                    // Then define and call a method to handle the successful payment intent.
                    // handlePaymentIntentSucceeded(paymentIntent);
                    break;
                case 'payment_method.attached':
                    const paymentMethod = event.data.object;
                    // Then define and call a method to handle the successful attachment of a PaymentMethod.
                    // handlePaymentMethodAttached(paymentMethod);
                    break;
                default:
                    // Unexpected event type
                    console.log(`Unhandled event type ${event.type}.`);
            }
 } catch (error) {
            log.error(`[POST /webhooks/stripe] : ${error.message}`);
            // await transaction.rollback();
            next(error);
        }
    });
#

I used what was in the doc

turbid epoch
#

How do you initialize your router

surreal dust
#
const router = Router();```
turbid epoch
#

Ah okay so you are using Express

#

That helps

#

Are you setting router.use(express.json()) as well?

surreal dust
#

no there is no configuration with router.use(express.json())

turbid epoch
#

Can you add a log right at the start of your endpoint function and log out req.body?

#

So add it right before your commented out signature

#

Oh wait

#

You have both the signatures commented out above?

#

Oh no never mind

#

That is separate line

#

Ignore that

surreal dust
#

so I add a log?

#
      "id": "req_UZt17uCmje6BnS",
      "idempotency_key": "fa77ef0a-feb8-466f-b15c-10261e564878"
    }```
#

at the end of the log I have this

silent condor
#

@surreal dust I'm hopping in since bismark has to head out soon

#

Is that the full log you're getting from printing out req.body?

surreal dust
#
    data: {
      "object": {
        "id": "ch_3L0nq8FxsE4pn4oa16yfFQoA",
        "object": "charge",
        "amount": 9990,
        "amount_captured": 9990,
        "amount_refunded": 0,
        "application": null,
        "application_fee": null,
        "application_fee_amount": null,
        "balance_transaction": "txn_3L0nq8FxsE4pn4oa1WrKbi0O",
        "billing_details": {
          "address": {
            "city": null,
            "country": null,
            "line1": null,
            "line2": null,
            "postal_code": "75000",
            "state": null
          },
          "email": null,
          "name": null,
          "phone": null
        },
        "calculated_statement_descriptor": "NOSTRUMCARE",
        "captured": true,
        "created": 1652884024,
        "currency": "eur",
        "customer": "cus_Hk2oGCZyR0Uhie",
        "description": "Subscription creation",
        "destination": null,
        "dispute": null,
        "disputed": false,
        "failure_balance_transaction": null,
        "failure_code": null,
        "failure_message": null,
        "fraud_details": {},
        "invoice": "in_1L0nq7FxsE4pn4oah50J1SbL",
        "livemode": false,
        "metadata": {},
        "on_behalf_of": null,
        "order": null,
        "outcome": {
          "network_status": "approved_by_network",
          "reason": null,
          "risk_level": "normal",
          "risk_score": 39,
          "seller_message": "Payment complete.",
          "type": "authorized"
#
       },
        "paid": true,
        "payment_intent": "pi_3L0nq8FxsE4pn4oa1olw4n5l",
        "payment_method": "pm_1HQCvrFxsE4pn4oa7KAlm0Kt",
        "payment_method_details": {
          "card": {
            "brand": "visa",
            "checks": {
              "address_line1_check": null,
              "address_postal_code_check": "pass",
              "cvc_check": null
            },
            "country": "US",
            "exp_month": 8,
            "exp_year": 2022,
            "fingerprint": "CwNpZ8hXaPZ8OQD4",
            "funding": "credit",
            "installments": null,
            "last4": "1111",
            "mandate": null,
            "network": "visa",
            "three_d_secure": null,
            "wallet": null
          },
          "type": "card"
        },
        "receipt_email": "davidzhiqiang.cai@gmail.com",
        "receipt_number": null,
        "receipt_url": "https://pay.stripe.com/receipts/acct_1H9nQsFxsE4pn4oa/ch_3L0nq8FxsE4pn4oa16yfFQoA/rcpt_LiEIYrrd0TmNkPYmoBC8Ay1Bpn3oS0U",
        "refunded": false,
        "refunds": {
          "object": "list",
          "data": [],
          "has_more": false,
          "total_count": 0,
          "url": "/v1/charges/ch_3L0nq8FxsE4pn4oa16yfFQoA/refunds"
        },
        "review": null,
        "shipping": null,
        "source": null,
        "source_transfer": null,
        "statement_descriptor": null,
        "statement_descriptor_suffix": null,
        "status": "succeeded",
        "transfer_data": null,
        "transfer_group": null
      }
    }
    --
    request: {
      "id": "req_SE0TSv3g4kjZAr",
      "idempotency_key": "613d377e-bcf4-43cc-8b20-d4287cbfa96d"
    }```
silent condor
#

👍 got it

#

so backing up here for a minute, you mentioned that you were using a webhook endpoint that you had created in the dashboard, right? You're not testing with the stripe cli?

surreal dust
#

no I haven't tested with the stripe cli yet but I'll try tomorrow! I'll let you know

silent condor
#

It's not a requirement to test with the CLI if you don't need it - I mainly asked because that's a really easy way to get this error (using the wrong webhook endpoint secret).

#

Since you're not using the CLI, can you confirm that the signature you're using in your code matches what you have in the dashboard?

surreal dust
#

I will tell you tomorrow because the person I work with who has access to stripe is not available

silent condor
#

Gotcha 👍

simple kestrelBOT
#

This thread has been archived. If you need help with anything else please ask in #dev-help or contact Stripe Support: https://support.stripe.com/contact

unique isle
#

@surreal dust i've reopened the thread, how can I help?

surreal dust
#

Thank you, I'll tell you right after I call.

#

I come back to you so we had a hook problem and @silent condor told us to check the secret endpoint webhook, after verification our secret endpoint webhook is the right one.

unique isle
#

what's the framework you're using?

#

e.g. are you using NextJS?

surreal dust
#

We are using the Nodejs framework and we have another api that manages to retrieve the rawBody of the stripe hook correctly, however on our current api we can not retrieve :/
We have the other api in version 12 and the current one in version 18, does it change anything?

unique isle
surreal dust
#

okay

surreal dust
#

we tried on our api version 12 and we have the same error as the one on version 18

unique isle
#

are you using the sample when you say you're getting the ^ error?

surreal dust
unique isle
surreal dust
#

it was a mistake we just returned a success response but signature verification failed

unique isle
#

alright, so because you've multiple webhook endpoints set up. To be absolutely certain, can you log the webhook endpoint secret in your console during runtime

console.log(endpointSecret);
event = stripe.webhooks.constructEvent(
surreal dust
#

already done it matches

unique isle
surreal dust
#

yes i followed the readme

surreal dust
unique isle
#

but there wouldn't be a rawBody parameter like my colleague mentioned previously. Are you saying if you log request.body in the sample code you're running now, there's nothing?

surreal dust
#

request.body gave us the logs above

#

if there’s no rawBody from the hook, how do we verify the signature?

#

const webhook = await stripe.verifyWebhook(req.rawBody, signature);

#

if replaced req.rawBody by req.body, but the signature still fail with the right secret…

twin magnet
#

hi I'm taking over for @unique isle

surreal dust
#

hi

twin magnet
#

every req has a rawBody and using that is necessary for the signature to be verified

surreal dust
#

that is what i said but i have not as you can see in the log below

twin magnet
#

you're not using express.raw({type: 'application/json'}) before your handler which means that the rawBody would be null

#

your code should look like router.post('/stripe', express.raw({type: 'application/json'}), async(request, response) => {

surreal dust
#

Yes we tried but it doesn't work

twin magnet
#

and test it out outside of your current code base

surreal dust
#

it was a mistake on our side. Thank you for your patience and help!

#

we forgot to allow the rawBody