Я пытаюсь закодировать систему подписки с полосой. Мой следующий код в основном скопирован из документов полосы, но он всегда показывает мне эту ошибку:
Webhook signature verification failed. Webhook payload must b
e provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
Signature verification is impossible without access to the original signed material.
Learn more about webhook signing and explore webhook integration
examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing
Это мой код, написанный на javascript:
app.post(
'/webhook',
express.raw({ type: 'application/json' }),
(request, response) => {
let event = request.body;
const endpointSecret = 'whsec_.....';
if (endpointSecret) {
const signature = request.headers['stripe-signature'];
try {
event = stripe.webhooks.constructEvent(
request.body,
signature,
endpointSecret
);
} catch (err) {
console.info(`⚠️ Webhook signature verification failed.`, err.message);
return response.sendStatus(400);
}
}
let subscription;
let status;
switch (event.type) {
case 'customer.subscription.created':
subscription = event.data.object;
status = subscription.status;
console.info(`Subscription status is ${status}.`);
break;
default:
console.info(`Unhandled event type ${event.type}.`);
}
response.send();
}
);
Кто-нибудь знает, что я делаю неправильно? Я буквально час ищу в Интернете и ничего не могу найти. Заранее спасибо!



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Похоже, что что-то в вашем приложении анализирует входящий запрос в формате, отличном от того, который ожидает функция (например, JSON). У вас есть промежуточное программное обеспечение или синтаксический анализатор, настроенный в вашем приложении глобально? Если это так, вы, вероятно, захотите отключить его или просто добавить исключение, когда оно не затрагивает тело входящего запроса, которое отправляется на /webhook маршрут.
Это потому что app.use(express.json()); код. Попробуйте переместить маршрут вебхука до app.use(express.json());.
// webhook route
app.post(
'/webhook',
express.raw({ type: 'application/json' }),
(request, response) => {
let event = request.body;
const endpointSecret = 'whsec_.....';
if (endpointSecret) {
const signature = request.headers['stripe-signature'];
try {
event = stripe.webhooks.constructEvent(
request.body,
signature,
endpointSecret
);
} catch (err) {
console.info(`⚠️ Webhook signature verification failed.`, err.message);
return response.sendStatus(400);
}
}
let subscription;
let status;
switch (event.type) {
case 'customer.subscription.created':
subscription = event.data.object;
status = subscription.status;
console.info(`Subscription status is ${status}.`);
break;
default:
console.info(`Unhandled event type ${event.type}.`);
}
response.send();
}
);
app.use(express.json());
Hi i had the same issue when i was trying to implement the web-hook in my react application and i found this solution:
in your server.js file use this code :
app.use(
bodyParser.json({
verify: function(req, res, buf) {
req.rawBody = buf;
}
})
);
and you must use it before the `app.use(bodyParser.json());`
and the in your stripe-file
use this line of code:
event = stripe.webhooks.constructEvent(request.rawBody, sig, endpointSecret);
instead of this line:
event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
У меня точно такие же модули и код, как в этом примере: https://stripe.com/docs/billing/quickstart#provision-access-webhooks