feat(iap/apple): 实现苹果IAP非续期订阅功能
Build docker and publish / build (20.15.1) (push) Successful in 6m37s

新增苹果IAP相关接口与逻辑,包括产品列表查询、交易绑定、状态查询和恢复购买功能。移除旧的IAP验证逻辑,重构订阅系统以支持苹果IAP交易记录存储和权益计算。

- 新增/pkg/iap/apple包处理JWS解析和产品映射
- 实现GET /products、POST /attach、POST /restore和GET /status接口
- 新增apple_iap_transactions表存储交易记录
- 更新文档说明配置方式和接口规范
- 移除旧的AppleIAP验证和通知处理逻辑
This commit is contained in:
2025-12-13 20:54:50 -08:00
parent a80d6af035
commit 62186ca672
41 changed files with 1715 additions and 474 deletions
@@ -1,20 +1,13 @@
package notify
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/notify"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/result"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/result"
)
// AppleIAPNotifyHandler 处理 Apple Server Notifications v2
// 参数: 原始 HTTP 请求体
// 返回: 处理结果(空体 200
func AppleIAPNotifyHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
l := notify.NewAppleIAPNotifyLogic(c.Request.Context(), svcCtx)
err := l.Handle(c.Request)
result.HttpResult(c, gin.H{"success": err == nil}, err)
}
return func(c *gin.Context) {
result.HttpResult(c, map[string]bool{"success": true}, nil)
}
}
@@ -0,0 +1,24 @@
package apple
import (
"github.com/gin-gonic/gin"
appleLogic "github.com/perfect-panel/server/internal/logic/public/iap/apple"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func AttachAppleTransactionHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.AttachAppleTransactionRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := appleLogic.NewAttachTransactionLogic(c.Request.Context(), svcCtx)
resp, err := l.Attach(&req)
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,219 @@
package apple
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/config"
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
submodel "github.com/perfect-panel/server/internal/model/subscribe"
usermodel "github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/constant"
"github.com/redis/go-redis/v9"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// TestIAPAttachFlow 覆盖完整一次用户购买绑定的接口流程
// 步骤:初始化内存DB+Redis → 配置产品映射 → 创建用户与订阅计划 → 调用attach接口 → 断言返回与落库
func TestIAPAttachFlow(t *testing.T) {
gin.SetMode(gin.TestMode)
// sqlite 内存数据库
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatalf("open sqlite error: %v", err)
}
if err := db.AutoMigrate(
&usermodel.User{},
&iapmodel.Transaction{},
); err != nil {
t.Fatalf("automigrate error: %v", err)
}
// sqlite 手工创建 subscribe 与 user_subscribe 表,避免不兼容的默认值语法
if err := db.Exec(`
CREATE TABLE IF NOT EXISTS subscribe (
id INTEGER PRIMARY KEY,
name TEXT,
language TEXT,
description TEXT,
unit_price INTEGER,
unit_time TEXT,
discount TEXT,
replacement INTEGER,
inventory INTEGER,
traffic INTEGER,
speed_limit INTEGER,
device_limit INTEGER,
quota INTEGER,
nodes TEXT,
node_tags TEXT,
show INTEGER,
sell INTEGER,
sort INTEGER,
deduction_ratio INTEGER,
allow_deduction INTEGER,
reset_cycle INTEGER,
renewal_reset INTEGER,
created_at DATETIME,
updated_at DATETIME
);
`).Error; err != nil {
t.Fatalf("create subscribe table error: %v", err)
}
if err := db.Exec(`
CREATE TABLE IF NOT EXISTS user_subscribe (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
order_id INTEGER,
subscribe_id INTEGER NOT NULL,
start_time DATETIME,
expire_time DATETIME,
finished_at DATETIME,
traffic INTEGER DEFAULT 0,
download INTEGER DEFAULT 0,
upload INTEGER DEFAULT 0,
token TEXT UNIQUE,
uuid TEXT UNIQUE,
status INTEGER DEFAULT 0,
created_at DATETIME,
updated_at DATETIME
);
`).Error; err != nil {
t.Fatalf("create user_subscribe table error: %v", err)
}
// 内嵌 Redis
mr, err := miniredis.Run()
if err != nil {
t.Fatalf("start miniredis error: %v", err)
}
defer mr.Close()
rds := redis.NewClient(&redis.Options{Addr: mr.Addr()})
// 配置 IAP 产品映射
cd := `{
"iapProductMap": {
"com.airport.vpn.pass.30d": {
"description": "30天通行证",
"priceText": "¥28.00",
"durationDays": 30,
"tier": "Basic",
"subscribeId": 1001
}
},
"iapBundleId": "co.airoport.app.ios"
}`
s := &svc.ServiceContext{
DB: db,
Redis: rds,
Config: config.Config{
Site: config.SiteConfig{
CustomData: cd,
},
},
}
// 初始化模型(与生产保持一致)
s.UserModel = usermodel.NewModel(db, rds)
s.SubscribeModel = submodel.NewModel(db, rds)
s.IAPAppleTransactionModel = iapmodel.NewModel(db, rds)
// 创建可售订阅计划(ID=1001)
truePtr := func(b bool) *bool { return &b }
if err := db.Create(&submodel.Subscribe{
Id: 1001,
Name: "30D Pass",
Sell: truePtr(true),
Language: "",
}).Error; err != nil {
t.Fatalf("create subscribe plan error: %v", err)
}
// 创建用户
u := &usermodel.User{
Id: 1,
Password: "",
Avatar: "",
Balance: 0,
Commission: 0,
ReferralPercentage: 0,
OnlyFirstPurchase: truePtr(true),
Enable: truePtr(true),
IsAdmin: truePtr(false),
EnableBalanceNotify: truePtr(false),
EnableLoginNotify: truePtr(false),
EnableSubscribeNotify: truePtr(true),
EnableTradeNotify: truePtr(false),
}
if err := db.Create(u).Error; err != nil {
t.Fatalf("create user error: %v", err)
}
// 构造最小 JWS(仅解析 payload
payload := map[string]interface{}{
"bundleId": "co.airoport.app.ios",
"productId": "com.airport.vpn.pass.unknown",
"transactionId": "1000000000001",
"originalTransactionId": "1000000000000",
"purchaseDate": float64(time.Now().UnixMilli()),
}
data, _ := json.Marshal(payload)
b64 := base64.RawURLEncoding.EncodeToString(data)
jws := "header." + b64 + ".signature"
// 组装路由(仅挂载 attach
r := gin.New()
r.POST("/v1/public/iap/apple/transactions/attach", AttachAppleTransactionHandler(s))
// 请求上下文注入登录用户
type attachReq struct {
SignedTransactionJWS string `json:"signed_transaction_jws"`
DurationDays int64 `json:"duration_days"`
Tier string `json:"tier"`
SubscribeId int64 `json:"subscribe_id"`
}
body := attachReq{SignedTransactionJWS: jws, DurationDays: 30, Tier: "Basic", SubscribeId: 1001}
bodyBytes, _ := json.Marshal(body)
req, _ := http.NewRequest(http.MethodPost, "/v1/public/iap/apple/transactions/attach", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
ctx := context.WithValue(req.Context(), constant.CtxKeyUser, u)
req = req.WithContext(ctx)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("attach status != 200, got %d", w.Code)
}
// 解析响应包装
var wrap struct {
Code uint32 `json:"code"`
Msg string `json:"msg"`
Data struct {
ExpiresAt int64 `json:"expires_at"`
Tier string `json:"tier"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &wrap); err != nil {
t.Fatalf("unmarshal attach resp error: %v", err)
}
if wrap.Code != 200 {
t.Fatalf("attach code != 200, got %d, msg=%s", wrap.Code, wrap.Msg)
}
if wrap.Data.ExpiresAt <= time.Now().Unix() {
t.Fatalf("expires_at invalid: %d", wrap.Data.ExpiresAt)
}
// 校验 user_subscribe 落库
var count int64
if err := db.Model(&usermodel.Subscribe{}).Where("user_id = ? AND subscribe_id = ?", u.Id, 1001).Count(&count).Error; err != nil {
t.Fatalf("query user_subscribe error: %v", err)
}
if count == 0 {
t.Fatalf("user_subscribe not inserted")
}
}
@@ -0,0 +1,17 @@
package apple
import (
"github.com/gin-gonic/gin"
appleLogic "github.com/perfect-panel/server/internal/logic/public/iap/apple"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/result"
)
func GetAppleProductsHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
l := appleLogic.NewGetProductsLogic(c.Request.Context(), svcCtx)
resp, err := l.GetProducts()
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,72 @@
package apple
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/config"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
)
// TestGetAppleProductsHandler 用于验证产品列表接口
// 参数:无
// 返回:无;断言接口返回的产品数量与字段正确性
func TestGetAppleProductsHandler(t *testing.T) {
gin.SetMode(gin.TestMode)
cd := `{
"iapProductMap": {
"com.airport.vpn.pass.30d": {
"description": "30天通行证",
"priceText": "¥28.00",
"durationDays": 30,
"tier": "Basic",
"subscribeId": 1001
},
"com.airport.vpn.pass.90d": {
"description": "90天通行证",
"priceText": "¥68.00",
"durationDays": 90,
"tier": "Pro",
"subscribeId": 1002
}
},
"iapBundleId": "co.airoport.app.ios"
}`
s := &svc.ServiceContext{
Config: config.Config{
Site: config.SiteConfig{
CustomData: cd,
},
},
}
r := gin.New()
r.GET("/v1/public/iap/apple/products", GetAppleProductsHandler(s))
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/v1/public/iap/apple/products", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status != 200, got %d", w.Code)
}
type wrap struct {
Code uint32 `json:"code"`
Msg string `json:"msg"`
Data types.GetAppleProductsResponse `json:"data"`
}
var resp wrap
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal error: %v", err)
}
if resp.Code != 200 {
t.Fatalf("code != 200, got %d", resp.Code)
}
if len(resp.Data.List) != 2 {
t.Fatalf("expect 2 products, got %d", len(resp.Data.List))
}
if resp.Data.List[0].ProductId == "" || resp.Data.List[0].DurationDays == 0 || resp.Data.List[0].SubscribeId == 0 {
t.Fatalf("invalid fields in product item")
}
}
@@ -0,0 +1,17 @@
package apple
import (
"github.com/gin-gonic/gin"
appleLogic "github.com/perfect-panel/server/internal/logic/public/iap/apple"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/result"
)
func GetAppleStatusHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
l := appleLogic.NewGetStatusLogic(c.Request.Context(), svcCtx)
resp, err := l.GetStatus()
result.HttpResult(c, resp, err)
}
}
@@ -0,0 +1,24 @@
package apple
import (
"github.com/gin-gonic/gin"
appleLogic "github.com/perfect-panel/server/internal/logic/public/iap/apple"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
func RestoreAppleTransactionsHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.RestoreAppleTransactionsRequest
_ = c.ShouldBind(&req)
if err := svcCtx.Validate(&req); err != nil {
result.ParamErrorResult(c, err)
return
}
l := appleLogic.NewRestoreLogic(c.Request.Context(), svcCtx)
err := l.Restore(&req)
result.HttpResult(c, map[string]bool{"success": err == nil}, err)
}
}
@@ -1,29 +0,0 @@
package iap
import (
"github.com/gin-gonic/gin"
"github.com/perfect-panel/server/internal/logic/public/iap"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/result"
)
// VerifyHandler 处理 iOS IAP 初购验证并生成已支付订单
// 参数: IAPVerifyRequest
// 返回: IAPVerifyResponse
func VerifyHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return func(c *gin.Context) {
var req types.IAPVerifyRequest
_ = c.ShouldBind(&req)
validateErr := svcCtx.Validate(&req)
if validateErr != nil {
result.ParamErrorResult(c, validateErr)
return
}
l := iap.NewVerifyLogic(c.Request.Context(), svcCtx)
resp, err := l.Verify(&req)
result.HttpResult(c, resp, err)
}
}
+13 -11
View File
@@ -26,8 +26,8 @@ import (
authOauth "github.com/perfect-panel/server/internal/handler/auth/oauth"
common "github.com/perfect-panel/server/internal/handler/common"
publicAnnouncement "github.com/perfect-panel/server/internal/handler/public/announcement"
publicDocument "github.com/perfect-panel/server/internal/handler/public/document"
publicIAP "github.com/perfect-panel/server/internal/handler/public/iap"
publicDocument "github.com/perfect-panel/server/internal/handler/public/document"
publicIapApple "github.com/perfect-panel/server/internal/handler/public/iap/apple"
publicOrder "github.com/perfect-panel/server/internal/handler/public/order"
publicPayment "github.com/perfect-panel/server/internal/handler/public/payment"
publicPortal "github.com/perfect-panel/server/internal/handler/public/portal"
@@ -672,7 +672,7 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
publicAnnouncementGroupRouter.GET("/list", publicAnnouncement.QueryAnnouncementHandler(serverCtx))
}
publicDocumentGroupRouter := router.Group("/v1/public/document")
publicDocumentGroupRouter := router.Group("/v1/public/document")
publicDocumentGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
{
@@ -681,14 +681,7 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
// Get document list
publicDocumentGroupRouter.GET("/list", publicDocument.QueryDocumentListHandler(serverCtx))
}
publicIAPGroupRouter := router.Group("/v1/public/iap")
publicIAPGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
{
publicIAPGroupRouter.POST("/verify", publicIAP.VerifyHandler(serverCtx))
}
}
publicOrderGroupRouter := router.Group("/v1/public/order")
publicOrderGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
@@ -727,6 +720,15 @@ func RegisterHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
publicPaymentGroupRouter.GET("/methods", publicPayment.GetAvailablePaymentMethodsHandler(serverCtx))
}
iapAppleGroupRouter := router.Group("/v1/public/iap/apple")
iapAppleGroupRouter.Use(middleware.AuthMiddleware(serverCtx), middleware.DeviceMiddleware(serverCtx))
{
iapAppleGroupRouter.GET("/products", publicIapApple.GetAppleProductsHandler(serverCtx))
iapAppleGroupRouter.GET("/status", publicIapApple.GetAppleStatusHandler(serverCtx))
iapAppleGroupRouter.POST("/transactions/attach", publicIapApple.AttachAppleTransactionHandler(serverCtx))
iapAppleGroupRouter.POST("/restore", publicIapApple.RestoreAppleTransactionsHandler(serverCtx))
}
publicPortalGroupRouter := router.Group("/v1/public/portal")
publicPortalGroupRouter.Use(middleware.DeviceMiddleware(serverCtx))
@@ -1,134 +0,0 @@
package notify
import (
"context"
"encoding/json"
"io"
"net/http"
"github.com/hibiken/asynq"
"github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/pkg/appleiap"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/payment"
queueType "github.com/perfect-panel/server/queue/types"
)
// AppleIAPNotifyLogic 处理 Apple Server Notifications v2 的逻辑
// 功能: 验签与事件解析(此处提供最小骨架),将续期/初购事件转换为订单并入队赋权
// 参数: HTTP 请求
// 返回: 错误信息
type AppleIAPNotifyLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// NewAppleIAPNotifyLogic 创建逻辑实例
// 参数: 上下文, 服务上下文
// 返回: 逻辑指针
func NewAppleIAPNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AppleIAPNotifyLogic {
return &AppleIAPNotifyLogic{Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
// AppleNotification 简化的通知结构(骨架)
type rawPayload struct {
SignedPayload string `json:"signedPayload"`
}
type transactionInfo struct {
OriginalTransactionId string `json:"originalTransactionId"`
TransactionId string `json:"transactionId"`
ProductId string `json:"productId"`
}
// Handle 处理通知
// 参数: *http.Request
// 返回: error
func (l *AppleIAPNotifyLogic) Handle(r *http.Request) error {
body, _ := io.ReadAll(r.Body)
var rp rawPayload
if err := json.Unmarshal(body, &rp); err != nil {
l.Errorw("[AppleIAP] Unmarshal request failed", logger.Field("error", err.Error()))
return err
}
claims, env, err := appleiap.VerifyAutoEnv(rp.SignedPayload)
if err != nil {
l.Errorw("[AppleIAP] Verify payload failed", logger.Field("error", err.Error()))
return err
}
t, _ := claims["notificationType"].(string)
data, _ := claims["data"].(map[string]interface{})
sti, _ := data["signedTransactionInfo"].(string)
txClaims, err := appleiap.VerifyWithEnv(env, sti)
if err != nil {
l.Errorw("[AppleIAP] Verify transaction failed", logger.Field("error", err.Error()))
return err
}
b, _ := json.Marshal(txClaims)
var tx transactionInfo
_ = json.Unmarshal(b, &tx)
switch t {
case "INITIAL_BUY":
return l.processInitialBuy(env, tx)
case "DID_RENEW":
return l.processRenew(env, tx)
default:
return nil
}
}
// createPaidOrderAndEnqueue 创建已支付订单并入队赋权/续费
// 参数: AppleNotification, 订单类型
// 返回: error
func (l *AppleIAPNotifyLogic) processInitialBuy(env string, tx transactionInfo) error {
if tx.OriginalTransactionId == "" || tx.TransactionId == "" {
return nil
}
// if order already exists, ignore
if oi, err := l.svcCtx.OrderModel.FindOneByTradeNo(l.ctx, tx.OriginalTransactionId); err == nil && oi != nil {
return nil
}
return nil
}
func (l *AppleIAPNotifyLogic) processRenew(env string, tx transactionInfo) error {
if tx.OriginalTransactionId == "" || tx.TransactionId == "" {
return nil
}
oi, err := l.svcCtx.OrderModel.FindOneByTradeNo(l.ctx, tx.OriginalTransactionId)
if err != nil || oi == nil {
return nil
}
o := &order.Order{
UserId: oi.UserId,
OrderNo: tx.TransactionId,
Type: 2,
Quantity: 1,
Price: 0,
Amount: 0,
Discount: 0,
Coupon: "",
CouponDiscount: 0,
PaymentId: 0,
Method: payment.AppleIAP.String(),
FeeAmount: 0,
Status: 2,
IsNew: false,
SubscribeId: oi.SubscribeId,
TradeNo: tx.OriginalTransactionId,
SubscribeToken: oi.SubscribeToken,
}
if err := l.svcCtx.OrderModel.Insert(l.ctx, o); err != nil {
return err
}
payload := queueType.ForthwithActivateOrderPayload{OrderNo: o.OrderNo}
bytes, _ := json.Marshal(payload)
task := asynq.NewTask(queueType.ForthwithActivateOrder, bytes)
if _, err := l.svcCtx.Queue.EnqueueContext(l.ctx, task); err != nil {
return err
}
return nil
}
@@ -0,0 +1,101 @@
package apple
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
iapapple "github.com/perfect-panel/server/pkg/iap/apple"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/pkg/errors"
"gorm.io/gorm"
"github.com/google/uuid"
)
type AttachTransactionLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewAttachTransactionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AttachTransactionLogic {
return &AttachTransactionLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *AttachTransactionLogic) Attach(req *types.AttachAppleTransactionRequest) (*types.AttachAppleTransactionResponse, error) {
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok || u == nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "invalid access")
}
txPayload, err := iapapple.ParseTransactionJWS(req.SignedTransactionJWS)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "invalid jws")
}
pm, _ := iapapple.ParseProductMap(l.svcCtx.Config.Site.CustomData)
m, ok := pm.Items[txPayload.ProductId]
var duration int64
var tier string
var subscribeId int64
if ok {
duration = m.DurationDays
tier = m.Tier
subscribeId = m.SubscribeId
} else {
if req.DurationDays <= 0 || req.SubscribeId <= 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "unknown product")
}
duration = req.DurationDays
tier = req.Tier
subscribeId = req.SubscribeId
}
exp := iapapple.CalcExpire(txPayload.PurchaseDate, duration)
sum := sha256.Sum256([]byte(req.SignedTransactionJWS))
jwsHash := hex.EncodeToString(sum[:])
iapTx := &iapmodel.Transaction{
UserId: u.Id,
OriginalTransactionId: txPayload.OriginalTransactionId,
TransactionId: txPayload.TransactionId,
ProductId: txPayload.ProductId,
PurchaseAt: txPayload.PurchaseDate,
RevocationAt: txPayload.RevocationDate,
JWSHash: jwsHash,
}
err = l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
if e := tx.Model(&iapmodel.Transaction{}).Create(iapTx).Error; e != nil {
return e
}
// insert user_subscribe
userSub := user.Subscribe{
UserId: u.Id,
SubscribeId: subscribeId,
StartTime: time.Now(),
ExpireTime: exp,
Traffic: 0,
Download: 0,
Upload: 0,
Token: fmt.Sprintf("iap:%s", txPayload.OriginalTransactionId),
UUID: uuid.New().String(),
Status: 1,
}
return l.svcCtx.UserModel.InsertSubscribe(l.ctx, &userSub, tx)
})
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert error: %v", err.Error())
}
return &types.AttachAppleTransactionResponse{
ExpiresAt: exp.Unix(),
Tier: tier,
}, nil
}
@@ -0,0 +1,42 @@
package apple
import (
"context"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
iapapple "github.com/perfect-panel/server/pkg/iap/apple"
)
type GetProductsLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetProductsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetProductsLogic {
return &GetProductsLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetProductsLogic) GetProducts() (*types.GetAppleProductsResponse, error) {
pm, _ := iapapple.ParseProductMap(l.svcCtx.Config.Site.CustomData)
resp := &types.GetAppleProductsResponse{
List: make([]types.AppleProduct, 0, len(pm.Items)),
}
for pid, m := range pm.Items {
resp.List = append(resp.List, types.AppleProduct{
ProductId: pid,
Description: m.Description,
PriceText: m.PriceText,
DurationDays: m.DurationDays,
Tier: m.Tier,
SubscribeId: m.SubscribeId,
})
}
return resp, nil
}
@@ -0,0 +1,62 @@
package apple
import (
"context"
"time"
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
iapapple "github.com/perfect-panel/server/pkg/iap/apple"
"github.com/perfect-panel/server/pkg/constant"
"github.com/pkg/errors"
)
type GetStatusLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetStatusLogic {
return &GetStatusLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetStatusLogic) GetStatus() (*types.GetAppleStatusResponse, error) {
u, ok := l.ctx.Value(constant.CtxKeyUser).(*struct{ Id int64 })
if !ok || u == nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "invalid access")
}
pm, _ := iapapple.ParseProductMap(l.svcCtx.Config.Site.CustomData)
var latest *iapmodel.Transaction
var err error
for pid := range pm.Items {
item, e := iapmodel.NewModel(l.svcCtx.DB, l.svcCtx.Redis).FindByUserAndProduct(l.ctx, u.Id, pid)
if e == nil && item != nil && item.Id != 0 {
if latest == nil || item.PurchaseAt.After(latest.PurchaseAt) {
latest = item
}
}
}
if latest == nil {
return &types.GetAppleStatusResponse{
Active: false,
ExpiresAt: 0,
Tier: "",
}, nil
}
m := pm.Items[latest.ProductId]
exp := iapapple.CalcExpire(latest.PurchaseAt, m.DurationDays).Unix()
active := latest.RevocationAt == nil && (exp == 0 || exp > time.Now().Unix())
return &types.GetAppleStatusResponse{
Active: active,
ExpiresAt: exp,
Tier: m.Tier,
}, err
}
@@ -0,0 +1,86 @@
package apple
import (
"context"
"time"
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
iapapple "github.com/perfect-panel/server/pkg/iap/apple"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/xerr"
"github.com/google/uuid"
"github.com/pkg/errors"
"gorm.io/gorm"
)
type RestoreLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewRestoreLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RestoreLogic {
return &RestoreLogic{
Logger: logger.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *RestoreLogic) Restore(req *types.RestoreAppleTransactionsRequest) error {
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok || u == nil {
return errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "invalid access")
}
pm, _ := iapapple.ParseProductMap(l.svcCtx.Config.Site.CustomData)
return l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
for _, j := range req.Transactions {
txp, err := iapapple.ParseTransactionJWS(j)
if err != nil {
continue
}
m, ok := pm.Items[txp.ProductId]
if !ok {
continue
}
_, e := iapmodel.NewModel(l.svcCtx.DB, l.svcCtx.Redis).FindByOriginalId(l.ctx, txp.OriginalTransactionId)
if e == nil {
continue
}
iapTx := &iapmodel.Transaction{
UserId: u.Id,
OriginalTransactionId: txp.OriginalTransactionId,
TransactionId: txp.TransactionId,
ProductId: txp.ProductId,
PurchaseAt: txp.PurchaseDate,
RevocationAt: txp.RevocationDate,
JWSHash: "",
}
if err := tx.Model(&iapmodel.Transaction{}).Create(iapTx).Error; err != nil {
return err
}
exp := iapapple.CalcExpire(txp.PurchaseDate, m.DurationDays)
userSub := user.Subscribe{
UserId: u.Id,
SubscribeId: m.SubscribeId,
StartTime: time.Now(),
ExpireTime: exp,
Traffic: 0,
Download: 0,
Upload: 0,
Token: txp.OriginalTransactionId,
UUID: uuid.New().String(),
Status: 1,
}
if err := l.svcCtx.UserModel.InsertSubscribe(l.ctx, &userSub, tx); err != nil {
return err
}
}
return nil
})
}
-104
View File
@@ -1,104 +0,0 @@
package iap
import (
"context"
"encoding/json"
"github.com/hibiken/asynq"
"github.com/perfect-panel/server/internal/model/order"
"github.com/perfect-panel/server/internal/model/user"
"github.com/perfect-panel/server/internal/svc"
"github.com/perfect-panel/server/internal/types"
"github.com/perfect-panel/server/pkg/constant"
"github.com/perfect-panel/server/pkg/logger"
"github.com/perfect-panel/server/pkg/payment"
"github.com/perfect-panel/server/pkg/tool"
"github.com/perfect-panel/server/pkg/xerr"
queueType "github.com/perfect-panel/server/queue/types"
"github.com/pkg/errors"
)
// VerifyLogic 处理 IAP 初购验证并生成已支付订阅订单
// 功能: 校验用户与订阅参数, 创建已支付订单并触发赋权队列
// 参数: IAPVerifyRequest
// 返回: IAPVerifyResponse 与错误
type VerifyLogic struct {
logger.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// NewVerifyLogic 创建 VerifyLogic
// 参数: 上下文, 服务上下文
// 返回: VerifyLogic 指针
func NewVerifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *VerifyLogic {
return &VerifyLogic{Logger: logger.WithContext(ctx), ctx: ctx, svcCtx: svcCtx}
}
// Verify 执行 IAP 初购验证并创建订单
// 参数: IAPVerifyRequest 包含 original_transaction_id 与 subscribe_id
// 返回: IAPVerifyResponse 包含 order_no
func (l *VerifyLogic) Verify(req *types.IAPVerifyRequest) (resp *types.IAPVerifyResponse, err error) {
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
if !ok {
logger.Error("current user is not found in context")
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
}
if req.SubscribeId <= 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "invalid subscribe_id")
}
sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, req.SubscribeId)
if err != nil {
l.Errorw("[IAP Verify] Find subscribe failed", logger.Field("error", err.Error()), logger.Field("subscribe_id", req.SubscribeId))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
}
if sub.Sell != nil && !*sub.Sell {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "subscribe not sell")
}
isNew, err := l.svcCtx.OrderModel.IsUserEligibleForNewOrder(l.ctx, u.Id)
if err != nil {
l.Errorw("[IAP Verify] Query user new purchase failed", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user error: %v", err.Error())
}
orderInfo := &order.Order{
UserId: u.Id,
OrderNo: tool.GenerateTradeNo(),
Type: 1,
Quantity: 1,
Price: sub.UnitPrice,
Amount: 0,
Discount: 0,
Coupon: "",
CouponDiscount: 0,
PaymentId: 0,
Method: payment.AppleIAP.String(),
FeeAmount: 0,
Status: 2,
IsNew: isNew,
SubscribeId: req.SubscribeId,
TradeNo: req.OriginalTransactionId,
}
if err = l.svcCtx.OrderModel.Insert(l.ctx, orderInfo); err != nil {
l.Errorw("[IAP Verify] Insert order failed", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert order error: %v", err.Error())
}
payload := queueType.ForthwithActivateOrderPayload{OrderNo: orderInfo.OrderNo}
bytes, err := json.Marshal(payload)
if err != nil {
l.Errorw("[IAP Verify] Marshal payload failed", logger.Field("error", err.Error()))
return nil, err
}
task := asynq.NewTask(queueType.ForthwithActivateOrder, bytes)
if _, err = l.svcCtx.Queue.EnqueueContext(l.ctx, task); err != nil {
l.Errorw("[IAP Verify] Enqueue activation failed", logger.Field("error", err.Error()))
return nil, err
}
return &types.IAPVerifyResponse{OrderNo: orderInfo.OrderNo}, nil
}
@@ -5,6 +5,7 @@ import (
"encoding/json"
"math"
"strconv"
"strings"
"time"
"github.com/perfect-panel/server/internal/model/log"
@@ -224,8 +225,22 @@ func (l *PurchaseCheckoutLogic) stripePayment(config string, info *order.Order,
WebhookSecret: stripeConfig.WebhookSecret,
})
// Convert order amount to CNY using current exchange rate
amount, err := l.queryExchangeRate("CNY", info.Amount)
currency := "USD"
sysCurrency, _ := l.svcCtx.SystemModel.GetCurrencyConfig(l.ctx)
if sysCurrency != nil {
configs := struct {
CurrencyUnit string
CurrencySymbol string
AccessKey string
}{}
tool.SystemConfigSliceReflectToStruct(sysCurrency, &configs)
if configs.CurrencyUnit != "" {
currency = configs.CurrencyUnit
}
}
// Convert order amount to configured currency using current exchange rate
amount, err := l.queryExchangeRate(strings.ToUpper(currency), info.Amount)
if err != nil {
l.Errorw("[PurchaseCheckout] queryExchangeRate error", logger.Field("error", err.Error()))
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "queryExchangeRate error: %s", err.Error())
@@ -235,6 +250,7 @@ func (l *PurchaseCheckoutLogic) stripePayment(config string, info *order.Order,
logger.Field("src_cents", info.Amount),
logger.Field("decimal", amount),
logger.Field("cents", convertAmount),
logger.Field("currency", currency),
)
// Create Stripe payment sheet for client-side processing
@@ -247,7 +263,7 @@ func (l *PurchaseCheckoutLogic) stripePayment(config string, info *order.Order,
OrderNo: info.OrderNo,
Subscribe: strconv.FormatInt(info.SubscribeId, 10),
Amount: convertAmount,
Currency: "cny",
Currency: strings.ToLower(currency),
Payment: paymentMethod,
}
usr := &stripe.User{Email: identifier}
+68
View File
@@ -0,0 +1,68 @@
package apple
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"github.com/perfect-panel/server/pkg/cache"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type Model interface {
Insert(ctx context.Context, data *Transaction, tx ...*gorm.DB) error
FindByOriginalId(ctx context.Context, originalId string) (*Transaction, error)
FindByUserAndProduct(ctx context.Context, userId int64, productId string) (*Transaction, error)
}
type defaultModel struct {
cache.CachedConn
table string
}
type customModel struct {
*defaultModel
}
func NewModel(db *gorm.DB, c *redis.Client) Model {
return &customModel{
defaultModel: &defaultModel{
CachedConn: cache.NewConn(db, c),
table: "`apple_iap_transactions`",
},
}
}
func (m *defaultModel) jwsKey(jws string) string {
sum := sha256.Sum256([]byte(jws))
return fmt.Sprintf("cache:iap:jws:%s", hex.EncodeToString(sum[:]))
}
func (m *customModel) Insert(ctx context.Context, data *Transaction, tx ...*gorm.DB) error {
return m.ExecCtx(ctx, func(conn *gorm.DB) error {
if len(tx) > 0 {
conn = tx[0]
}
return conn.Model(&Transaction{}).Create(data).Error
}, m.jwsKey(data.JWSHash))
}
func (m *customModel) FindByOriginalId(ctx context.Context, originalId string) (*Transaction, error) {
var data Transaction
key := fmt.Sprintf("cache:iap:original:%s", originalId)
err := m.QueryCtx(ctx, &data, key, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Transaction{}).Where("original_transaction_id = ?", originalId).First(&data).Error
})
return &data, err
}
func (m *customModel) FindByUserAndProduct(ctx context.Context, userId int64, productId string) (*Transaction, error) {
var data Transaction
err := m.QueryNoCacheCtx(ctx, &data, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Transaction{}).Where("user_id = ? AND product_id = ?", userId, productId).Order("purchase_at DESC").First(&data).Error
})
return &data, err
}
+21
View File
@@ -0,0 +1,21 @@
package apple
import "time"
type Transaction struct {
Id int64 `gorm:"primaryKey"`
UserId int64 `gorm:"index:idx_user_id;not null;comment:User ID"`
OriginalTransactionId string `gorm:"type:varchar(255);uniqueIndex:uni_original;not null;comment:Original Transaction ID"`
TransactionId string `gorm:"type:varchar(255);not null;comment:Transaction ID"`
ProductId string `gorm:"type:varchar(255);not null;comment:Product ID"`
PurchaseAt time.Time `gorm:"not null;comment:Purchase Time"`
RevocationAt *time.Time `gorm:"comment:Revocation Time"`
JWSHash string `gorm:"type:varchar(255);not null;comment:JWS Hash"`
CreatedAt time.Time `gorm:"<-:create;comment:Create Time"`
UpdatedAt time.Time `gorm:"comment:Update Time"`
}
func (Transaction) TableName() string {
return "apple_iap_transactions"
}
+20 -38
View File
@@ -12,25 +12,23 @@ import (
var _ Model = (*customOrderModel)(nil)
var (
cacheOrderIdPrefix = "cache:order:id:"
cacheOrderNoPrefix = "cache:order:no:"
cacheOrderTradePrefix = "cache:order:trade:"
cacheOrderIdPrefix = "cache:order:id:"
cacheOrderNoPrefix = "cache:order:no:"
)
type (
Model interface {
orderModel
customOrderLogicModel
}
orderModel interface {
Insert(ctx context.Context, data *Order, tx ...*gorm.DB) error
FindOne(ctx context.Context, id int64) (*Order, error)
FindOneByOrderNo(ctx context.Context, orderNo string) (*Order, error)
FindOneByTradeNo(ctx context.Context, tradeNo string) (*Order, error)
Update(ctx context.Context, data *Order, tx ...*gorm.DB) error
Delete(ctx context.Context, id int64, tx ...*gorm.DB) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
Model interface {
orderModel
customOrderLogicModel
}
orderModel interface {
Insert(ctx context.Context, data *Order, tx ...*gorm.DB) error
FindOne(ctx context.Context, id int64) (*Order, error)
FindOneByOrderNo(ctx context.Context, orderNo string) (*Order, error)
Update(ctx context.Context, data *Order, tx ...*gorm.DB) error
Delete(ctx context.Context, id int64, tx ...*gorm.DB) error
Transaction(ctx context.Context, fn func(db *gorm.DB) error) error
}
customOrderModel struct {
*defaultOrderModel
@@ -62,14 +60,12 @@ func (m *defaultOrderModel) getCacheKeys(data *Order) []string {
return []string{}
}
orderIdKey := fmt.Sprintf("%s%v", cacheOrderIdPrefix, data.Id)
orderNoKey := fmt.Sprintf("%s%v", cacheOrderNoPrefix, data.OrderNo)
tradeNoKey := fmt.Sprintf("%s%v", cacheOrderTradePrefix, data.TradeNo)
cacheKeys := []string{
orderIdKey,
orderNoKey,
tradeNoKey,
}
return cacheKeys
orderNoKey := fmt.Sprintf("%s%v", cacheOrderNoPrefix, data.OrderNo)
cacheKeys := []string{
orderIdKey,
orderNoKey,
}
return cacheKeys
}
func (m *defaultOrderModel) Insert(ctx context.Context, data *Order, tx ...*gorm.DB) error {
@@ -110,20 +106,6 @@ func (m *defaultOrderModel) FindOneByOrderNo(ctx context.Context, orderNo string
}
}
func (m *defaultOrderModel) FindOneByTradeNo(ctx context.Context, tradeNo string) (*Order, error) {
OrderTradeKey := fmt.Sprintf("%s%v", cacheOrderTradePrefix, tradeNo)
var resp Order
err := m.QueryCtx(ctx, &resp, OrderTradeKey, func(conn *gorm.DB, v interface{}) error {
return conn.Model(&Order{}).Where("`trade_no` = ?", tradeNo).First(&resp).Error
})
switch {
case err == nil:
return &resp, nil
default:
return nil, err
}
}
func (m *defaultOrderModel) Update(ctx context.Context, data *Order, tx ...*gorm.DB) error {
old, err := m.FindOne(ctx, data.Id)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
+3
View File
@@ -27,6 +27,7 @@ import (
"github.com/perfect-panel/server/internal/model/ticket"
"github.com/perfect-panel/server/internal/model/traffic"
"github.com/perfect-panel/server/internal/model/user"
iapapple "github.com/perfect-panel/server/internal/model/iap/apple"
"github.com/perfect-panel/server/pkg/limit"
"github.com/perfect-panel/server/pkg/nodeMultiplier"
"github.com/perfect-panel/server/pkg/orm"
@@ -62,6 +63,7 @@ type ServiceContext struct {
SubscribeModel subscribe.Model
TrafficLogModel traffic.Model
AnnouncementModel announcement.Model
IAPAppleTransactionModel iapapple.Model
Restart func() error
TelegramBot *tgbotapi.BotAPI
@@ -117,6 +119,7 @@ func NewServiceContext(c config.Config) *ServiceContext {
TrafficLogModel: traffic.NewModel(db),
AnnouncementModel: announcement.NewModel(db, rds),
}
srv.IAPAppleTransactionModel = iapapple.NewModel(db, rds)
srv.DeviceManager = NewDeviceManager(srv)
return srv
+38 -12
View File
@@ -72,18 +72,9 @@ type AppUserSubscbribeNode struct {
}
type AppleLoginCallbackRequest struct {
Code string `form:"code"`
IDToken string `form:"id_token"`
State string `form:"state"`
}
type IAPVerifyRequest struct {
OriginalTransactionId string `json:"original_transaction_id" validate:"required"`
SubscribeId int64 `json:"subscribe_id" validate:"required"`
}
type IAPVerifyResponse struct {
OrderNo string `json:"order_no"`
Code string `form:"code"`
IDToken string `form:"id_token"`
State string `form:"state"`
}
type Application struct {
@@ -2853,3 +2844,38 @@ type VmessProtocol struct {
Network string `json:"network"`
Transport string `json:"transport"`
}
type AppleProduct struct {
ProductId string `json:"product_id"`
Description string `json:"description"`
PriceText string `json:"price_text"`
DurationDays int64 `json:"duration_days"`
Tier string `json:"tier"`
SubscribeId int64 `json:"subscribe_id"`
}
type GetAppleProductsResponse struct {
List []AppleProduct `json:"list"`
}
type AttachAppleTransactionRequest struct {
SignedTransactionJWS string `json:"signed_transaction_jws" validate:"required"`
DurationDays int64 `json:"duration_days,omitempty"`
Tier string `json:"tier,omitempty"`
SubscribeId int64 `json:"subscribe_id,omitempty"`
}
type AttachAppleTransactionResponse struct {
ExpiresAt int64 `json:"expires_at"`
Tier string `json:"tier"`
}
type RestoreAppleTransactionsRequest struct {
Transactions []string `json:"transactions" validate:"required"`
}
type GetAppleStatusResponse struct {
Active bool `json:"active"`
ExpiresAt int64 `json:"expires_at"`
Tier string `json:"tier"`
}