@vbusatta/adonis-stripe
Version:
Provider for AdonisJS 6. Simplifies Stripe integration with webhooks and services.
81 lines (80 loc) • 2.73 kB
JavaScript
/**
* Stripe Service for AdonisJS 6.
*
* This module provides a service for interacting with the Stripe API and handling
* incoming webhook events. The service is designed to be used as a singleton and
* can be registered with the AdonisJS IoC container.
*
* @see https://stripe.com/docs/api
* @see https://stripe.com/docs/webhooks
*/
import { Stripe as StripeSDK } from 'stripe';
export default class StripeService {
constructor(logger, config) {
this.
this.
apiVersion: config.apiVersion || this.
});
this.
}
/**
* Provides direct access to the Stripe SDK instance.
*/
get api() {
return this.
}
/**
* Processes an incoming webhook request by verifying the signature and handling the event.
*/
async processWebhook(rawBody, signature) {
const event = this.verifyWebhookSignature(rawBody, signature);
await this.handleEvent(event);
}
/**
* Verifies the signature of a Stripe webhook request and extracts the event.
*/
verifyWebhookSignature(rawBody, signature) {
if (!this.
this.
throw new Error('Webhook secret not configured');
}
try {
this.
return this.
}
catch (error) {
this.
throw new Error('Invalid webhook signature');
}
}
/**
* Processes a Stripe event by invoking the registered handler.
*/
async handleEvent(event) {
this.
const handler = this.
if (handler) {
try {
await handler(event);
}
catch (error) {
this.
}
}
else {
this.
}
}
/**
* Registers a handler for a specific Stripe event type.
*/
onEvent(eventType, handler) {
this.
this.
}
}