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

# Go Boilerplate

> 快速开始使用我们的最小 Go boilerplate，将 Dodo Payments 集成到您的 Go 后端应用程序中

<Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/go-boilerplate">
  精简的 Go + Dodo Payments 样板
</Card>

## 概述

Go boilerplate 提供了一个生产就绪的起点，用于将 Dodo Payments 集成到您的 Go 后端中。此模板包括结账会话处理、Webhook 验证、客户门户集成，并遵循 Go 最佳实践，帮助您快速开始接受支付。

<Info>
  该样板使用 Go 1.21+ 并采用清晰的架构模式（`cmd`、`internal`、`templates`）、HTML 模板，以及 `dodopayments-go` SDK 实现无缝的 API 集成。
</Info>

### 特性

* **快速设置** - 在 5 分钟内开始
* **支付集成** - 使用 `dodopayments-go` SDK 的预配置结账流程
* **现代 UI** - 使用 HTML 模板的清爽暗色主题定价页面
* **Webhook 处理** - 安全地验证并处理支付事件
* **客户门户** - 自助订阅管理
* **Go 最佳实践** - 采用 `cmd`、`internal` 和 `templates` 的清晰架构
* **预填写结账** - 展示如何传递客户数据以提升体验

## 先决条件

在开始之前，请确保您拥有：

* **Go 1.21+**
* **Dodo Payments 账户**（以从仪表板访问 API 和 Webhook 密钥）

## 快速开始

<Steps>
  <Step title="Clone the Repository">
    ```bash theme={null}
    git clone https://github.com/dodopayments/go-boilerplate.git
    cd go-boilerplate
    ```
  </Step>

  <Step title="Install Dependencies">
    ```bash theme={null}
    make install
    ```

    或者手动：

    ```bash theme={null}
    go mod download
    ```
  </Step>

  <Step title="Get API Credentials">
    在 [Dodo Payments](https://dodopayments.com/) 注册，并从仪表板获取凭证：

    * **API 密钥：** [仪表板 → 开发者 → API 密钥](https://app.dodopayments.com/developer/api-keys)
    * **Webhook 密钥：** [仪表板 → 开发者 → Webhooks](https://app.dodopayments.com/developer/webhooks)

    <Tip>
      开发时确保处于 **测试模式**！
    </Tip>
  </Step>

  <Step title="Configure Environment Variables">
    在根目录创建一个 `.env` 文件：

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

    使用您的 Dodo Payments 凭证更新值：

    ```bash .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:8000
    DODO_PAYMENTS_ENVIRONMENT=test_mode
    ```

    <Warning>
      永远不要将你的 `.env` 文件提交到版本控制。它已经包含在 `.gitignore` 中。
    </Warning>
  </Step>

  <Step title="Add Your Products">
    用 Dodo Payments 中的实际产品 ID 更新 `internal/lib/products.go`：

    ```go theme={null}
    var Products = []Product{
        {
            ProductID:   "pdt_001", // Replace with your product ID
            Name:        "Basic Plan",
            Description: "Get access to basic features and support",
            Price:       9999, // in cents
            Features: []string{
                "Access to basic features",
                "Email support",
                "1 Team member",
                "Basic analytics",
            },
        },
        // ... add more products
    }
    ```
  </Step>

  <Step title="Run the Development Server">
    ```bash theme={null}
    make run
    ```

    或者手动：

    ```bash theme={null}
    go run cmd/server/main.go
    ```

    打开 [http://localhost:8000](http://localhost:8000) 查看您的定价页面！

    <Check>
      你应该能看到一个暗色主题的定价页面，产品已准备好购买。
    </Check>
  </Step>
</Steps>

## 项目结构

```text theme={null}
go-boilerplate/
├── cmd/
│   └── server/             # Application entry point
├── internal/
│   ├── api/                # API handlers (Checkout, Portal, Webhook)
│   ├── core/               # Configuration and system core
│   └── lib/                # Shared logic (Products, Customer utils)
├── templates/              # HTML templates
├── Makefile                # Build and run commands
├── go.mod                  # Go module definition
├── go.sum                  # Dependency checksums
├── .env.example            # Environment template
└── README.md
```

## API 端点

该 boilerplate 包含以下预配置的端点：

| 端点                     | 方法   | 描述                         |
| ---------------------- | ---- | -------------------------- |
| `/`                    | GET  | 显示产品列表的定价页面                |
| `/api/checkout`        | POST | 创建新的结账会话                   |
| `/api/webhook`         | POST | 处理 Dodo Payments 的 webhook |
| `/api/customer-portal` | POST | 生成客户门户 URL                 |

## 自定义

### 更新产品信息

编辑 `internal/lib/products.go` 以修改：

* 产品 ID（来自你的 Dodo 仪表板）
* 定价
* 功能
* 描述

```go theme={null}
var Products = []Product{
    {
        ProductID:   "pdt_001", // Replace with your product ID
        Name:        "Basic Plan",
        Description: "Get access to basic features and support",
        Price:       9999,
        Features: []string{
            "Access to basic features",
            "Email support",
            "1 Team member",
            "Basic analytics",
        },
    },
}
```

### 预填客户数据

在 `templates/index.html` 中，用你的实际用户数据替换硬编码的客户数据：

```javascript theme={null}
const customerData = {
    name: "John Doe",       // Replace with actual logged-in user's name
    email: "john@example.com"  // Replace with actual logged-in user's email
};
```

在生产应用中，您将动态注入这些值来自您的身份验证系统。

## Webhook 事件

该样板展示了如何在 `internal/api/webhook.go` 中处理 webhook 事件。支持的事件包括：

| 事件                    | 描述         |
| --------------------- | ---------- |
| `subscription.active` | 在订阅变为激活时触发 |
| `payment.succeeded`   | 在付款成功时触发   |

在 webhook 处理程序中添加您的业务逻辑，以：

* 更新数据库中的用户权限
* 发送确认电子邮件
* 提供对数字产品的访问
* 跟踪分析和指标

## 本地测试 Webhooks

对于本地开发，使用 [ngrok](https://ngrok.com/) 来暴露您的本地服务器：

```bash theme={null}
ngrok http 8000
```

在您的 [Dodo Payments 仪表板](https://app.dodopayments.com/developer/webhooks) 中更新 webhook URL：

```
https://your-ngrok-url.ngrok.io/api/webhook
```

## 部署

### 为生产构建

```bash theme={null}
make build
```

或者手动：

```bash theme={null}
go build -o bin/server cmd/server/main.go
./bin/server
```

### 部署到 Vercel

\[

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

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

### Docker

创建一个 `Dockerfile`：

```dockerfile theme={null}
FROM golang:1.21-alpine AS builder

WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download

COPY . .
RUN go build -o bin/server cmd/server/main.go

FROM alpine:latest
WORKDIR /app
COPY --from=builder /app/bin/server .
COPY --from=builder /app/templates ./templates

EXPOSE 8000
CMD ["./server"]
```

构建并运行：

```bash theme={null}
docker build -t go-dodo .
docker run -p 8000:8000 --env-file .env go-dodo
```

### 生产注意事项

<Warning>
  部署到生产环境前：

  * 将 `DODO_PAYMENTS_ENVIRONMENT` 切换为 `live_mode`
  * 使用仪表板中的生产 API 密钥
  * 将 webhook URL 更新为你的生产域名
  * 为所有端点启用 HTTPS
</Warning>

## 故障排除

<AccordionGroup>
  <Accordion title="Build errors or missing dependencies">
    确保 Go 模块已正确下载：

    ```bash theme={null}
    go mod tidy
    go mod download
    ```
  </Accordion>

  <Accordion title="Checkout session creation fails">
    **常见原因：**

    * 无效的产品 ID － 确认它在你的 Dodo 仪表板中存在
    * `.env` 中的 API 密钥或环境设置错误
    * 检查服务器日志以获取详细错误信息
  </Accordion>

  <Accordion title="Webhooks not receiving events">
    本地测试时，使用 [ngrok](https://ngrok.com) 将你的服务器暴露出来：

    ```bash theme={null}
    ngrok http 8000
    ```

    在你的 [Dodo 仪表板](https://app.dodopayments.com/developer/webhooks) 中将 webhook URL 更新为 ngrok URL。确保在 `.env` 文件中更新正确的 webhook 验证密钥。
  </Accordion>

  <Accordion title="Templates not loading">
    确保你从项目根目录运行服务器，或者在代码中正确配置了模板路径。
  </Accordion>
</AccordionGroup>

## 了解更多

<CardGroup cols={2}>
  <Card title="Go SDK" icon="golang" href="/developer-resources/sdks/go">
    完整的 Go SDK 文档
  </Card>

  <Card title="Webhooks Documentation" icon="webhook" href="/developer-resources/webhooks">
    了解所有 webhook 事件和最佳实践
  </Card>

  <Card title="Checkout Sessions" icon="credit-card" href="/developer-resources/checkout-session">
    深入了解结账会话配置
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    完整的 Dodo Payments API 文档
  </Card>
</CardGroup>

## 支持

需要有关 boilerplate 的帮助吗？

* 加入我们的 [Discord 社区](https://discord.gg/bYqAp4ayYh) 进行提问和讨论
* 查看 [GitHub 仓库](https://github.com/dodopayments/go-boilerplate) 以获取问题和更新
* 联系我们的 [支持团队](mailto:support@dodopayments.com) 寻求帮助
