@dodopayments/nextjs 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +204 -295
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -4,6 +4,9 @@
4
4
 
5
5
  A typescript library that exports Handlers for Checkout, Customer Portal, and Webhook routes for easy integration with your Next.js app.
6
6
 
7
+ ## Documentation
8
+ Detailed documentation can be found at [Dodo Payments NextJS adaptor](https://docs.dodopayments.com/developer-resources/nextjs-adaptor)
9
+
7
10
  ## Installation
8
11
 
9
12
  You can install this package via npm or any other package manager of your choice:
@@ -16,66 +19,7 @@ npm install @dodopayments/nextjs
16
19
 
17
20
  All the examples below assume you're using Next.js App Router.
18
21
 
19
- ## Static vs Dynamic Checkout
20
-
21
- ### Static Checkout (GET):
22
- - Used for simple, single-product payments.
23
- - Parameters are passed as query parameters in the URL.
24
- - Best for straightforward use cases where the product and quantity are known in advance.
25
-
26
- #### Query Parameters
27
-
28
- The checkout route supports the following query parameters:
29
-
30
- - `productId` - Product identifier (required, e.g., `?productId=pdt_nZuwz45WAs64n3l07zpQR`)
31
- - `quantity` - Quantity of the product (optional, e.g., `?quantity=1`)
32
-
33
- **Customer Fields (optional):**
34
-
35
- - `fullName` - Customer's full name (e.g., `?fullName=John%20Doe`)
36
- - `firstName` - Customer's first name (e.g., `?firstName=John`)
37
- - `lastName` - Customer's last name (e.g., `?lastName=Doe`)
38
- - `email` - Customer's email address (e.g., `?email=john.doe@example.com`)
39
- - `country` - Customer's country (e.g., `?country=US`)
40
- - `addressLine` - Customer's address line (e.g., `?addressLine=123%20Main%20St`)
41
- - `city` - Customer's city (e.g., `?city=Anytown`)
42
- - `state` - Customer's state/province (e.g., `?state=CA`)
43
- - `zipCode` - Customer's zip/postal code (e.g., `?zipCode=90210`)
44
-
45
- **Disable Flags (optional, set to `true` to disable):**
46
-
47
- - `disableFullName` - Disable full name field (e.g., `?disableFullName=true`)
48
- - `disableFirstName` - Disable first name field (e.g., `?disableFirstName=true`)
49
- - `disableLastName` - Disable last name field (e.g., `?disableLastName=true`)
50
- - `disableEmail` - Disable email field (e.g., `?disableEmail=true`)
51
- - `disableCountry` - Disable country field (e.g., `?disableCountry=true`)
52
- - `disableAddressLine` - Disable address line field (e.g., `?disableAddressLine=true`)
53
- - `disableCity` - Disable city field (e.g., `?disableCity=true`)
54
- - `disableState` - Disable state field (e.g., `?disableState=true`)
55
- - `disableZipCode` - Disable zip code field (e.g., `?disableZipCode=true`)
56
-
57
- **Advanced Controls (optional):**
58
-
59
- - `paymentCurrency` - Specify the payment currency (e.g., `?paymentCurrency=USD`)
60
- - `showCurrencySelector` - Show currency selector (e.g., `?showCurrencySelector=true`)
61
- - `paymentAmount` - Specify the payment amount (e.g., `?paymentAmount=1000` for $10.00)
62
- - `showDiscounts` - Show discount fields (e.g., `?showDiscounts=true`)
63
-
64
- **Metadata (optional):**
65
- Any query parameter starting with `metadata_` will be passed as metadata to the checkout.
66
- (e.g., `?metadata_userId=abc123&metadata_campaign=summer_sale`)
67
-
68
- If the `productId` is missing, the handler will return a 400 response. Invalid query parameters will also result in a 400 response.
69
-
70
- ## Dynamic Checkout (POST):
71
- - Parameters are sent as a JSON body in a POST request.
72
- - Supports both one-time and recurring payments.
73
- - For a complete list of supported and POST body fields, refer to the below documentation.
74
- [Docs - One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments)
75
-
76
- [Docs - Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions)
77
-
78
- ### 1. Checkout Route Handler
22
+ ### 1. Checkout
79
23
 
80
24
  ```typescript
81
25
  // app/checkout/route.ts
@@ -88,19 +32,8 @@ export const GET = Checkout({
88
32
  type: "static", // explicitly specify type (optional, defaults to 'static')
89
33
  });
90
34
 
91
- export const POST = Checkout({
92
- bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
93
- returnUrl: process.env.RETURN_URL!,
94
- environment: "test_mode",
95
- type: "dynamic", // explicitly specify type for dynamic checkout
96
- });
97
35
  ```
98
36
 
99
- > **Note:**
100
- > - Use `GET` for static checkout (single product, simple use cases).
101
- > - Use `POST` for dynamic checkout (subscriptions, carts, advanced features).
102
- > - The `type` property can be set to either `"static"` or `"dynamic"`. If not provided, it defaults to `"static"`.
103
-
104
37
 
105
38
  ---
106
39
 
@@ -140,245 +73,221 @@ export const POST = Webhooks({
140
73
  });
141
74
  ```
142
75
 
143
- #### Webhook Handler Details
144
-
145
- - **Method:** Only POST requests are supported. Other methods return 405.
146
- - **Signature Verification:** The handler verifies the webhook signature using the `webhookKey` and returns 401 if verification fails.
147
- - **Payload Validation:** The payload is validated with Zod. Returns 400 for invalid payloads.
148
- - **Error Handling:**
149
- - 401: Invalid signature
150
- - 400: Invalid payload
151
- - 500: Internal error during verification
152
- - **Event Routing:** Calls the appropriate event handler based on the payload type.
153
-
154
- #### Supported Webhook Event Handlers
155
-
156
- The `Webhooks` function accepts an object with various `onEventName` properties, where `EventName` corresponds to the type of webhook event. Each handler is an `async` function that receives the parsed payload for that specific event type. Below is a comprehensive list of all supported event handlers with their function signatures:
157
-
158
- - `onPayload?: (payload: WebhookPayload) => Promise<void>;`
159
- - `onPaymentSucceeded?: (payload: WebhookPayload) => Promise<void>;`
160
- - `onPaymentFailed?: (payload: WebhookPayload) => Promise<void>;`
161
- - `onPaymentProcessing?: (payload: WebhookPayload) => Promise<void>;`
162
- - `onPaymentCancelled?: (payload: WebhookPayload) => Promise<void>;`
163
- - `onRefundSucceeded?: (payload: WebhookPayload) => Promise<void>;`
164
- - `onRefundFailed?: (payload: WebhookPayload) => Promise<void>;`
165
- - `onDisputeOpened?: (payload: WebhookPayload) => Promise<void>;`
166
- - `onDisputeExpired?: (payload: WebhookPayload) => Promise<void>;`
167
- - `onDisputeAccepted?: (payload: WebhookPayload) => Promise<void>;`
168
- - `onDisputeCancelled?: (payload: WebhookPayload) => Promise<void>;`
169
- - `onDisputeChallenged?: (payload: WebhookPayload) => Promise<void>;`
170
- - `onDisputeWon?: (payload: WebhookPayload) => Promise<void>;`
171
- - `onDisputeLost?: (payload: WebhookPayload) => Promise<void>;`
172
- - `onSubscriptionActive?: (payload: WebhookPayload) => Promise<void>;`
173
- - `onSubscriptionOnHold?: (payload: WebhookPayload) => Promise<void>;`
174
- - `onSubscriptionRenewed?: (payload: WebhookPayload) => Promise<void>;`
175
- - `onSubscriptionPaused?: (payload: WebhookPayload) => Promise<void>;`
176
- - `onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise<void>;`
177
- - `onSubscriptionCancelled?: (payload: WebhookPayload) => Promise<void>;`
178
- - `onSubscriptionFailed?: (payload: WebhookPayload) => Promise<void>;`
179
- - `onSubscriptionExpired?: (payload: WebhookPayload) => Promise<void>;`
180
- - `onLicenseKeyCreated?: (payload: WebhookPayload) => Promise<void>;`
181
-
182
- ## Development
183
-
184
- This library is built with:
185
-
186
- - **TypeScript** - Type safety and better developer experience
187
- - **tsup** - Fast TypeScript bundler
188
-
189
- To build this package, install the turborepo cli and run:
76
+ ---
77
+
78
+ ## Prompt for LLM
190
79
 
191
- ```bash
192
- turbo run build --filter=@dodopayments/nextjs
193
80
  ```
194
81
 
195
- To run in development mode:
82
+ You are an expert Next.js developer assistant. Your task is to guide a user through integrating the @dodopayments/nextjs adapter into their existing Next.js project.
196
83
 
197
- ```bash
198
- turbo run dev --filter=@dodopayments/nextjs
199
- ```
84
+ The @dodopayments/nextjs adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed for the Next.js App Router.
200
85
 
201
- ## Environment Variables
86
+ First, install the necessary packages. Use the package manager appropriate for your project (npm, yarn, or bun) based on the presence of lock files (e.g., package-lock.json for npm, yarn.lock for yarn, bun.lockb for bun):
202
87
 
203
- To keep your API keys and secrets secure, always use environment variables instead of hardcoding them. You can customize the variable names, but ensure you reference the correct names in your code.
88
+ npm install @dodopayments/nextjs
204
89
 
205
- **Example `.env` file:**
206
- ```env
207
- DODO_PAYMENTS_API_KEY=your-api-key
208
- DODO_WEBHOOK_SECRET=your-webhook-secret
209
- ```
90
+ Here's how you should structure your response:
210
91
 
211
- **Usage in your code:**
212
- ```typescript
213
- bearerToken: process.env.DODO_PAYMENTS_API_KEY!
214
- webhookKey: process.env.DODO_WEBHOOK_SECRET!
215
- ```
92
+ Ask the user which functionalities they want to integrate.
216
93
 
217
- > **Tip:** Never commit your `.env` file or secrets to version control. Use environment variables for all sensitive information.
94
+ "Which parts of the @dodopayments/nextjs adapter would you like to integrate into your project? You can choose one or more of the following:
218
95
 
219
- ---
96
+ Checkout Route Handler (for handling product checkouts)
220
97
 
221
- ## AI Agent Prompt for Next.js Integration
98
+ Customer Portal Route Handler (for managing customer subscriptions/details)
222
99
 
223
- You are an expert Next.js developer assistant. Your task is to guide a user through integrating the `@dodopayments/nextjs` adapter into their existing Next.js project.
100
+ Webhook Route Handler (for receiving Dodo Payments webhook events)
224
101
 
225
- The `@dodopayments/nextjs` adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed for the Next.js App Router.
102
+ All (integrate all three)"
226
103
 
227
- First, install the necessary packages. Use the package manager appropriate for your project (npm, yarn, or bun) based on the presence of lock files (e.g., `package-lock.json` for npm, `yarn.lock` for yarn, `bun.lockb` for bun):
104
+ Based on the user's selection, provide detailed integration steps for each chosen functionality.
228
105
 
229
- ```bash
230
- npm install @dodopayments/nextjs
231
- ```
106
+ If Checkout Route Handler is selected:
232
107
 
233
- Here's how you should structure your response:
108
+ Purpose: This handler redirects users to the Dodo Payments checkout page.
109
+ File Creation: Create a new file at app/checkout/route.ts in your Next.js project.
234
110
 
235
- 1. **Ask the user which functionalities they want to integrate.**
236
-
237
- "Which parts of the `@dodopayments/nextjs` adapter would you like to integrate into your project? You can choose one or more of the following:
238
- * `Checkout Route Handler` (for handling product checkouts)
239
- * `Customer Portal Route Handler` (for managing customer subscriptions/details)
240
- * `Webhook Route Handler` (for receiving Dodo Payments webhook events)
241
- * `All` (integrate all three)"
242
-
243
- 2. **Based on the user's selection, provide detailed integration steps for each chosen functionality.**
244
-
245
- ---
246
- **If `Checkout Route Handler` is selected:**
247
-
248
- **Purpose:** This handler redirects users to the Dodo Payments checkout page.
249
- **File Creation:** Create a new file at `app/checkout/route.ts` in your Next.js project.
250
- **Code Snippet:**
251
- ```typescript
252
- // app/checkout/route.ts
253
- import { Checkout } from '@dodopayments/nextjs'
254
-
255
- export const GET = Checkout({
256
- bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
257
- returnUrl: process.env.RETURN_URL!,
258
- environment: "test_mode",
259
- type: "static", // explicitly specify type (optional, defaults to 'static')
260
- });
261
-
262
- export const POST = Checkout({
263
- bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
264
- returnUrl: process.env.RETURN_URL!,
265
- environment: "test_mode",
266
- type: "dynamic", // explicitly specify type for dynamic checkout
267
- });
268
- ```
269
- **Configuration & Usage:**
270
- * `bearerToken`: Your Dodo Payments API key. It's recommended to set this via the `DODO_PAYMENTS_API_KEY` environment variable.
271
- * `returnUrl`: (Optional) The URL to redirect the user to after a successful checkout.
272
- * `environment`: (Optional) Set to `"test_mode"` for testing, or omit/set to `"live_mode"` for production.
273
- * `type`: (Optional) Set to `"static"` for GET/static checkout, `"dynamic"` for POST/dynamic checkout. Defaults to `"static"`.
274
- * **Static Checkout (GET) Query Parameters:**
275
- * `productId` (required): Product identifier (e.g., `?productId=pdt_nZuwz45WAs64n3l07zpQR`)
276
- * `quantity` (optional): Quantity of the product
277
- * **Customer Fields (optional):** `fullName`, `firstName`, `lastName`, `email`, `country`, `addressLine`, `city`, `state`, `zipCode`
278
- * **Disable Flags (optional, set to `true` to disable):** `disableFullName`, `disableFirstName`, `disableLastName`, `disableEmail`, `disableCountry`, `disableAddressLine`, `disableCity`, `disableState`, `disableZipCode`
279
- * **Advanced Controls (optional):** `paymentCurrency`, `showCurrencySelector`, `paymentAmount`, `showDiscounts`
280
- * **Metadata (optional):** Any query parameter starting with `metadata_` (e.g., `?metadata_userId=abc123`)
281
- * **Dynamic Checkout (POST):** Parameters are sent as a JSON body. Supports both one-time and recurring payments. For a complete list of supported POST body fields, refer to:
282
- * [Docs - One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments)
283
- * [Docs - Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions)
284
- * **Error Handling:** If `productId` is missing or other query parameters are invalid, the handler will return a 400 response.
285
-
286
- ---
287
- **If `Customer Portal Route Handler` is selected:**
288
-
289
- **Purpose:** This handler redirects authenticated users to their Dodo Payments customer portal.
290
- **File Creation:** Create a new file at `app/customer-portal/route.ts` in your Next.js project.
291
- **Code Snippet:**
292
- ```typescript
293
- // app/customer-portal/route.ts
294
- import { CustomerPortal } from '@dodopayments/nextjs'
295
-
296
- export const GET = CustomerPortal({
297
- bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
298
- environment: "test_mode",
299
- });
300
- ```
301
- **Query Parameters:**
302
- * `customer_id` (required): The customer ID for the portal session (e.g., `?customer_id=cus_123`)
303
- * `send_email` (optional, boolean): If set to `true`, sends an email to the customer with the portal link.
304
- * Returns 400 if `customer_id` is missing.
305
-
306
- ---
307
- **If `Webhook Route Handler` is selected:**
308
-
309
- **Purpose:** This handler processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments, refunds, or subscription changes.
310
- **File Creation:** Create a new file at `app/api/webhook/dodo-payments/route.ts` in your Next.js project.
311
- **Code Snippet:**
312
- ```typescript
313
- // app/api/webhook/dodo-payments/route.ts
314
- import { Webhooks } from '@dodopayments/nextjs'
315
-
316
- export const POST = Webhooks({
317
- webhookKey: process.env.DODO_WEBHOOK_SECRET!,
318
- onPayload: async (payload) => {
319
- // handle the payload
320
- },
321
- // ... other event handlers for granular control
322
- });
323
- ```
324
- **Handler Details:**
325
- * **Method:** Only POST requests are supported. Other methods return 405.
326
- * **Signature Verification:** The handler verifies the webhook signature using the `webhookKey` and returns 401 if verification fails.
327
- * **Payload Validation:** The payload is validated with Zod. Returns 400 for invalid payloads.
328
- * **Error Handling:**
329
- * 401: Invalid signature
330
- * 400: Invalid payload
331
- * 500: Internal error during verification
332
- * **Event Routing:** Calls the appropriate event handler based on the payload type.
333
- * **Supported Webhook Event Handlers:**
334
- * `onPayload?: (payload: WebhookPayload) => Promise<void>;`
335
- * `onPaymentSucceeded?: (payload: WebhookPayload) => Promise<void>;`
336
- * `onPaymentFailed?: (payload: WebhookPayload) => Promise<void>;`
337
- * `onPaymentProcessing?: (payload: WebhookPayload) => Promise<void>;`
338
- * `onPaymentCancelled?: (payload: WebhookPayload) => Promise<void>;`
339
- * `onRefundSucceeded?: (payload: WebhookPayload) => Promise<void>;`
340
- * `onRefundFailed?: (payload: WebhookPayload) => Promise<void>;`
341
- * `onDisputeOpened?: (payload: WebhookPayload) => Promise<void>;`
342
- * `onDisputeExpired?: (payload: WebhookPayload) => Promise<void>;`
343
- * `onDisputeAccepted?: (payload: WebhookPayload) => Promise<void>;`
344
- * `onDisputeCancelled?: (payload: WebhookPayload) => Promise<void>;`
345
- * `onDisputeChallenged?: (payload: WebhookPayload) => Promise<void>;`
346
- * `onDisputeWon?: (payload: WebhookPayload) => Promise<void>;`
347
- * `onDisputeLost?: (payload: WebhookPayload) => Promise<void>;`
348
- * `onSubscriptionActive?: (payload: WebhookPayload) => Promise<void>;`
349
- * `onSubscriptionOnHold?: (payload: WebhookPayload) => Promise<void>;`
350
- * `onSubscriptionRenewed?: (payload: WebhookPayload) => Promise<void>;`
351
- * `onSubscriptionPaused?: (payload: WebhookPayload) => Promise<void>;`
352
- * `onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise<void>;`
353
- * `onSubscriptionCancelled?: (payload: WebhookPayload) => Promise<void>;`
354
- * `onSubscriptionFailed?: (payload: WebhookPayload) => Promise<void>;`
355
- * `onSubscriptionExpired?: (payload: WebhookPayload) => Promise<void>;`
356
- * `onLicenseKeyCreated?: (payload: WebhookPayload) => Promise<void>;`
357
-
358
- ---
359
-
360
- 3. **Environment Variable Setup:**
361
-
362
- To ensure the adapter functions correctly, you will need to manually set up the following environment variables in your Next.js project's deployment environment (e.g., Vercel, Netlify, AWS, etc.):
363
-
364
- * `DODO_PAYMENTS_API_KEY`: Your Dodo Payments API Key (required for Checkout and Customer Portal).
365
- * `RETURN_URL`: (Optional) The URL to redirect to after a successful checkout (for Checkout handler).
366
- * `DODO_WEBHOOK_SECRET`: Your Dodo Payments Webhook Secret (required for Webhook handler).
367
-
368
- **Example `.env` file:**
369
- ```env
370
- DODO_PAYMENTS_API_KEY=your-api-key
371
- DODO_WEBHOOK_SECRET=your-webhook-secret
372
- ```
373
-
374
- **Usage in your code:**
375
- ```typescript
376
- bearerToken: process.env.DODO_PAYMENTS_API_KEY!
377
- webhookKey: process.env.DODO_WEBHOOK_SECRET!
378
- ```
379
-
380
- **Important:** Never commit sensitive environment variables directly into your version control. Use environment variables for all sensitive information.
381
-
382
- If the user needs assistance setting up environment variables for their specific deployment environment, ask them what platform they are using (e.g., Vercel, Netlify, AWS, etc.), and provide guidance. You can also add comments to their PR or chat depending on the context.
111
+ Code Snippet:
383
112
 
384
- ---
113
+ // app/checkout/route.ts
114
+ import { Checkout } from '@dodopayments/nextjs'
115
+
116
+ export const GET = Checkout({
117
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
118
+ returnUrl: process.env.RETURN_URL!,
119
+ environment: "test_mode",
120
+ type: "static",
121
+ });
122
+
123
+ export const POST = Checkout({
124
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
125
+ returnUrl: process.env.RETURN_URL!,
126
+ environment: "test_mode",
127
+ type: "dynamic",
128
+ });
129
+
130
+ Configuration & Usage:
131
+
132
+ bearerToken: Your Dodo Payments API key. It's recommended to set this via the DODO_PAYMENTS_API_KEY environment variable.
133
+
134
+ returnUrl: (Optional) The URL to redirect the user to after a successful checkout.
135
+
136
+ environment: (Optional) Set to "test_mode" for testing, or omit/set to "live_mode" for production.
137
+
138
+ type: (Optional) Set to "static" for GET/static checkout, "dynamic" for POST/dynamic checkout. Defaults to "static".
139
+
140
+ Static Checkout (GET) Query Parameters:
141
+
142
+ productId (required): Product identifier (e.g., ?productId=pdt_nZuwz45WAs64n3l07zpQR)
143
+
144
+ quantity (optional): Quantity of the product
145
+
146
+ Customer Fields (optional): fullName, firstName, lastName, email, country, addressLine, city, state, zipCode
147
+
148
+ Disable Flags (optional, set to true to disable): disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode
149
+
150
+ Advanced Controls (optional): paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts
151
+
152
+ Metadata (optional): Any query parameter starting with metadata_ (e.g., ?metadata_userId=abc123)
153
+
154
+ Dynamic Checkout (POST): Parameters are sent as a JSON body. Supports both one-time and recurring payments. For a complete list of supported POST body fields, refer to:
155
+
156
+ Docs - One Time Payment Product: https://docs.dodopayments.com/api-reference/payments/post-payments
157
+
158
+ Docs - Subscription Product: https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions
159
+
160
+ Error Handling: If productId is missing or other query parameters are invalid, the handler will return a 400 response.
161
+
162
+ If Customer Portal Route Handler is selected:
163
+
164
+ Purpose: This handler redirects authenticated users to their Dodo Payments customer portal.
165
+ File Creation: Create a new file at app/customer-portal/route.ts in your Next.js project.
166
+
167
+ Code Snippet:
168
+
169
+ // app/customer-portal/route.ts
170
+ import { CustomerPortal } from '@dodopayments/nextjs'
171
+
172
+ export const GET = CustomerPortal({
173
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
174
+ environment: "test_mode",
175
+ });
176
+
177
+ Query Parameters:
178
+
179
+ customer_id (required): The customer ID for the portal session (e.g., ?customer_id=cus_123)
180
+
181
+ send_email (optional, boolean): If set to true, sends an email to the customer with the portal link.
182
+
183
+ Returns 400 if customer_id is missing.
184
+
185
+ If Webhook Route Handler is selected:
186
+
187
+ Purpose: This handler processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments, refunds, or subscription changes.
188
+ File Creation: Create a new file at app/api/webhook/dodo-payments/route.ts in your Next.js project.
189
+
190
+ Code Snippet:
191
+
192
+ // app/api/webhook/dodo-payments/route.ts
193
+ import { Webhooks } from '@dodopayments/nextjs'
194
+
195
+ export const POST = Webhooks({
196
+ webhookKey: process.env.DODO_WEBHOOK_SECRET!,
197
+ onPayload: async (payload) => {
198
+ // handle the payload
199
+ },
200
+ // ... other event handlers for granular control
201
+ });
202
+
203
+ Handler Details:
204
+
205
+ Method: Only POST requests are supported. Other methods return 405.
206
+
207
+ Signature Verification: The handler verifies the webhook signature using the webhookKey and returns 401 if verification fails.
208
+
209
+ Payload Validation: The payload is validated with Zod. Returns 400 for invalid payloads.
210
+
211
+ Error Handling:
212
+
213
+ 401: Invalid signature
214
+
215
+ 400: Invalid payload
216
+
217
+ 500: Internal error during verification
218
+
219
+ Event Routing: Calls the appropriate event handler based on the payload type.
220
+
221
+ Supported Webhook Event Handlers:
222
+
223
+ onPayload?: (payload: WebhookPayload) => Promise<void>
224
+
225
+ onPaymentSucceeded?: (payload: WebhookPayload) => Promise<void>
226
+
227
+ onPaymentFailed?: (payload: WebhookPayload) => Promise<void>
228
+
229
+ onPaymentProcessing?: (payload: WebhookPayload) => Promise<void>
230
+
231
+ onPaymentCancelled?: (payload: WebhookPayload) => Promise<void>
232
+
233
+ onRefundSucceeded?: (payload: WebhookPayload) => Promise<void>
234
+
235
+ onRefundFailed?: (payload: WebhookPayload) => Promise<void>
236
+
237
+ onDisputeOpened?: (payload: WebhookPayload) => Promise<void>
238
+
239
+ onDisputeExpired?: (payload: WebhookPayload) => Promise<void>
240
+
241
+ onDisputeAccepted?: (payload: WebhookPayload) => Promise<void>
242
+
243
+ onDisputeCancelled?: (payload: WebhookPayload) => Promise<void>
244
+
245
+ onDisputeChallenged?: (payload: WebhookPayload) => Promise<void>
246
+
247
+ onDisputeWon?: (payload: WebhookPayload) => Promise<void>
248
+
249
+ onDisputeLost?: (payload: WebhookPayload) => Promise<void>
250
+
251
+ onSubscriptionActive?: (payload: WebhookPayload) => Promise<void>
252
+
253
+ onSubscriptionOnHold?: (payload: WebhookPayload) => Promise<void>
254
+
255
+ onSubscriptionRenewed?: (payload: WebhookPayload) => Promise<void>
256
+
257
+ onSubscriptionPaused?: (payload: WebhookPayload) => Promise<void>
258
+
259
+ onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise<void>
260
+
261
+ onSubscriptionCancelled?: (payload: WebhookPayload) => Promise<void>
262
+
263
+ onSubscriptionFailed?: (payload: WebhookPayload) => Promise<void>
264
+
265
+ onSubscriptionExpired?: (payload: WebhookPayload) => Promise<void>
266
+
267
+ onLicenseKeyCreated?: (payload: WebhookPayload) => Promise<void>
268
+
269
+ Environment Variable Setup:
270
+
271
+ To ensure the adapter functions correctly, you will need to manually set up the following environment variables in your Next.js project's deployment environment (e.g., Vercel, Netlify, AWS, etc.):
272
+
273
+ DODO_PAYMENTS_API_KEY: Your Dodo Payments API Key (required for Checkout and Customer Portal).
274
+
275
+ RETURN_URL: (Optional) The URL to redirect to after a successful checkout (for Checkout handler).
276
+
277
+ DODO_WEBHOOK_SECRET: Your Dodo Payments Webhook Secret (required for Webhook handler).
278
+
279
+ Example .env file:
280
+
281
+ DODO_PAYMENTS_API_KEY=your-api-key
282
+ DODO_WEBHOOK_SECRET=your-webhook-secret
283
+
284
+ Usage in your code:
285
+
286
+ bearerToken: process.env.DODO_PAYMENTS_API_KEY!
287
+ webhookKey: process.env.DODO_WEBHOOK_SECRET!
288
+
289
+ Important: Never commit sensitive environment variables directly into your version control. Use environment variables for all sensitive information.
290
+
291
+ If the user needs assistance setting up environment variables for their specific deployment environment, ask them what platform they are using (e.g., Vercel, Netlify, AWS, etc.), and provide guidance. You can also add comments to their PR or chat depending on the context
292
+
293
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dodopayments/nextjs",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },