> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Better-Auth Adapter

> This guide shows you how to integrate Dodo Payments into your authentication flow using the Better-Auth adaptor.

# Overview

The <b>Better Auth Adapter</b> for Dodo Payments provides:

* Automatic customer creation on sign-up
* Checkout Sessions (preferred) with product slug mapping
* Self-service customer portal
* Metered usage ingestion and reporting endpoints for usage-based billing
* Real-time webhook event processing with signature verification
* Full TypeScript support

<Note>
  You need a Dodo Payments account and API keys to use this integration.
</Note>

# Prerequisites

* Node.js 20+
* Access to your Dodo Payments Dashboard
* Existing project using [better-auth](https://www.npmjs.com/package/better-auth)

# Installation

<Steps>
  <Step title="Install dependencies">
    Run the following command in your project root:

    ```bash theme={null}
    npm install @dodopayments/better-auth dodopayments better-auth zod
    ```

    <Check>
      All required packages are now installed.
    </Check>
  </Step>
</Steps>

# Setup

<Steps>
  <Step title="Configure environment variables">
    Add these to your <code>.env</code> file:

    ```env expandable theme={null}
    DODO_PAYMENTS_API_KEY=your_api_key_here
    DODO_PAYMENTS_WEBHOOK_SECRET=your_webhook_secret_here
    BETTER_AUTH_URL=http://localhost:3000
    BETTER_AUTH_SECRET=your_better_auth_secret_here
    ```

    <Warning>
      Never commit API keys or secrets to version control.
    </Warning>
  </Step>

  <Step title="Set up server-side integration">
    Create or update <code>src/lib/auth.ts</code>:

    ```typescript expandable theme={null}
    import { betterAuth } from "better-auth";
    import {
      dodopayments,
      checkout,
      portal,
      webhooks,
      usage,
    } from "@dodopayments/better-auth";
    import DodoPayments from "dodopayments";

    export const dodoPayments = new DodoPayments({
      bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
      environment: "test_mode", // or "live_mode" for production
    });

    export const { auth, endpoints, client } = BetterAuth({
      plugins: [
        dodopayments({
          client: dodoPayments,
          createCustomerOnSignUp: true,
          use: [
            checkout({
              products: [
                {
                  productId: "pdt_xxxxxxxxxxxxxxxxxxxxx",
                  slug: "premium-plan",
                },
              ],
              successUrl: "/dashboard/success",
              authenticatedUsersOnly: true,
            }),
            portal(),
            webhooks({
              webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_SECRET!,
              onPayload: async (payload) => {
                console.log("Received webhook:", payload.event_type);
              },
            }),
            usage(),
          ],
        }),
      ],
    });
    ```

    <Tip>
      Set <code>environment</code> to <code>live\_mode</code> for production.
    </Tip>
  </Step>

  <Step title="Set up client-side integration">
    Create or update <code>src/lib/auth-client.ts</code>:

    ```typescript expandable theme={null}
    import { createAuthClient } from "better-auth/react";
    import { dodopaymentsClient } from "@dodopayments/better-auth/client";

    export const authClient = createAuthClient({
      baseURL: process.env.BETTER_AUTH_URL || "http://localhost:3000",
      plugins: [dodopaymentsClient()],
    });
    ```
  </Step>
</Steps>

# Usage Examples

<Info>
  Prefer <code>authClient.dodopayments.checkoutSession</code> for new
  integrations. The legacy <code>checkout</code> method is deprecated and kept
  only for backward compatibility.
</Info>

## Creating a Checkout Session (Preferred)

<CodeGroup>
  ```typescript Using a slug theme={null}
  const { data: session, error } = await authClient.dodopayments.checkoutSession({
    // Option A: use a configured slug
    slug: "premium-plan",

  // Your internal id for reference
  referenceId: "order_123",
  });

  if (session) {
  window.location.href = session.url;
  }

  ```

  ```typescript Using product cart theme={null}
  const { data: session, error } = await authClient.dodopayments.checkoutSession({
    // Option B: pass a product cart/product id directly
    product_cart: [
      {
        product_id: "pdt_xxxxxxxxxxxxxxxxxxxxx",
        quantity: 1,
      }
    ],

    // Your internal id for reference
    referenceId: "order_123",
  });

  if (session) {
    window.location.href = session.url;
  }
  ```
</CodeGroup>

<Info>
  기존 <code>checkout</code> 메서드와 달리 <code>checkoutSession</code>은 결제 페이지에서 사용자의 정보가 가져가므로 처음부터 결제 정보를 요구하지 않습니다. 그래도 인수에 <code>billing</code> 키를 전달하여 이를 재정의할 수 있습니다.
</Info>

<Info>
  기존 <code>checkout</code> 메서드와 유사하게, <code>checkoutSession</code>은 더 나은 인증 세션에서 고객의 이메일과 이름을 가져오지만, 이메일과 이름이 포함된 <code>customer</code> 객체를 전달하여 재정의할 수 있습니다.
</Info>

<Info>
  인수에서 동일한 옵션을 [체크아웃 세션 생성](https://docs.dodopayments.com/api-reference/checkout-sessions/create) 엔드포인트의 요청 본문으로 전달할 수 있습니다.
</Info>

<Note>
  리턴 URL은 서버 플러그인에 구성된 <code>successUrl</code>에서 가져옵니다. 클라이언트 페이로드에 <code>return\_url</code>을 포함할 필요가 없습니다.
</Note>

## 레거시 체크아웃 (사용 중단됨)

<Warning>
  <code>authClient.dodopayments.checkout</code> 메서드는 사용 중단되었습니다. 새로운 구현에 <code>checkoutSession</code>을 사용하세요.
</Warning>

```typescript expandable theme={null}
const { data: checkout, error } = await authClient.dodopayments.checkout({
  slug: "premium-plan",
  customer: {
    email: "customer@example.com",
    name: "John Doe",
  },
  billing: {
    city: "San Francisco",
    country: "US",
    state: "CA",
    street: "123 Market St",
    zipcode: "94103",
  },
  referenceId: "order_123",
});

if (checkout) {
  window.location.href = checkout.url;
}
```

## 고객 포털에 접근

```typescript expandable theme={null}
const { data: customerPortal, error } =
  await authClient.dodopayments.customer.portal();
if (customerPortal && customerPortal.redirect) {
  window.location.href = customerPortal.url;
}
```

## 고객 데이터 나열

```typescript expandable theme={null}
// Get subscriptions
const { data: subscriptions, error } =
  await authClient.dodopayments.customer.subscriptions.list({
    query: {
      limit: 10,
      page: 1,
      status: "active",
    },
  });

// Get payment history
const { data: payments, error } =
  await authClient.dodopayments.customer.payments.list({
    query: {
      limit: 10,
      page: 1,
      status: "succeeded",
    },
  });
```

## 미터별 사용량 추적

서버에서 <code>usage()</code> 플러그인을 활성화하여 미터링 이벤트를 캡처하고 고객이 사용 기반 청구를 확인할 수 있도록 합니다.

* <code>authClient.dodopayments.usage.ingest</code>는 로그인 및 이메일이 인증된 사용자의 이벤트를 수집합니다.
* <code>authClient.dodopayments.usage.meters.list</code>는 해당 고객의 구독에 연결된 미터의 최근 사용량을 나열합니다.

```typescript expandable theme={null}
// Record a metered event (e.g., an API request)
const { error: ingestError } = await authClient.dodopayments.usage.ingest({
  event_id: crypto.randomUUID(),
  event_name: "api_request",
  metadata: {
    route: "/reports",
    method: "GET",
  },
  // Optional Date; defaults to now if omitted
  timestamp: new Date(),
});

if (ingestError) {
  console.error("Failed to record usage", ingestError);
}

// List recent usage for the current customer
const { data: usage, error: usageError } =
  await authClient.dodopayments.usage.meters.list({
    query: {
      page_size: 20,
      meter_id: "mtr_yourMeterId", // optional
    },
  });

if (usage?.items) {
  usage.items.forEach((event) => {
    console.log(event.event_name, event.timestamp, event.metadata);
  });
}
```

<Tip>
  사용량 수집 시 한 시간 이상이거나 5분 이상 미래의 타임스탬프는 거부됩니다.
</Tip>

<Tip>
  사용량 미터를 나열할 때 <code>meter\_id</code>를 생략하면 고객의 구독에 연결된 모든 미터가 반환됩니다.
</Tip>

# 웹훅

<Info>
  웹훅 플러그인은 Dodo Payments의 실시간 결제 이벤트를 안전한 서명 검증과 함께 처리합니다. 기본 엔드포인트는 <code>/api/auth/dodopayments/webhooks</code>입니다.
</Info>

<Steps>
  <Step title="Generate and set webhook secret">
    웹훅 비밀을 Dodo Payments 대시보드에서 엔드포인트 URL (예: <code>https\://\<your-domain>/api/auth/dodopayments/webhooks</code>)에 대해 생성하고 <code>.env</code> 파일에 설정하세요.

    ```env theme={null}
    DODO_PAYMENTS_WEBHOOK_SECRET=your_webhook_secret_here
    ```
  </Step>

  <Step title="Handle webhook events">
    예제 핸들러:

    ```typescript expandable theme={null}
    webhooks({
      webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_SECRET!,
      onPayload: async (payload) => {
        console.log("Received webhook:", payload.event_type);
      },
    });
    ```
  </Step>
</Steps>

### 지원되는 웹훅 이벤트 핸들러

<CodeGroup>
  ```typescript Typescript expandable theme={null}
  onPayload?: (payload: WebhookPayload) => Promise<void>;
  onPaymentSucceeded?: (payload: WebhookPayload) => Promise<void>;
  onPaymentFailed?: (payload: WebhookPayload) => Promise<void>;
  onPaymentProcessing?: (payload: WebhookPayload) => Promise<void>;
  onPaymentCancelled?: (payload: WebhookPayload) => Promise<void>;
  onRefundSucceeded?: (payload: WebhookPayload) => Promise<void>;
  onRefundFailed?: (payload: WebhookPayload) => Promise<void>;
  onDisputeOpened?: (payload: WebhookPayload) => Promise<void>;
  onDisputeExpired?: (payload: WebhookPayload) => Promise<void>;
  onDisputeAccepted?: (payload: WebhookPayload) => Promise<void>;
  onDisputeCancelled?: (payload: WebhookPayload) => Promise<void>;
  onDisputeChallenged?: (payload: WebhookPayload) => Promise<void>;
  onDisputeWon?: (payload: WebhookPayload) => Promise<void>;
  onDisputeLost?: (payload: WebhookPayload) => Promise<void>;
  onSubscriptionActive?: (payload: WebhookPayload) => Promise<void>;
  onSubscriptionOnHold?: (payload: WebhookPayload) => Promise<void>;
  onSubscriptionRenewed?: (payload: WebhookPayload) => Promise<void>;
  onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise<void>;
  onSubscriptionCancelled?: (payload: WebhookPayload) => Promise<void>;
  onSubscriptionFailed?: (payload: WebhookPayload) => Promise<void>;
  onSubscriptionExpired?: (payload: WebhookPayload) => Promise<void>;
  onSubscriptionUpdated?: (payload: WebhookPayload) => Promise<void>;
  onLicenseKeyCreated?: (payload: WebhookPayload) => Promise<void>;
  onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise<void>;
  onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise<void>;
  onDunningStarted?: (payload: WebhookPayload) => Promise<void>;
  onDunningRecovered?: (payload: WebhookPayload) => Promise<void>;
  onCreditAdded?: (payload: WebhookPayload) => Promise<void>;
  onCreditDeducted?: (payload: WebhookPayload) => Promise<void>;
  onCreditExpired?: (payload: WebhookPayload) => Promise<void>;
  onCreditRolledOver?: (payload: WebhookPayload) => Promise<void>;
  onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise<void>;
  onCreditOverageCharged?: (payload: WebhookPayload) => Promise<void>;
  onCreditManualAdjustment?: (payload: WebhookPayload) => Promise<void>;
  onCreditBalanceLow?: (payload: WebhookPayload) => Promise<void>;
  ```
</CodeGroup>

# 구성 참고

<AccordionGroup>
  <Accordion title="Plugin Options">
    * <b>client</b> (필수): DodoPayments 클라이언트 인스턴스
    * <b>createCustomerOnSignUp</b> (선택 사항): 사용자 등록 시 자동으로 고객 생성
    * <b>use</b> (필수): 사용할 플러그인 배열 (checkout, portal, usage, webhooks)
    * <b>getCustomerParams</b> (선택 사항): BetterAuth `User`을 수신하고 생성 및 업데이트 시 DodoPayments 고객에 첨부할 추가 필드를 반환하는 함수 (예: `metadata`, `phone_number`)

    ```typescript theme={null}
    dodopayments({
      client: dodoPayments,
      createCustomerOnSignUp: true,
      use: [portal()],
      getCustomerParams: (user) => ({
        metadata: { userId: user.id },
        phone_number: user.phoneNumber ?? null,
      }),
    })
    ```
  </Accordion>

  <Accordion title="Checkout Plugin Options">
    * <b>products</b>: 제품 배열 또는 제품을 반환하는 비동기 함수 -{" "}
      <b>successUrl</b>: 성공적인 결제 후 리디렉션할 URL -{" "}
      <b>authenticatedUsersOnly</b>: 사용자 인증 필요 (기본값: false)
  </Accordion>
</AccordionGroup>

# 문제 해결 및 팁

<AccordionGroup>
  <Accordion title="Common Issues">
    * <b>잘못된 API 키</b>: <code>.env</code>에서 <code>DODO\_PAYMENTS\_API\_KEY</code>를 다시 확인하세요. -{" "}
      <b>웹훅 서명 불일치</b>: 웹훅 비밀이 Dodo Payments 대시보드의 것과 일치하는지 확인하세요. - <b>고객이 생성되지 않음</b>: <code>createCustomerOnSignUp</code>이 <code>true</code>로 설정되어 있는지 확인하세요.
  </Accordion>

  <Accordion title="Best Practices">
    * 모든 비밀 및 키에 대한 환경 변수를 사용하세요. - <code>live\_mode</code>로 전환하기 전에 <code>test\_mode</code>에서 테스트하세요. - 디버깅 및 감사를 위해 웹훅 이벤트를 로그에 기록하세요.
  </Accordion>
</AccordionGroup>

# LLMs에 대한 프롬프트

```text expandable theme={null}
You are a skilled developer helping to integrate the @dodopayments/better-auth adapter into a typescript web application with better-auth. This adapter enables seamless payment processing through Dodo Payments with automatic customer management, checkout flows, and webhook handling.
STAGE 1: BASIC SETUP
This stage covers the foundational setup needed before implementing any plugins. Complete this stage first.
STEP 1: Installation
Install the required dependencies:
npm install @dodopayments/better-auth dodopayments better-auth zod
STEP 2: Environment Variables Setup
You will need to complete these external setup tasks. I will provide you with a TODO list for the actions you need to take outside of the code:
TODO LIST FOR USER:
1. Generate Dodo Payments API Key:
   - Go to your Dodo Payments Dashboard > Developer > API Keys
   - Create a new API key (or use existing)
   - Copy the API key value
   - Set environment variable: DODO_PAYMENTS_API_KEY=your_api_key_here
2. Generate Better Auth Secret:
   - Generate a random secret key (32+ characters)
   - Set environment variable: BETTER_AUTH_SECRET=your_better_auth_secret_here
3. Set Application URL:
   - For development: BETTER_AUTH_URL=http://localhost:3000
   - For production: BETTER_AUTH_URL=https://your-domain.com
4. Webhook Secret (only if implementing webhooks plugin):
   - This will be provided after you specify your domain name in Stage 2
   - Set environment variable: DODO_PAYMENTS_WEBHOOK_SECRET=your_webhook_secret_here
Add these environment variables to your .env file:
DODO_PAYMENTS_API_KEY=your_api_key_here
DODO_PAYMENTS_WEBHOOK_SECRET=your_webhook_secret_here
BETTER_AUTH_URL=http://localhost:3000
BETTER_AUTH_SECRET=your_better_auth_secret_here
STEP 3: Server Configuration
Create or update your better-auth setup file (src/lib/auth.ts):
import { BetterAuth } from "better-auth";
import { dodopayments } from "@dodopayments/better-auth";
import DodoPayments from "dodopayments";
// Create DodoPayments client
export const dodoPayments = new DodoPayments({
  bearerToken: process.env.DODO_PAYMENTS_API_KEY!,
  environment: "test_mode", // Change to "live_mode" for production
});
// Configure better-auth with dodopayments adapter
export const { auth, endpoints, client } = BetterAuth({
  plugins: [
    dodopayments({
      client: dodoPayments,
      createCustomerOnSignUp: true, // Auto-create customers on signup
      use: [], // We'll add plugins here in Stage 2
      // Optional: attach metadata or phone_number to DodoPayments customer records
      // getCustomerParams: (user) => ({
      //   metadata: { userId: user.id },
      //   phone_number: user.phoneNumber ?? null,
      // }),
    }),
  ],
});
STEP 4: Client Configuration
Create or update your auth client file (src/lib/auth-client.ts):
import { createAuthClient } from "better-auth/react";
import { dodopaymentsClient } from "@dodopayments/better-auth/client";
export const authClient = createAuthClient({
  baseURL: process.env.BETTER_AUTH_URL || "http://localhost:3000",
  plugins: [dodopaymentsClient()],
});
STAGE 2: PLUGIN IMPLEMENTATION
After completing Stage 1, you can selectively implement any of these plugins based on your needs. Each plugin is independent and can be added or removed as needed.
PLUGIN SELECTION:
Before implementing any plugins, ask the user which plugins they want to implement:
"Which plugins would you like to implement? You can choose any combination of:
1. CHECKOUT - Enables secure payment processing and checkout flows
2. PORTAL - Provides customer self-service portal for subscriptions and payments
3. USAGE - Tracks metered events and exposes usage history for billing beyond included allowances
4. WEBHOOKS - Handles real-time payment events from Dodo Payments
Please specify which plugins you want (e.g., 'checkout and usage', 'all four', 'just portal', etc.)"
If the user doesn't respond or you cannot prompt the user, implement all four plugins by default.
Based on the user's selection, implement only the requested plugins from the sections below:
CHECKOUT PLUGIN
Purpose: Enables secure payment processing using Checkout Sessions (preferred) with product slug mapping. A legacy checkout endpoint is also exposed for backward compatibility but is deprecated.
SETUP TODO LIST FOR USER:
1. Create products in Dodo Payments Dashboard:
   - Go to Dodo Payments Dashboard > Products
   - Create your products (e.g., subscription plans, one-time purchases)
   - Copy each product ID (starts with "pdt_")
   - Note down the product names for creating friendly slugs
2. Plan your checkout URLs:
   - Decide on your success URL (e.g., "/dashboard/success", "/thank-you")
   - Ensure this URL exists in your application
Configuration:
Add checkout to your imports in src/lib/auth.ts:
import { dodopayments, checkout } from "@dodopayments/better-auth";
Add checkout plugin to the use array in your dodopayments configuration:
use: [
  checkout({
    products: [
      {
        productId: "pdt_xxxxxxxxxxxxxxxxxxxxx", // Your actual product ID from Dodo Payments
        slug: "premium-plan", // Friendly slug for checkout
      },
      // Add more products as needed
    ],
    successUrl: "/dashboard/success", // Your success page URL
    authenticatedUsersOnly: true, // Require login for checkout
  }),
],
Usage Example (Preferred - Checkout Sessions):
const { data: session, error } = await authClient.dodopayments.checkoutSession({
  // Use the slug from your configuration OR provide product_cart directly
  slug: "premium-plan",
  // product_cart: [{ product_id: "pdt_xxxxxxxxxxxxxxxxxxxxx", quantity: 1 }],
  referenceId: "order_123", // Optional reference
});
if (session) {
  window.location.href = session.url;
}

Deprecated (Legacy Checkout):
const { data: checkout, error } = await authClient.dodopayments.checkout({
  slug: "premium-plan",
  customer: {
    email: "customer@example.com",
    name: "John Doe",
  },
  billing: {
    city: "San Francisco",
    country: "US",
    state: "CA",
    street: "123 Market St",
    zipcode: "94103",
  },
});
if (checkout) {
  window.location.href = checkout.url;
}
Options:
- products: Array of products or async function returning products
- successUrl: URL to redirect after successful payment
- authenticatedUsersOnly: Require user authentication (default: false)
PORTAL PLUGIN
Purpose: Provides customer self-service capabilities for managing subscriptions and viewing payment history.
Configuration:
Add portal to your imports in src/lib/auth.ts:
import { dodopayments, portal } from "@dodopayments/better-auth";
Add portal plugin to the use array in your dodopayments configuration:
use: [
  portal(),
],
Usage Examples:
// Access customer portal
const { data: customerPortal, error } = await authClient.dodopayments.customer.portal();
if (customerPortal && customerPortal.redirect) {
  window.location.href = customerPortal.url;
}
// List customer subscriptions
const { data: subscriptions, error } = await authClient.dodopayments.customer.subscriptions.list({
  query: {
    limit: 10,
    page: 1,
    active: true,
  },
});
// List customer payments
const { data: payments, error } = await authClient.dodopayments.customer.payments.list({
  query: {
    limit: 10,
    page: 1,
    status: "succeeded",
  },
});
Note: All portal methods require user authentication.

USAGE PLUGIN (METERED BILLING)
Purpose: Records metered events (like API requests) for usage-based plans and surfaces recent usage history per customer.

SETUP TODO LIST FOR USER:
1. Create or identify usage meters in the Dodo Payments Dashboard:
   - Dashboard > Usage > Meters
   - Copy the meter IDs (prefixed with <code>mtr_</code>) used by your usage-based plans
2. Decide which event names and metadata you will capture (e.g., <code>api_request</code>, route, method)
3. Ensure BetterAuth users verify their email addresses (the plugin enforces this before ingesting usage)

Configuration:
Add usage to your imports in <code>src/lib/auth.ts</code>:
    import { dodopayments, usage } from "@dodopayments/better-auth";

Add the plugin to the <code>use</code> array:
    use: [
      usage(),
    ],

Usage Examples:

    // Record a metered event for the signed-in customer
    const { error: ingestError } = await authClient.dodopayments.usage.ingest({
      event_id: crypto.randomUUID(),
      event_name: "api_request",
      metadata: {
        route: "/reports",
        method: "GET",
      },
      // Optional Date or ISO string; defaults to now
      timestamp: new Date(),
    });

    if (ingestError) {
      console.error("Failed to record usage", ingestError);
    }

    // List recent usage for the current customer
    const { data: usage, error: usageError } =
      await authClient.dodopayments.usage.meters.list({
        query: {
          page_size: 20,
          meter_id: "mtr_yourMeterId", // optional filter
        },
      });

    if (usage?.items) {
      usage.items.forEach((event) => {
        console.log(event.event_name, event.timestamp, event.metadata);
      });
    }

<Tip>
  The plugin exposes <code>authClient.dodopayments.usage.ingest</code> and
  <code>authClient.dodopayments.usage.meters.list</code>. Timestamps older
  than one hour or more than five minutes in the future are rejected.
</Tip>
<Tip>
  If you do
  not pass <code>meter_id</code> when listing usage meters, all meters tied to 
  the customer’s active subscriptions are returned.
</Tip>
WEBHOOKS PLUGIN
Purpose: Handles real-time payment events from Dodo Payments with secure signature verification.
BEFORE CONFIGURATION - Setup Webhook URL:
First, I need your domain name to generate the webhook URL and provide you with setup instructions.
STEP 1: Domain Name Input
What is your domain name? Please provide:
- For production: your domain name (e.g., "myapp.com", "api.mycompany.com")
- For staging: your staging domain (e.g., "staging.myapp.com")
- For development: use "localhost:3000" (or your local port)
STEP 2: After receiving your domain name, I will:
- Generate your webhook URL: https://[YOUR-DOMAIN]/api/auth/dodopayments/webhooks
- Provide you with a TODO list for webhook setup in Dodo Payments dashboard
- Give you the exact environment variable setup instructions
WEBHOOK SETUP TODO LIST (will be provided after domain input):
1. Configure webhook in Dodo Payments Dashboard:
   - Go to Dodo Payments Dashboard > Developer > Webhooks
   - Click "Add Webhook" or "Create Webhook"
   - Enter webhook URL: https://[YOUR-DOMAIN]/api/auth/dodopayments/webhooks
   - Select events you want to receive (or select all)
   - Copy the generated webhook secret
2. Set webhook secret in your environment:
   - For production: Set DODO_PAYMENTS_WEBHOOK_SECRET in your hosting provider environment
   - For staging: Set DODO_PAYMENTS_WEBHOOK_SECRET in your staging environment
   - For development: Add DODO_PAYMENTS_WEBHOOK_SECRET=your_webhook_secret_here to your .env file
3. Deploy your application with the webhook secret configured
STEP 3: Add webhooks to your imports in src/lib/auth.ts:
import { dodopayments, webhooks } from "@dodopayments/better-auth";
STEP 4: Add webhooks plugin to the use array in your dodopayments configuration:
use: [
  webhooks({
    webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_SECRET!,
    // Generic handler for all webhook events
    onPayload: async (payload) => {
      console.log("Received webhook:", payload.event_type);
    },
    // Payment event handlers
    onPaymentSucceeded: async (payload) => {
      console.log("Payment succeeded:", payload);
    },
    onPaymentFailed: async (payload) => {
      console.log("Payment failed:", payload);
    },
    onPaymentProcessing: async (payload) => {
      console.log("Payment processing:", payload);
    },
    onPaymentCancelled: async (payload) => {
      console.log("Payment cancelled:", payload);
    },
    // Refund event handlers
    onRefundSucceeded: async (payload) => {
      console.log("Refund succeeded:", payload);
    },
    onRefundFailed: async (payload) => {
      console.log("Refund failed:", payload);
    },
    // Dispute event handlers
    onDisputeOpened: async (payload) => {
      console.log("Dispute opened:", payload);
    },
    onDisputeExpired: async (payload) => {
      console.log("Dispute expired:", payload);
    },
    onDisputeAccepted: async (payload) => {
      console.log("Dispute accepted:", payload);
    },
    onDisputeCancelled: async (payload) => {
      console.log("Dispute cancelled:", payload);
    },
    onDisputeChallenged: async (payload) => {
      console.log("Dispute challenged:", payload);
    },
    onDisputeWon: async (payload) => {
      console.log("Dispute won:", payload);
    },
    onDisputeLost: async (payload) => {
      console.log("Dispute lost:", payload);
    },
    // Subscription event handlers
    onSubscriptionActive: async (payload) => {
      console.log("Subscription active:", payload);
    },
    onSubscriptionOnHold: async (payload) => {
      console.log("Subscription on hold:", payload);
    },
    onSubscriptionRenewed: async (payload) => {
      console.log("Subscription renewed:", payload);
    },
    onSubscriptionPlanChanged: async (payload) => {
      console.log("Subscription plan changed:", payload);
    },
    onSubscriptionCancelled: async (payload) => {
      console.log("Subscription cancelled:", payload);
    },
    onSubscriptionFailed: async (payload) => {
      console.log("Subscription failed:", payload);
    },
    onSubscriptionExpired: async (payload) => {
      console.log("Subscription expired:", payload);
    },
    onSubscriptionUpdated: async (payload) => {
      console.log("Subscription updated:", payload);
    },
    // License key event handlers
    onLicenseKeyCreated: async (payload) => {
      console.log("License key created:", payload);
    },
    // Abandoned checkout event handlers
    onAbandonedCheckoutDetected: async (payload) => {
      console.log("Abandoned checkout detected:", payload);
    },
    onAbandonedCheckoutRecovered: async (payload) => {
      console.log("Abandoned checkout recovered:", payload);
    },
    // Dunning event handlers
    onDunningStarted: async (payload) => {
      console.log("Dunning started:", payload);
    },
    onDunningRecovered: async (payload) => {
      console.log("Dunning recovered:", payload);
    },
    // Credit event handlers
    onCreditAdded: async (payload) => {
      console.log("Credit added:", payload);
    },
    onCreditDeducted: async (payload) => {
      console.log("Credit deducted:", payload);
    },
    onCreditExpired: async (payload) => {
      console.log("Credit expired:", payload);
    },
    onCreditRolledOver: async (payload) => {
      console.log("Credit rolled over:", payload);
    },
    onCreditRolloverForfeited: async (payload) => {
      console.log("Credit rollover forfeited:", payload);
    },
    onCreditOverageCharged: async (payload) => {
      console.log("Credit overage charged:", payload);
    },
    onCreditManualAdjustment: async (payload) => {
      console.log("Credit manual adjustment:", payload);
    },
    onCreditBalanceLow: async (payload) => {
      console.log("Credit balance low:", payload);
    },
  }),
],
Supported Webhook Event Handlers:
- onPayload: Generic handler for all webhook events
- onPaymentSucceeded: Payment completed successfully
- onPaymentFailed: Payment failed
- onPaymentProcessing: Payment is being processed
- onPaymentCancelled: Payment was cancelled
- onRefundSucceeded: Refund completed successfully
- onRefundFailed: Refund failed
- onDisputeOpened: Dispute was opened
- onDisputeExpired: Dispute expired
- onDisputeAccepted: Dispute was accepted
- onDisputeCancelled: Dispute was cancelled
- onDisputeChallenged: Dispute was challenged
- onDisputeWon: Dispute was won
- onDisputeLost: Dispute was lost
- onSubscriptionActive: Subscription became active
- onSubscriptionOnHold: Subscription was put on hold
- onSubscriptionRenewed: Subscription was renewed
- onSubscriptionPlanChanged: Subscription plan was changed
- onSubscriptionCancelled: Subscription was cancelled
- onSubscriptionFailed: Subscription failed
- onSubscriptionExpired: Subscription expired
- onSubscriptionUpdated: Subscription was updated
- onLicenseKeyCreated: License key was created
- onAbandonedCheckoutDetected: Abandoned checkout was detected
- onAbandonedCheckoutRecovered: Abandoned checkout was recovered
- onDunningStarted: Dunning process started
- onDunningRecovered: Dunning process recovered
- onCreditAdded: Credits were added
- onCreditDeducted: Credits were deducted
- onCreditExpired: Credits expired
- onCreditRolledOver: Credits were rolled over
- onCreditRolloverForfeited: Credit rollover was forfeited
- onCreditOverageCharged: Credit overage was charged
- onCreditManualAdjustment: Manual credit adjustment was made
- onCreditBalanceLow: Credit balance is low
COMBINING SELECTED PLUGINS:
After implementing the user's selected plugins, update your <code>src/lib/auth.ts</code> file to include all chosen plugins in the imports and <code>use</code> array:

Example for all four plugins:
    import {
      dodopayments,
      checkout,
      portal,
      usage,
      webhooks,
    } from "@dodopayments/better-auth";

    use: [
      checkout({
        // checkout configuration
      }),
      portal(),
      usage(),
      webhooks({
        // webhook configuration
      }),
    ];

Example for checkout + portal + usage:
    import { dodopayments, checkout, portal, usage } from "@dodopayments/better-auth";

    use: [
      checkout({
        // checkout configuration
      }),
      portal(),
      usage(),
    ];

Example for just webhooks:
    import { dodopayments, webhooks } from "@dodopayments/better-auth";

    use: [
      webhooks({
        // webhook configuration
      }),
    ];
IMPORTANT NOTES:
1. Complete Stage 1 before implementing any plugins
2. Ask the user which plugins they want to implement, or implement all four if no response
3. Only implement the plugins the user specifically requested
4. ALWAYS provide TODO lists for external actions the user needs to complete:
   - API key generation and environment variable setup
   - Product creation in Dodo Payments dashboard (for checkout plugin)
   - Usage meter configuration and API event definition (for usage plugin)
   - Webhook setup in Dodo Payments dashboard (for webhooks plugin)
   - Domain name collection for webhook URL generation
5. For webhook plugin: Ask for the user's domain name and generate the exact webhook URL: https://[domain]/api/auth/dodopayments/webhooks
6. The usage plugin requires the BetterAuth session user to exist and have a verified email before ingesting or listing usage
7. All client methods return <code>{ data, error }</code> objects for proper error handling
8. Use <code>test_mode</code> for development and <code>live_mode</code> for production
9. The webhook endpoint is automatically created and secured with signature verification (if webhooks plugin is selected)
10. Customer portal and subscription listing require user authentication (if portal plugin is selected)
11. Handle errors appropriately and test webhook functionality in development before going live
12. Present all external setup tasks as clear TODO lists with specific environment variable names
13. Use getCustomerParams to attach metadata or phone_number to DodoPayments customer records — the function receives the BetterAuth User object and runs on every customer creation and update

```
