### Install AdonisJS Stripe Package Source: https://github.com/vittoriobusatta/adonis-stripe/blob/main/README.md Install the Stripe integration package for AdonisJS 6 using the Ace CLI. This is the first step to setting up Stripe in your AdonisJS application. ```bash node ace add @vbusatta/adonis-stripe ``` -------------------------------- ### Configure AdonisJS Stripe Package Source: https://github.com/vittoriobusatta/adonis-stripe/blob/main/README.md Configure the Stripe package for AdonisJS 6 by running the configure command with the Ace CLI. This command generates necessary configuration files. ```bash node ace configure @vbusatta/adonis-stripe ``` -------------------------------- ### AdonisJS Stripe: Create Payment Intents with TypeScript Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Demonstrates how to use the Stripe service to create a payment intent. This requires the Stripe SDK to be initialized via the package. The function takes payment details and returns a Stripe PaymentIntent object or throws an error. ```typescript import stripe from '@vbusatta/adonis-stripe/services/main' export default class PaymentService { async createPaymentIntent() { try { const paymentIntent = await stripe.api.paymentIntents.create({ amount: 2000, currency: 'usd', payment_method_types: ['card'], metadata: { orderId: '12345' } }) return paymentIntent } catch (error) { console.error('Payment intent creation failed:', error) throw error } } async createCustomer(email: string, name: string) { const customer = await stripe.api.customers.create({ email, name, metadata: { source: 'web_app' } }) return customer } async retrieveCharge(chargeId: string) { const charge = await stripe.api.charges.retrieve(chargeId) return charge } } ``` -------------------------------- ### Webhook Controller Implementation Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Implement a minimal webhook controller to receive Stripe events. The `verifyStripeWebhook` middleware handles signature verification and event processing, automatically invoking registered event handlers. ```APIDOC ## Webhook Controller Implementation ### Description Implement a controller to handle incoming Stripe webhooks. The associated middleware (`verifyStripeWebhook`) performs the necessary security checks and event dispatching, allowing this controller to focus on acknowledging receipt. ### Method `POST` ### Endpoint `/webhooks/stripe` (Example, as configured in `start/routes.ts`) ### Parameters N/A (Parameters are handled by middleware and Stripe SDK) ### Request Body N/A (The request body is processed by the middleware) ### Request Example ```typescript // controllers/payments_controller.ts import type { HttpContext } from '@adonisjs/core/http' export default class PaymentsController { async handleWebhook({ response, logger }: HttpContext) { // The verifyStripeWebhook middleware has already validated the signature // and invoked any registered event handlers (via stripe.onEvent). logger.info('Stripe webhook received and processed successfully') return response.ok({ received: true }) } } ``` ### Response #### Success Response (200) - **received** (boolean) - Indicates that the webhook was successfully received and processed by the middleware. #### Response Example ```json { "received": true } ``` ``` -------------------------------- ### Stripe Environment Configuration (.env) Source: https://github.com/vittoriobusatta/adonis-stripe/blob/main/README.md Configure your Stripe API credentials and webhook secret in the .env file for the AdonisJS Stripe integration. An API version can also be specified. ```dotenv STRIPE_API_KEY = '' STRIPE_WEBHOOK_SECRET = '' STRIPE_API_VERSION = '' ``` -------------------------------- ### Create and Manage Stripe Subscriptions (TypeScript) Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Implements methods to create new Stripe subscriptions for a given customer and price ID, and to cancel existing subscriptions either immediately or at the end of the billing period. Includes error handling for subscription creation. ```typescript import stripe from '@vbusatta/adonis-stripe/services/main' export default class SubscriptionService { async createSubscription(customerId: string, priceId: string) { try { const subscription = await stripe.api.subscriptions.create({ customer: customerId, items: [{ price: priceId }], payment_behavior: 'default_incomplete', payment_settings: { save_default_payment_method: 'on_subscription' }, expand: ['latest_invoice.payment_intent'], }) return { subscriptionId: subscription.id, clientSecret: (subscription.latest_invoice as any)?.payment_intent?.client_secret, status: subscription.status } } catch (error) { console.error('Subscription creation failed:', error) throw new Error('Failed to create subscription') } } async cancelSubscription(subscriptionId: string, immediately: boolean = false) { if (immediately) { return await stripe.api.subscriptions.cancel(subscriptionId) } else { return await stripe.api.subscriptions.update(subscriptionId, { cancel_at_period_end: true }) } } } ``` -------------------------------- ### Stripe Service - Direct API Access Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt The Stripe service provides direct access to the Stripe SDK through the `api` property, enabling all Stripe API operations. ```APIDOC ## Stripe Service - Direct API Access ### Description Provides direct access to the Stripe SDK via the `api` property for all Stripe API operations. ### Method Various (e.g., `POST`, `GET`) ### Endpoint N/A (Service-level access) ### Parameters N/A ### Request Example ```typescript import stripe from '@vbusatta/adonis-stripe/services/main' // Example: Create a Payment Intent const paymentIntent = await stripe.api.paymentIntents.create({ amount: 2000, currency: 'usd', payment_method_types: ['card'], metadata: { orderId: '12345' } }); // Example: Create a Customer const customer = await stripe.api.customers.create({ email: 'test@example.com', name: 'John Doe', metadata: { source: 'web_app' } }); // Example: Retrieve a Charge const charge = await stripe.api.charges.retrieve('ch_123'); ``` ### Response #### Success Response (200) - **paymentIntent** (Stripe.PaymentIntent) - The created payment intent object. - **customer** (Stripe.Customer) - The created customer object. - **charge** (Stripe.Charge) - The retrieved charge object. #### Response Example ```json { "id": "pi_...", "amount": 2000, "currency": "usd", // ... other payment intent details } ``` ``` -------------------------------- ### Webhook Middleware Configuration Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Configure the webhook signature validation middleware in `start/kernel.ts` and apply it to your webhook route in `start/routes.ts` to ensure the authenticity of incoming Stripe webhooks. ```APIDOC ## Webhook Middleware Configuration ### Description Configure and apply the `verifyStripeWebhook` middleware to secure your webhook endpoints by validating Stripe's signature. This ensures that incoming webhook requests are genuinely from Stripe. ### Method Middleware registration and route application ### Endpoint - `start/kernel.ts`: For middleware registration. - `start/routes.ts`: For applying middleware to a specific route. ### Parameters N/A ### Request Example ```typescript // start/kernel.ts import router from '@adonisjs/core/services/router' export const middleware = router.named({ verifyStripeWebhook: () => import('@vbusatta/adonis-stripe/middleware'), }) // start/routes.ts import { middleware } from '#start/kernel' import router from '@adonisjs/core/services/router' const PaymentsController = () => import('#controllers/payments_controller') router .post('webhooks/stripe', [PaymentsController, 'handleWebhook']) .use(middleware.verifyStripeWebhook()) ``` ### Response N/A (Middleware is applied to a route) #### Response Example N/A ``` -------------------------------- ### Configure Stripe with Environment Variables (TypeScript) Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Sets up Stripe configuration using environment variables for API keys, webhook secrets, and optional advanced settings like API version, retries, and telemetry. It expects a .env file for these variables. ```typescript // config/stripe.ts import env from '#start/env' import { defineConfig } from '@vbusatta/adonis-stripe' export default defineConfig({ apiKey: env.get('STRIPE_API_KEY'), webhookSecret: env.get('STRIPE_WEBHOOK_SECRET'), apiVersion: env.get('STRIPE_API_VERSION') || '2024-11-20.acacia', maxNetworkRetries: 2, timeout: 80000, // 80 seconds telemetry: true, appInfo: { name: 'My AdonisJS App', version: '1.0.0', url: 'https://myapp.com' } }) // .env // STRIPE_API_KEY=sk_test_51... // STRIPE_WEBHOOK_SECRET=whsec_... // STRIPE_API_VERSION=2024-11-20.acacia ``` -------------------------------- ### Access Stripe SDK via Service Source: https://github.com/vittoriobusatta/adonis-stripe/blob/main/README.md Access the Stripe SDK directly through the 'stripe' service in AdonisJS. This allows for easy creation of payment intents and other Stripe operations. ```typescript // /services/payment_service.ts import stripe from '@vbusatta/adonis-stripe/services/main' export default class PaymentService { async createPaymentIntent() { return await stripe.api.paymentIntents.create({ amount: 1000, currency: 'usd', }) } } ``` -------------------------------- ### Apply Stripe Webhook Middleware to Route Source: https://github.com/vittoriobusatta/adonis-stripe/blob/main/README.md Apply the `verifyStripeWebhook` middleware to your Stripe webhook route in AdonisJS to ensure that only validated requests are processed. ```typescript // /start/routes.ts import { middleware } from '#start/kernel' import router from '@adonisjs/core/services/router' const PaymentsController = () => import('#controllers/payments/payments_controller') router .post('stripe/webhook', [PaymentsController, 'handleWebhook']) .use(middleware.verifyStripeWebhook()) ``` -------------------------------- ### AdonisJS Stripe: Configure Webhook Middleware in TypeScript Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Illustrates how to configure the webhook signature validation middleware in AdonisJS. This involves importing the middleware and applying it to specific routes, ensuring that incoming Stripe webhooks are authenticated. ```typescript // start/kernel.ts import router from '@adonisjs/core/services/router' export const middleware = router.named({ verifyStripeWebhook: () => import('@vbusatta/adonis-stripe/middleware'), }) // start/routes.ts import { middleware } from '#start/kernel' import router from '@adonisjs/core/services/router' const PaymentsController = () => import('#controllers/payments_controller') router .post('webhooks/stripe', [PaymentsController, 'handleWebhook']) .use(middleware.verifyStripeWebhook()) ``` -------------------------------- ### Stripe Webhook Controller Acknowledgment Source: https://github.com/vittoriobusatta/adonis-stripe/blob/main/README.md Implement a simple webhook controller in AdonisJS that acknowledges receipt of Stripe webhook requests. The actual event handling is managed by the 'stripe' service and its registered handlers. ```typescript // /controllers/payments_controller.ts import type { HttpContext } from '@adonisjs/core/http' export default class PaymentsController { async handleWebhook({ response }: HttpContext) { return response.ok({ received: true }) } } ``` -------------------------------- ### Register Stripe Webhook Middleware Source: https://github.com/vittoriobusatta/adonis-stripe/blob/main/README.md Register the `verifyStripeWebhook` named middleware in your AdonisJS kernel to automatically validate incoming Stripe webhook requests. ```typescript // /start/kernel.ts export const middleware = router.named({ verifyStripeWebhook: () => import('@vbusatta/adonis-stripe/middleware'), }) ``` -------------------------------- ### AdonisJS Stripe: Implement Webhook Controller in TypeScript Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Provides a basic implementation of a webhook controller for handling Stripe events in AdonisJS. The middleware performs the signature verification, and the Stripe service automatically invokes registered event handlers. ```typescript import type { HttpContext } from '@adonisjs/core/http' export default class PaymentsController { async handleWebhook({ response, logger }: HttpContext) { // Middleware handles signature verification and event processing // Event handlers registered via stripe.onEvent() are automatically invoked logger.info('Stripe webhook received and processed successfully') return response.ok({ received: true }) } } ``` -------------------------------- ### Event Handler Registration Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Register custom handlers for specific Stripe webhook events using the `onEvent` method. This allows for asynchronous processing of various Stripe events. ```APIDOC ## Event Handler Registration ### Description Register custom handlers for specific Stripe webhook events using the `onEvent` method. This enables the application to react to different Stripe events like payment success, failures, or subscription changes. ### Method `stripe.onEvent(eventName, handlerFunction)` ### Endpoint N/A (Service-level registration) ### Parameters - **eventName** (string) - Required - The name of the Stripe event to listen for (e.g., 'payment_intent.succeeded'). - **handlerFunction** (function) - Required - The asynchronous function to execute when the event occurs. It receives the Stripe `Event` object as an argument. ### Request Example ```typescript import { Stripe } from 'stripe' import stripe from '@vbusatta/adonis-stripe/services/main' // In your service or boot file: stripe.onEvent('payment_intent.succeeded', this.handlePaymentSuccess.bind(this)) stripe.onEvent('payment_intent.payment_failed', this.handlePaymentFailure.bind(this)) // Handler methods: private async handlePaymentSuccess(event: Stripe.Event) { const paymentIntent = event.data.object as Stripe.PaymentIntent; console.log(`Payment ${paymentIntent.id} succeeded.`); // Your custom logic here } private async handlePaymentFailure(event: Stripe.Event) { const paymentIntent = event.data.object as Stripe.PaymentIntent; console.error(`Payment ${paymentIntent.id} failed: ${paymentIntent.last_payment_error?.message}`); // Your custom logic here } ``` ### Response N/A (This method is for event registration, not direct request/response) #### Response Example N/A ``` -------------------------------- ### Process Stripe Refunds (TypeScript) Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Provides functionality to process refunds for Stripe payments, including creating a refund with an optional amount and reason, and listing existing refunds. It validates the payment intent ID and logs errors. ```typescript import stripe from '@vbusatta/adonis-stripe/services/main' export default class RefundService { async createRefund(paymentIntentId: string, amount?: number, reason?: string) { try { const refundParams: any = { payment_intent: paymentIntentId, reason: reason || 'requested_by_customer' } if (amount) { refundParams.amount = amount } const refund = await stripe.api.refunds.create(refundParams) return { refundId: refund.id, amount: refund.amount, status: refund.status, currency: refund.currency } } catch (error) { console.error('Refund creation failed:', error) throw new Error('Failed to process refund') } } async listRefunds(limit: number = 10) { const refunds = await stripe.api.refunds.list({ limit }) return refunds.data } } ``` -------------------------------- ### Handle Stripe Events with Custom Handlers Source: https://github.com/vittoriobusatta/adonis-stripe/blob/main/README.md Register custom handlers for Stripe events using the `onEvent` method in AdonisJS. This allows you to process specific Stripe events like 'charge.succeeded'. ```typescript // /services/payment_service.ts import { Stripe } from 'stripe' import stripe from '@vbusatta/adonis-stripe/services/main' export default class PaymentService { constructor() { stripe.onEvent('charge.succeeded', this.chargeSucceeded.bind(this)) } private async chargeSucceeded(event: Stripe.Event) { const charge = event.data.object as Stripe.Charge console.log(`Charge ${charge.id} was successful`) } } ``` -------------------------------- ### AdonisJS Stripe: Register Event Handlers with TypeScript Source: https://context7.com/vittoriobusatta/adonis-stripe/llms.txt Shows how to register custom handlers for various Stripe webhook events. The `stripe.onEvent` method is used to associate specific event types with handler functions. These handlers receive a Stripe.Event object and can perform actions based on the event data. ```typescript import { Stripe } from 'stripe' import stripe from '@vbusatta/adonis-stripe/services/main' export default class PaymentEventService { constructor() { stripe.onEvent('payment_intent.succeeded', this.handlePaymentSuccess.bind(this)) stripe.onEvent('payment_intent.payment_failed', this.handlePaymentFailure.bind(this)) stripe.onEvent('customer.subscription.created', this.handleSubscriptionCreated.bind(this)) } private async handlePaymentSuccess(event: Stripe.Event) { const paymentIntent = event.data.object as Stripe.PaymentIntent console.log(`Payment ${paymentIntent.id} succeeded for amount ${paymentIntent.amount}`) // Update database, send confirmation email, etc. } private async handlePaymentFailure(event: Stripe.Event) { const paymentIntent = event.data.object as Stripe.PaymentIntent console.error(`Payment ${paymentIntent.id} failed: ${paymentIntent.last_payment_error?.message}`) // Notify customer, retry logic, etc. } private async handleSubscriptionCreated(event: Stripe.Event) { const subscription = event.data.object as Stripe.Subscription console.log(`New subscription ${subscription.id} created for customer ${subscription.customer}`) // Activate subscription features, send welcome email, etc. } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.