@vbusatta/adonis-stripe
Version:
Provider for AdonisJS 6. Simplifies Stripe integration with webhooks and services.
44 lines (43 loc) • 2.02 kB
JavaScript
/**
* Middleware to validate and handle incoming Stripe webhook events.
*
* This middleware verifies the signature of the webhook request to ensure
* that it comes from Stripe. If the signature is valid, the event is attached
* to the context and processed by the appropriate handler in the `StripeService`.
*
* @see https://stripe.com/docs/webhooks
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { inject } from '@adonisjs/core';
let InitializeStripeWebhookMiddleware = class InitializeStripeWebhookMiddleware {
stripe;
constructor(stripe) {
this.stripe = stripe;
}
async handle(ctx, next) {
const sig = ctx.request.header('stripe-signature');
const rawBody = ctx.request.raw();
if (!sig || !rawBody) {
ctx.logger.warn('Invalid Stripe webhook request');
return ctx.response.status(400).send('Invalid webhook request');
}
const rawBodyBuffer = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, 'utf-8');
try {
await this.stripe.processWebhook(rawBodyBuffer, sig);
}
catch (error) {
ctx.logger.error(`Webhook signature verification failed: ${error.message}`);
return ctx.response.status(400).send('Webhook signature is missing');
}
await next();
}
};
InitializeStripeWebhookMiddleware = __decorate([
inject()
], InitializeStripeWebhookMiddleware);
export default InitializeStripeWebhookMiddleware;