From 262ce70998fa52dec3120589f51c47e96fb96df4 Mon Sep 17 00:00:00 2001
From: 905086 <k2049@qq.com>
Date: Tue, 03 Nov 2026 17:04:19 +0800
Subject: [PATCH] feat: 完成游戏盒子前后端基础功能开发

---
 server/handlers/keys.go |   76 ++++++++++++++++++++++++++++++++++++++
 1 files changed, 76 insertions(+), 0 deletions(-)

diff --git a/server/handlers/keys.go b/server/handlers/keys.go
new file mode 100644
index 0000000..fceea00
--- /dev/null
+++ b/server/handlers/keys.go
@@ -0,0 +1,76 @@
+package handlers
+
+import (
+	"net/http"
+	"time"
+
+	"gamebox-server/config"
+	"gamebox-server/models"
+
+	"github.com/gin-gonic/gin"
+)
+
+func cardDuration(cardType string) time.Duration {
+	switch cardType {
+	case "day":
+		return 24 * time.Hour
+	case "month":
+		return 30 * 24 * time.Hour
+	case "year":
+		return 365 * 24 * time.Hour
+	}
+	return 0
+}
+
+// ActivateKey 激活会员密钥(绑定机器)
+func ActivateKey(c *gin.Context) {
+	userID := c.GetUint("user_id")
+	var req struct {
+		Code        string `json:"code"`
+		MachineCode string `json:"machine_code"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil || req.Code == "" {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "请输入激活码"})
+		return
+	}
+	if req.MachineCode == "" {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "获取机器码失败"})
+		return
+	}
+	var key models.MemberKey
+	if err := config.DB.Where("code = ?", req.Code).First(&key).Error; err != nil {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "激活码不存在,请检查后重新输入"})
+		return
+	}
+
+	now := time.Now()
+	if key.Status == 0 {
+		// 未使用,直接激活
+		expired := now.Add(cardDuration(key.CardType))
+		config.DB.Model(&key).Updates(map[string]interface{}{
+			"status":       1,
+			"user_id":      userID,
+			"machine_code": req.MachineCode,
+			"activated_at": now,
+			"expired_at":   expired,
+		})
+		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "激活成功!", "data": gin.H{
+			"expire_at": expired.Format("2006-01-02 15:04:05"),
+		}})
+		return
+	}
+
+	// 已使用的密钥
+	if key.MachineCode != req.MachineCode {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该激活码已在其他电脑上使用,无法在此设备激活!"})
+		return
+	}
+	if key.ExpiredAt != nil && key.ExpiredAt.Before(now) {
+		c.JSON(http.StatusOK, gin.H{"code": 1, "msg": "该激活码已过期,请使用新的激活码!"})
+		return
+	}
+	// 同机器重复激活,返回当前有效期
+	c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "该激活码已在此设备激活", "data": gin.H{
+		"expire_at": key.ExpiredAt.Format("2006-01-02 15:04:05"),
+	}})
+}

--
Gitblit v1.10.0