# Webhook 部署方案

由于 Gitea Runner 容器环境限制，采用更简单可靠的 Webhook 方式触发部署。

## 🚀 配置步骤

### 第一步：在服务器上配置部署脚本

SSH 登录服务器后执行：

```bash
# 1. 克隆代码（如果还没有）
cd /www/dk_project/dk_app
git clone https://gitea.pinzhuhui.com/xiaoquan/rent.git
cd rent

# 2. 配置 Git 凭证
git config credential.helper store
git pull origin test  # 输入用户名和 Gitea Token

# 3. 赋予部署脚本执行权限
chmod +x deploy/scripts/deploy.sh

# 4. 创建环境变量文件
cat > /root/.env.test << 'EOF'
export TEST_DB_PASSWORD="your_password"
export TEST_JWT_SECRET="your_jwt_secret"
export ENCRYPTION_KEY="your_encryption_key"
EOF

cat > /root/.env.prod << 'EOF'
export PROD_DB_PASSWORD="your_password"
export PROD_JWT_SECRET="your_jwt_secret"
export ENCRYPTION_KEY="your_encryption_key"
EOF

# 5. 测试部署脚本
/www/dk_project/dk_app/rent/deploy/scripts/deploy.sh test
```

### 第二步：配置 Webhook 服务

#### 方法1：使用 webhook (推荐)

```bash
# 安装 webhook
cd /root
wget https://github.com/adnanh/webhook/releases/download/2.8.1/webhook-linux-amd64.tar.gz
tar -xzf webhook-linux-amd64.tar.gz
mv webhook-linux-amd64/webhook /usr/local/bin/
chmod +x /usr/local/bin/webhook

# 创建 webhook 配置
mkdir -p /root/webhooks
cat > /root/webhooks/hooks.json << 'EOF'
[
  {
    "id": "rent-deploy-test",
    "execute-command": "/www/dk_project/dk_app/rent/deploy/scripts/deploy.sh",
    "command-working-directory": "/www/dk_project/dk_app/rent",
    "pass-arguments-to-command": [
      {
        "source": "string",
        "name": "test"
      }
    ],
    "trigger-rule": {
      "and": [
        {
          "match": {
            "type": "payload-hash-sha256",
            "secret": "your-webhook-secret",
            "parameter": {
              "source": "header",
              "name": "X-Gitea-Signature"
            }
          }
        },
        {
          "match": {
            "type": "value",
            "value": "refs/heads/test",
            "parameter": {
              "source": "payload",
              "name": "ref"
            }
          }
        }
      ]
    }
  },
  {
    "id": "rent-deploy-prod",
    "execute-command": "/www/dk_project/dk_app/rent/deploy/scripts/deploy.sh",
    "command-working-directory": "/www/dk_project/dk_app/rent",
    "pass-arguments-to-command": [
      {
        "source": "string",
        "name": "prod"
      }
    ],
    "trigger-rule": {
      "and": [
        {
          "match": {
            "type": "payload-hash-sha256",
            "secret": "your-webhook-secret",
            "parameter": {
              "source": "header",
              "name": "X-Gitea-Signature"
            }
          }
        },
        {
          "match": {
            "type": "value",
            "value": "refs/heads/prod",
            "parameter": {
              "source": "payload",
              "name": "ref"
            }
          }
        }
      ]
    }
  }
]
EOF

# 启动 webhook 服务
nohup webhook -hooks /root/webhooks/hooks.json -verbose -port 9000 > /root/webhooks/webhook.log 2>&1 &

# 设置开机自启
cat > /etc/systemd/system/webhook.service << 'EOF'
[Unit]
Description=Webhook Service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/webhook -hooks /root/webhooks/hooks.json -verbose -port 9000
Restart=always

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable webhook
systemctl start webhook
```

#### 方法2：使用简单的 PHP 脚本（如果有宝塔面板）

在宝塔面板创建一个站点，添加 `webhook.php`：

```php
<?php
// webhook.php
$secret = 'your-webhook-secret';
$branch = $_POST['ref'] ?? '';

// 验证签名
$signature = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? '';
$payload = file_get_contents('php://input');
$expected = hash_hmac('sha256', $payload, $secret);

if (!hash_equals($expected, $signature)) {
    http_response_code(403);
    die('Invalid signature');
}

// 执行部署
if ($branch === 'refs/heads/test') {
    $output = shell_exec('/www/dk_project/dk_app/rent/deploy/scripts/deploy.sh test 2>&1');
} elseif ($branch === 'refs/heads/prod') {
    $output = shell_exec('/www/dk_project/dk_app/rent/deploy/scripts/deploy.sh prod 2>&1');
} else {
    http_response_code(400);
    die('Unknown branch');
}

echo $output;
?>
```

### 第三步：在 Gitea 中配置 Webhook

1. 登录 Gitea
2. 进入仓库 → Settings → Webhooks
3. 点击 "添加 Webhook" → "Gitea"
4. 配置：
   - **目标 URL**: 
     - webhook 方式：`http://your-server:9000/hooks/rent-deploy-test`
     - PHP 方式：`http://your-server/webhook.php`
   - **HTTP 方法**: POST
   - **POST Content Type**: application/json
   - **密钥**: `your-webhook-secret`（与上面配置的一致）
   - **触发条件**: 勾选 "推送事件"
   - **分支过滤**: `test` 或 `prod`
5. 点击 "添加 Webhook"
6. 点击 "测试推送" 验证

---

## 🔄 工作流程

```
1. git push origin test
   ↓
2. Gitea 触发 Webhook
   ↓
3. Webhook 服务调用 deploy.sh
   ↓
4. 脚本自动：
   - git pull 更新代码
   - docker-compose build 构建
   - docker-compose up 部署
   ↓
5. 完成！
```

---

## 🔍 查看日志

### webhook 方式
```bash
tail -f /root/webhooks/webhook.log
```

### 手动测试
```bash
/www/dk_project/dk_app/rent/deploy/scripts/deploy.sh test
```

---

## ✅ 优点

- ✅ 不依赖 Runner 容器
- ✅ 直接在宿主机执行
- ✅ 简单可靠
- ✅ 容易调试

---

**维护者**：开发团队  
**最后更新**：2026-06-10
