> ## 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.

# Next.js 最小化模板

> 克隆 Next.js 最小样板，即可获得定价页面、结账会话、webhook 处理程序，以及已接入 Dodo Payments 的 Customer Portal 链接。

## 概述

Next.js 最小样板是一个已连接 Dodo Payments 的入门应用。添加 API 密钥和产品 ID 后，即可获得一个可打开结账页面的定价页面、一个用于处理支付事件的 webhook 端点，以及一个指向 Customer Portal 的链接。

> [!NOTE]
>
> 此样板使用带有 TypeScript、Tailwind CSS 4 和 `@dodopayments/nextjs` adaptor 的 Next.js 16 App Router。若要将相同的路由处理程序添加到现有应用，请参阅 [Next.js Adaptor](/developer-resources/nextjs-adaptor)。

### 特性

样板包含：

* **快速设置**：大约五分钟即可从克隆项目开始运行定价页面。
* **结账**：基于 `@dodopayments/nextjs` 构建的预配置结账流程。
* **定价页面**：使用 Tailwind CSS 设置样式的深色主题定价页面。
* **Webhook 处理程序**：验证每个 webhook 签名并为事件运行你的代码的端点。
* **Customer Portal**：打开 Customer Portal 的页眉链接，客户可以在其中管理订阅。
* **TypeScript**：带类型的产品定义和处理程序。
* **预填充结账信息**：将客户姓名和电子邮件传递给结账页面，客户无需重新输入。

## 前置条件

开始之前，你需要：

* **Node.js 20.9 或更高版本**，这是 Next.js 16 的要求。
* **Dodo Payments 账户**，用于在控制面板中创建 API 密钥和 webhook 签名密钥。

## 快速开始

**1. Clone the Repository**

```bash theme={null}
git clone https://github.com/dodopayments/dodo-nextjs-minimal-boilerplate.git
cd dodo-nextjs-minimal-boilerplate
```

**2. Install Dependencies**

```bash theme={null}
npm install
```

**3. Get API Credentials**

在 [Dodo Payments](https://dodopayments.com/) 注册，然后从控制面板获取凭据：

* **API Key：** 在 [Dashboard → Developer → API Keys](https://app.dodopayments.com/developer/api-keys) 下创建密钥。
* **Webhook Key：** 在 [Dashboard → Developer → Webhooks](https://app.dodopayments.com/developer/webhooks) 下添加端点，然后复制其签名密钥。端点 URL 必须公开并使用 HTTPS。若要在你的计算机上接收事件，请参阅 [Webhook Events](#webhook-events)。

> [!TIP]
>
> 在侧边栏中的 **Live Mode** 开关关闭时创建这两项。测试模式密钥只能与 `DODO_PAYMENTS_ENVIRONMENT=test_mode` 配合使用，测试模式支付不会转移真实资金。

**4. Configure Environment Variables**

将示例文件复制到根目录，以创建一个 `.env` 文件：

```bash theme={null}
cp .env.example .env
```

将值设置为你的 Dodo Payments 凭据：

```env theme={null}
DODO_PAYMENTS_API_KEY=your_api_key_here
DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_signing_key_here
DODO_PAYMENTS_RETURN_URL=http://localhost:3000
DODO_PAYMENTS_ENVIRONMENT=test_mode
```

路由处理程序会读取以下变量：

* `DODO_PAYMENTS_API_KEY` 用于验证结账和 Customer Portal 处理程序。
* `DODO_PAYMENTS_WEBHOOK_KEY` 用于验证 webhook 签名。
* `DODO_PAYMENTS_RETURN_URL` 是结账完成支付后将客户重定向到的位置。
* `DODO_PAYMENTS_ENVIRONMENT` 的值为 `test_mode` 或 `live_mode`。

> [!WARNING]
>
> 不要将 `.env` 文件提交到版本控制中。代码库中的 `.gitignore` 已将其排除。

**5. Add Your Products**

将 `src/lib/products.ts` 中的示例产品替换为你自己的产品。将每个 `product_id` 设置为控制面板 **Products** 下某个产品的 ID：

```typescript theme={null}
export const products: Product[] = [
  {
    product_id: "pdt_001", // Replace with your product ID
    name: "Basic Plan",
    description: "Get access to basic features and support",
    price: 9999, // in cents
    features: [
      "Access to basic features",
      "Email support",
      "1 Team member",
      "Basic analytics",
    ],
  },
  // ... add more products
];
```

定价页面会从此文件中显示 `name`、`description`、`price` 和 `features`。结账会按照 Dodo Payments 中产品设置的价格收费，因此请确保 `price` 与产品保持同步。

**6. Run the Development Server**

```bash theme={null}
npm run dev
```

打开 [http://localhost:3000](http://localhost:3000) 查看你的定价页面。

## 项目结构

结账、Customer Portal 和 webhook 路由处理程序位于 `src/app/api/` 下：

```text theme={null}
src/
├── app/
│   ├── api/
│   │   ├── checkout/          # Checkout session handler
│   │   ├── customer-portal/   # Customer portal redirect
│   │   └── webhook/           # Webhook event handler
│   ├── components/
│   │   ├── Footer.tsx         # Reusable footer
│   │   ├── Header.tsx         # Navigation header
│   │   └── ProductCard.tsx    # Product pricing card
│   ├── globals.css            # Global styles
│   ├── layout.tsx             # Root layout
│   └── page.tsx               # Pricing page (home)
└── lib/
    └── products.ts            # Product definitions
```

## 自定义

### 更新产品信息

编辑 `src/lib/products.ts` 以更改：

* 产品 ID，来自 Dodo Payments 控制面板中的 **Products**
* 价格
* 功能
* 描述

### 预填充客户数据

`src/app/components/ProductCard.tsx` 会在每个结账请求中发送硬编码的姓名和电子邮件。将其替换为已登录用户的信息：

```typescript theme={null}
customer: {
  name: "John Doe",
  email: "john@example.com",
},
```

### 更新 Customer Portal

`src/app/components/Header.tsx` 中的 **Customer Portal** 链接会打开 `/api/customer-portal`，并使用硬编码的客户 ID。将其替换为已登录用户的 Dodo Payments 客户 ID：

```typescript theme={null}
const CUSTOMER_ID = "cus_001"; // Replace with actual customer ID
```

如需获取用于测试的客户 ID，请完成一次测试购买，然后从控制面板的 **Customers** 中复制客户 ID。在生产环境中，请从后端获取该 ID。

## Webhook 事件

`src/app/api/webhook/route.ts` 中的处理程序会使用 `DODO_PAYMENTS_WEBHOOK_KEY` 验证每个请求，然后处理两个事件：

* `onSubscriptionActive` 在订阅变为活跃状态时运行（`subscription.active`）。
* `onPaymentSucceeded` 在支付成功时运行（`payment.succeeded`）。

在这些处理程序中添加你的业务逻辑：

```typescript theme={null}
onSubscriptionActive: async (payload) => {
  // Grant access to your product
  // Update user database
  // Send welcome email
},
```

如需处理更多事件，请添加相应的处理程序，例如 `onSubscriptionCancelled`。[Next.js Adaptor](/developer-resources/nextjs-adaptor#supported-webhook-event-handlers) 列出了所有受支持的处理程序。

Dodo Payments 无法访问 `localhost`。进行本地开发时，请使用 [ngrok](https://ngrok.com/) 等隧道工具公开本地服务器，并将隧道 URL 用作 webhook 端点。

## 部署

### 构建生产版本

```bash theme={null}
npm run build
npm start
```

### 部署到 Vercel

\[

![使用 Vercel 部署](https://vercel.com/button)

]\([https://vercel.com/new/clone?repository-url=https://github.com/dodopayments/dodo-nextjs-minimal-boilerplate](https://vercel.com/new/clone?repository-url=https://github.com/dodopayments/dodo-nextjs-minimal-boilerplate))

在 Vercel 控制面板中添加四个环境变量，并将 `DODO_PAYMENTS_RETURN_URL` 设置为你的生产 URL。

### 更新 Webhook URL

部署后，在 [Dodo Payments Dashboard](https://app.dodopayments.com/developer/webhooks) 中添加生产 webhook URL，将 `example.com` 替换为你的域名：

```text theme={null}
https://example.com/api/webhook
```

每个端点都有自己的签名密钥。将新端点的密钥复制到生产环境中的 `DODO_PAYMENTS_WEBHOOK_KEY`。

## 故障排除

> **Module not found or build errors**
>
> 删除 `node_modules` 和 `package-lock.json`，然后重新安装依赖：
>
> ```bash theme={null}
> rm -rf node_modules package-lock.json
> npm install
> ```

> **Checkout redirect fails**
>
> 检查以下常见原因：
>
> * 产品 ID 在你的 Dodo Payments 控制面板中不存在。
> * `.env` 中的 API 密钥或 `DODO_PAYMENTS_ENVIRONMENT` 不正确。测试模式密钥只能与 `test_mode` 配合使用。
>
> 在浏览器控制台以及运行 `npm run dev` 的终端中查找错误。

> **Webhooks not receiving events**
>
> 进行本地测试时，使用 [ngrok](https://ngrok.com) 暴露你的服务器：
>
> ```bash theme={null}
> ngrok http 3000
> ```
>
> 在你的 [Dodo dashboard](https://app.dodopayments.com/developer/webhooks) 中，添加一个端点，其 URL 为 ngrok HTTPS URL 后接 `/api/webhook`。将该端点的签名密钥复制到 `.env` 文件中的 `DODO_PAYMENTS_WEBHOOK_KEY`。

> **Customer portal link doesn't work**
>
> 将 `src/app/components/Header.tsx` 中硬编码的 `CUSTOMER_ID` 替换为 Dodo Payments 控制面板中某个客户的 ID。
>
> 在生产环境中，请改为从身份验证系统和数据库获取客户 ID。

## 了解更多

* [Dodo Payments 文档](https://docs.dodopayments.com/)
* [Checkout Sessions 文档](https://docs.dodopayments.com/developer-resources/checkout-session)
* [Webhooks 文档](https://docs.dodopayments.com/developer-resources/webhooks)
* [Next.js Adaptor](/developer-resources/nextjs-adaptor)：`Checkout`、`CustomerPortal` 和 `Webhooks` 处理程序的选项

## 支持

如需样板帮助：

* 在 [Discord 社区](https://discord.gg/bYqAp4ayYh)中提问。
* 在 [GitHub 代码库](https://github.com/dodopayments/dodo-nextjs-minimal-boilerplate)中报告问题并关注更新。
* 发送电子邮件至 [支持团队](mailto:support@dodopayments.com)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.