# 积分充值系统 - 快速启动

## 🚀 5分钟快速上手

### 1️⃣ 执行数据库迁移

```bash
mysql -u root -p 1818ai < V6__add_points_recharge_system.sql
```

**验证**：
```sql
-- 检查套餐数据
SELECT name, points, bonus_points, total_points, price FROM points_package;
-- 应该看到6个套餐

-- 检查order表新字段
DESC `order`;
-- 应该包含 order_type, points_package_id, points_amount
```

---

### 2️⃣ 启动应用

```bash
mvn spring-boot:run
```

或者

```bash
mvn clean package
java -jar target/1818_user_server-0.0.1-SNAPSHOT.jar
```

---

### 3️⃣ 测试接口

#### 步骤1：获取套餐列表（无需登录）

```bash
curl -X GET "http://localhost:8080/user/points/packages"
```

**预期响应**：
```json
{
  "code": 200,
  "data": [
    {
      "id": 1,
      "name": "体验包",
      "points": 100,
      "price": 10.00,
      ...
    }
  ]
}
```

---

#### 步骤2：用户登录获取Token

```bash
curl -X POST "http://localhost:8080/user/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"phone":"13800138000","password":"123456"}'
```

**获取token**：
```json
{
  "code": 200,
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}
```

---

#### 步骤3：创建充值订单（需要登录）

```bash
curl -X POST "http://localhost:8080/user/points/recharge" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -d '{"packageId":2,"paymentMethod":2}'
```

**预期响应**：
```json
{
  "code": 200,
  "data": {
    "orderNo": "ORD20251021123456",
    "amount": 48.00,
    "pointsAmount": 605,
    "paymentMethod": 2
  }
}
```

**注意**：
- `pointsAmount` 可能是 605（500基础+50赠送+55首充奖励）
- 如果是首次充值，会有10%的额外奖励

---

#### 步骤4：模拟支付成功（测试用）

```bash
curl -X POST "http://localhost:8080/payment/callback/test?orderNo=ORD20251021123456"
```

**预期响应**：`success`

---

#### 步骤5：查看用户积分

```bash
curl -X GET "http://localhost:8080/user/info" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
```

**验证积分是否到账**：
```json
{
  "code": 200,
  "data": {
    "points": 605,
    "pointsExpiresAt": "2026-10-21T12:35:10"
  }
}
```

---

#### 步骤6：查看充值记录

```bash
curl -X GET "http://localhost:8080/user/points/recharge/records?page=1&size=10" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
```

---

## 📝 前端快速集成

### HTML示例

```html
<!DOCTYPE html>
<html>
<head>
    <title>积分充值</title>
</head>
<body>
    <h1>积分充值</h1>
    
    <!-- 套餐列表 -->
    <div id="packages"></div>
    
    <script>
        const API_BASE = 'http://localhost:8080';
        const token = localStorage.getItem('token'); // 从登录获取
        
        // 1. 加载套餐列表
        async function loadPackages() {
            const res = await fetch(`${API_BASE}/user/points/packages`);
            const result = await res.json();
            
            if (result.code === 200) {
                const html = result.data.map(pkg => `
                    <div class="package">
                        <h3>${pkg.name}</h3>
                        <p>${pkg.description}</p>
                        <p>基础积分：${pkg.points}</p>
                        <p>赠送积分：${pkg.bonusPoints}</p>
                        <p>总计：${pkg.totalPoints}积分</p>
                        <p class="price">¥${pkg.price}</p>
                        <button onclick="recharge(${pkg.id}, 2)">
                            微信支付
                        </button>
                    </div>
                `).join('');
                
                document.getElementById('packages').innerHTML = html;
            }
        }
        
        // 2. 创建充值订单
        async function recharge(packageId, paymentMethod) {
            const res = await fetch(`${API_BASE}/user/points/recharge`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    packageId: packageId,
                    paymentMethod: paymentMethod
                })
            });
            
            const result = await res.json();
            
            if (result.code === 200) {
                const { orderNo, paymentParams } = result.data;
                console.log('订单创建成功：', orderNo);
                
                // TODO: 调起真实支付
                // 这里暂时调用测试回调
                testPay(orderNo);
            } else {
                alert(result.message);
            }
        }
        
        // 3. 测试支付（仅开发环境）
        async function testPay(orderNo) {
            const res = await fetch(
                `${API_BASE}/payment/callback/test?orderNo=${orderNo}`,
                { method: 'POST' }
            );
            
            if (await res.text() === 'success') {
                alert('充值成功！');
                location.reload();
            }
        }
        
        // 页面加载时获取套餐
        loadPackages();
    </script>
</body>
</html>
```

---

## 🔐 Swagger测试

访问：`http://localhost:8080/doc.html`

### 测试步骤：

1. **获取套餐** → `GET /user/points/packages`
2. **用户登录** → `POST /user/auth/login` → 获取token
3. **点击右上角🔑图标** → 输入 `Bearer YOUR_TOKEN`
4. **创建充值订单** → `POST /user/points/recharge`
5. **测试支付回调** → `POST /payment/callback/test`
6. **查看充值记录** → `GET /user/points/recharge/records`

---

## ✅ 完成检查清单

- [ ] 数据库迁移成功（6个套餐）
- [ ] 能够获取套餐列表
- [ ] 能够创建充值订单
- [ ] 测试支付回调成功
- [ ] 用户积分正确到账
- [ ] 充值记录正常显示
- [ ] 首充奖励正确计算

---

## 🎉 成功！

现在用户可以：
- ✅ 浏览积分套餐
- ✅ 选择支付方式充值
- ✅ 查看充值历史
- ✅ 享受首充奖励

**下一步**：对接真实的支付宝/微信支付接口

详细文档请查看：`POINTS_RECHARGE_GUIDE.md`

