同步历史版本代码
This commit is contained in:
@@ -0,0 +1,138 @@
|
||||
package apple
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/perfect-panel/server/internal/model/payment"
|
||||
"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"
|
||||
)
|
||||
|
||||
type AttachTransactionByIdLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
func NewAttachTransactionByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AttachTransactionByIdLogic {
|
||||
return &AttachTransactionByIdLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *AttachTransactionByIdLogic) AttachById(req *types.AttachAppleTransactionByIdRequest) (*types.AttachAppleTransactionResponse, error) {
|
||||
l.Infow("attach by transaction id start", logger.Field("orderNo", req.OrderNo), logger.Field("transactionId", req.TransactionId))
|
||||
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
if !ok || u == nil {
|
||||
l.Errorw("attach by id invalid access")
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "invalid access")
|
||||
}
|
||||
ord, err := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
|
||||
if err != nil {
|
||||
l.Errorw("attach by id order not exist", logger.Field("orderNo", req.OrderNo))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.OrderNotExist), "order not exist")
|
||||
}
|
||||
pay, err := l.svcCtx.PaymentModel.FindOne(l.ctx, ord.PaymentId)
|
||||
if err != nil {
|
||||
l.Errorw("attach by id payment not found", logger.Field("paymentId", ord.PaymentId))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.PaymentMethodNotFound), "payment not found")
|
||||
}
|
||||
hasKey := false
|
||||
if pay.Config != "" && (strings.Contains(pay.Config, "-----BEGIN PRIVATE KEY-----") || strings.Contains(pay.Config, "BEGIN PRIVATE KEY")) {
|
||||
hasKey = true
|
||||
}
|
||||
l.Infow("attach by id payment config meta", logger.Field("paymentId", pay.Id), logger.Field("platform", pay.Platform), logger.Field("config_len", len(pay.Config)), logger.Field("has_private_key", hasKey))
|
||||
if pay.Config == "" {
|
||||
l.Errorw("attach by id iap config empty", logger.Field("paymentId", pay.Id))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "iap config is empty")
|
||||
}
|
||||
var cfg payment.AppleIAPConfig
|
||||
if err := cfg.Unmarshal([]byte(pay.Config)); err != nil {
|
||||
l.Errorw("attach by id iap config error", logger.Field("error", err.Error()), logger.Field("paymentId", pay.Id), logger.Field("platform", pay.Platform), logger.Field("config_len", len(pay.Config)), logger.Field("has_private_key", hasKey))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "iap config error")
|
||||
}
|
||||
apiCfg := iapapple.ServerAPIConfig{
|
||||
KeyID: cfg.KeyID,
|
||||
IssuerID: cfg.IssuerID,
|
||||
PrivateKey: cfg.PrivateKey,
|
||||
Sandbox: cfg.Sandbox,
|
||||
}
|
||||
|
||||
// Try to extract BundleID from productIds (if available in config) or custom data
|
||||
// For now, we leave it empty unless we find it in config, but we can try to parse from payment config if needed.
|
||||
// However, ServerAPIConfig update allows optional BundleID.
|
||||
|
||||
if req.Sandbox != nil {
|
||||
apiCfg.Sandbox = *req.Sandbox
|
||||
}
|
||||
|
||||
// Try to fix PEM format if it is missing newlines (common issue)
|
||||
if !strings.Contains(apiCfg.PrivateKey, "\n") && strings.Contains(apiCfg.PrivateKey, "BEGIN PRIVATE KEY") {
|
||||
apiCfg.PrivateKey = strings.ReplaceAll(apiCfg.PrivateKey, " ", "\n")
|
||||
apiCfg.PrivateKey = strings.ReplaceAll(apiCfg.PrivateKey, "-----BEGIN\nPRIVATE\nKEY-----", "-----BEGIN PRIVATE KEY-----")
|
||||
apiCfg.PrivateKey = strings.ReplaceAll(apiCfg.PrivateKey, "-----END\nPRIVATE\nKEY-----", "-----END PRIVATE KEY-----")
|
||||
}
|
||||
|
||||
// Fallback to hardcoded key (For debugging/dev)
|
||||
if apiCfg.PrivateKey == "" {
|
||||
apiCfg.PrivateKey = `-----BEGIN PRIVATE KEY-----
|
||||
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgsVDj0g/D7uNCm8aC
|
||||
E4TuaiDT4Pgb1IuuZ69YdGNvcAegCgYIKoZIzj0DAQehRANCAARObgGumaESbPMM
|
||||
SIRDAVLcWemp0fMlnfDE4EHmqcD58arEJWsr3aWEhc4BHocOUIGjko0cVWGchrFa
|
||||
/T/KG1tr
|
||||
-----END PRIVATE KEY-----`
|
||||
apiCfg.KeyID = "2C4X3HVPM8"
|
||||
}
|
||||
|
||||
if apiCfg.KeyID == "" || apiCfg.IssuerID == "" || apiCfg.PrivateKey == "" {
|
||||
l.Errorw("attach by id credential missing")
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "apple server api credential missing")
|
||||
}
|
||||
|
||||
// Hardcode IssuerID as fallback (since it was missing in config)
|
||||
if apiCfg.IssuerID == "" || apiCfg.IssuerID == "some_issuer_id" {
|
||||
apiCfg.IssuerID = "34f54810-5118-4b7f-8069-c8c1e012b7a9"
|
||||
}
|
||||
|
||||
// Try to get BundleID from Site CustomData if not set
|
||||
if apiCfg.BundleID == "" {
|
||||
var customData struct {
|
||||
IapBundleId string `json:"iapBundleId"`
|
||||
}
|
||||
if l.svcCtx.Config.Site.CustomData != "" {
|
||||
_ = json.Unmarshal([]byte(l.svcCtx.Config.Site.CustomData), &customData)
|
||||
apiCfg.BundleID = customData.IapBundleId
|
||||
}
|
||||
}
|
||||
|
||||
jws, err := iapapple.GetTransactionInfo(apiCfg, req.TransactionId)
|
||||
if err != nil {
|
||||
l.Errorw("fetch transaction info error", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "fetch transaction info error")
|
||||
}
|
||||
// reuse existing attach logic with JWS
|
||||
attach := NewAttachTransactionLogic(l.ctx, l.svcCtx)
|
||||
resp, e := attach.Attach(&types.AttachAppleTransactionRequest{
|
||||
SignedTransactionJWS: jws,
|
||||
SubscribeId: 0,
|
||||
DurationDays: 0,
|
||||
Tier: "",
|
||||
OrderNo: req.OrderNo,
|
||||
})
|
||||
if e != nil {
|
||||
l.Errorw("attach by id commit error", logger.Field("error", e.Error()))
|
||||
return nil, e
|
||||
}
|
||||
l.Infow("attach by transaction id ok", logger.Field("orderNo", req.OrderNo), logger.Field("transactionId", req.TransactionId), logger.Field("expiresAt", resp.ExpiresAt))
|
||||
return resp, nil
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package apple
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/hibiken/asynq"
|
||||
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
|
||||
"github.com/perfect-panel/server/internal/model/subscribe"
|
||||
"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"
|
||||
queueType "github.com/perfect-panel/server/queue/types"
|
||||
"github.com/pkg/errors"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
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) {
|
||||
l.Infow("开始绑定 Apple IAP 交易", logger.Field("orderNo", req.OrderNo))
|
||||
u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
|
||||
if !ok || u == nil {
|
||||
l.Errorw("无效访问,用户信息缺失")
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "invalid access")
|
||||
}
|
||||
txPayload, err := iapapple.VerifyTransactionJWS(req.SignedTransactionJWS)
|
||||
if err != nil {
|
||||
l.Errorw("JWS 验签失败", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "invalid jws")
|
||||
}
|
||||
l.Infow("JWS 验签成功", logger.Field("productId", txPayload.ProductId), logger.Field("originalTransactionId", txPayload.OriginalTransactionId), logger.Field("purchaseAt", txPayload.PurchaseDate))
|
||||
// idempotency: check existing transaction by original id
|
||||
var existTx *iapmodel.Transaction
|
||||
existTx, _ = iapmodel.NewModel(l.svcCtx.DB, l.svcCtx.Redis).FindByOriginalId(l.ctx, txPayload.OriginalTransactionId)
|
||||
l.Infow("幂等等检查", logger.Field("originalTransactionId", txPayload.OriginalTransactionId), logger.Field("exists", existTx != nil && existTx.Id > 0))
|
||||
|
||||
// 解析 Apple 商品ID中的单位与数量:支持 dayN / monthN / yearN
|
||||
var parsedUnit string
|
||||
var parsedQuantity int64
|
||||
{
|
||||
pid := strings.ToLower(txPayload.ProductId)
|
||||
parts := strings.Split(pid, ".")
|
||||
for i := len(parts) - 1; i >= 0; i-- {
|
||||
p := parts[i]
|
||||
if strings.HasPrefix(p, "day") || strings.HasPrefix(p, "month") || strings.HasPrefix(p, "year") {
|
||||
switch {
|
||||
case strings.HasPrefix(p, "day"):
|
||||
parsedUnit = "Day"
|
||||
p = p[len("day"):]
|
||||
case strings.HasPrefix(p, "month"):
|
||||
parsedUnit = "Month"
|
||||
p = p[len("month"):]
|
||||
case strings.HasPrefix(p, "year"):
|
||||
parsedUnit = "Year"
|
||||
p = p[len("year"):]
|
||||
}
|
||||
digits := p
|
||||
for j := 0; j < len(digits); j++ {
|
||||
if digits[j] < '0' || digits[j] > '9' {
|
||||
digits = digits[:j]
|
||||
break
|
||||
}
|
||||
}
|
||||
if q, e := strconv.ParseInt(digits, 10, 64); e == nil && q > 0 {
|
||||
parsedQuantity = q
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
l.Infow("商品映射解析", logger.Field("productId", txPayload.ProductId), logger.Field("解析单位", parsedUnit), logger.Field("解析数量", parsedQuantity))
|
||||
|
||||
// 基于订阅列表的折扣配置做匹配:UnitTime=Day 且 Discount.quantity == parsedQuantity
|
||||
var duration int64
|
||||
var tier string
|
||||
var subscribeId int64
|
||||
if parsedQuantity > 0 {
|
||||
_, subs, e := l.svcCtx.SubscribeModel.FilterList(l.ctx, &subscribe.FilterParams{
|
||||
Page: 1,
|
||||
Size: 9999,
|
||||
Show: true,
|
||||
Sell: true,
|
||||
DefaultLanguage: true,
|
||||
})
|
||||
if e == nil && len(subs) > 0 {
|
||||
for _, item := range subs {
|
||||
if parsedUnit != "" && !strings.EqualFold(item.UnitTime, parsedUnit) {
|
||||
continue
|
||||
}
|
||||
var discounts []types.SubscribeDiscount
|
||||
if item.Discount != "" {
|
||||
_ = json.Unmarshal([]byte(item.Discount), &discounts)
|
||||
}
|
||||
for _, d := range discounts {
|
||||
if int64(d.Quantity) == parsedQuantity {
|
||||
switch parsedUnit {
|
||||
case "Day":
|
||||
duration = parsedQuantity
|
||||
case "Month":
|
||||
duration = parsedQuantity * 30
|
||||
case "Year":
|
||||
duration = parsedQuantity * 365
|
||||
default:
|
||||
duration = parsedQuantity
|
||||
}
|
||||
subscribeId = item.Id
|
||||
tier = item.Name
|
||||
l.Infow("订阅映射命中", logger.Field("subscribeId", subscribeId), logger.Field("name", tier), logger.Field("durationDays", duration))
|
||||
break
|
||||
}
|
||||
}
|
||||
if subscribeId > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
l.Infow("订阅列表为空或查询失败", logger.Field("error", func() string {
|
||||
if e != nil {
|
||||
return e.Error()
|
||||
}
|
||||
return ""
|
||||
}()))
|
||||
}
|
||||
}
|
||||
if subscribeId == 0 {
|
||||
// fallback from order_no if provided
|
||||
if req.OrderNo != "" {
|
||||
if ord, e := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo); e == nil && ord != nil && ord.Id != 0 {
|
||||
duration = ord.Quantity
|
||||
subscribeId = ord.SubscribeId
|
||||
l.Infow("使用订单信息回退", logger.Field("orderNo", req.OrderNo), logger.Field("durationDays", duration), logger.Field("subscribeId", subscribeId))
|
||||
} else {
|
||||
l.Infow("订单信息不可用,尝试请求参数回退", logger.Field("orderNo", req.OrderNo))
|
||||
}
|
||||
}
|
||||
// final fallback: use request fields
|
||||
if duration <= 0 {
|
||||
duration = req.DurationDays
|
||||
}
|
||||
if tier == "" {
|
||||
tier = req.Tier
|
||||
}
|
||||
if subscribeId <= 0 {
|
||||
subscribeId = req.SubscribeId
|
||||
}
|
||||
l.Infow("使用请求参数回退", logger.Field("durationDays", duration), logger.Field("tier", tier), logger.Field("subscribeId", subscribeId))
|
||||
if duration <= 0 || subscribeId <= 0 {
|
||||
l.Errorw("商品识别失败", logger.Field("durationDays", duration), logger.Field("tier", tier), logger.Field("subscribeId", subscribeId))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "unknown product")
|
||||
}
|
||||
}
|
||||
exp := iapapple.CalcExpire(txPayload.PurchaseDate, duration)
|
||||
l.Infow("计算订阅到期时间", logger.Field("expireAt", exp), logger.Field("expireUnix", exp.Unix()))
|
||||
|
||||
if existTx != nil && existTx.Id > 0 {
|
||||
token := fmt.Sprintf("iap:%s", txPayload.OriginalTransactionId)
|
||||
existSub, err := l.svcCtx.UserModel.FindOneSubscribeByToken(l.ctx, token)
|
||||
if err == nil && existSub != nil && existSub.Id > 0 {
|
||||
// Already processed, return success
|
||||
l.Infow("事务已处理,直接返回", logger.Field("originalTransactionId", txPayload.OriginalTransactionId), logger.Field("tier", tier), logger.Field("expiresAt", exp.Unix()))
|
||||
return &types.AttachAppleTransactionResponse{
|
||||
ExpiresAt: exp.Unix(),
|
||||
Tier: tier,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
sum := sha256.Sum256([]byte(req.SignedTransactionJWS))
|
||||
jwsHash := hex.EncodeToString(sum[:])
|
||||
l.Infow("准备写入事务记录", logger.Field("userId", u.Id), logger.Field("transactionId", txPayload.TransactionId), logger.Field("originalTransactionId", txPayload.OriginalTransactionId), logger.Field("productId", txPayload.ProductId), logger.Field("jwsHash", jwsHash))
|
||||
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 existTx == nil || existTx.Id == 0 {
|
||||
if e := tx.Model(&iapmodel.Transaction{}).Create(iapTx).Error; e != nil {
|
||||
l.Errorw("写入事务表失败", logger.Field("error", e.Error()))
|
||||
return e
|
||||
}
|
||||
l.Infow("写入事务表成功", logger.Field("id", iapTx.Id))
|
||||
}
|
||||
// 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,
|
||||
}
|
||||
if e := l.svcCtx.UserModel.InsertSubscribe(l.ctx, &userSub, tx); e != nil {
|
||||
l.Errorw("写入用户订阅失败", logger.Field("error", e.Error()))
|
||||
return e
|
||||
}
|
||||
l.Infow("写入用户订阅成功", logger.Field("userId", u.Id), logger.Field("subscribeId", subscribeId), logger.Field("expireUnix", exp.Unix()))
|
||||
// optional: mark related order as paid and enqueue activation
|
||||
if req.OrderNo != "" {
|
||||
orderInfo, e := l.svcCtx.OrderModel.FindOneByOrderNo(l.ctx, req.OrderNo)
|
||||
if e != nil {
|
||||
// do not fail transaction if order not found; just continue
|
||||
l.Infow("订单不存在或查询失败,跳过订单状态更新", logger.Field("orderNo", req.OrderNo))
|
||||
return nil
|
||||
}
|
||||
if orderInfo.Status == 1 {
|
||||
if e := l.svcCtx.OrderModel.UpdateOrderStatus(l.ctx, req.OrderNo, 2, tx); e != nil {
|
||||
l.Errorw("更新订单状态失败", logger.Field("orderNo", req.OrderNo), logger.Field("error", e.Error()))
|
||||
return e
|
||||
}
|
||||
l.Infow("更新订单状态成功", logger.Field("orderNo", req.OrderNo), logger.Field("status", 2))
|
||||
}
|
||||
// enqueue activation regardless (idempotent handler downstream)
|
||||
payload := queueType.ForthwithActivateOrderPayload{OrderNo: req.OrderNo}
|
||||
bytes, _ := json.Marshal(payload)
|
||||
task := asynq.NewTask(queueType.ForthwithActivateOrder, bytes)
|
||||
if _, e := l.svcCtx.Queue.EnqueueContext(l.ctx, task); e != nil {
|
||||
// non-fatal
|
||||
l.Errorw("enqueue activate task error", logger.Field("error", e.Error()))
|
||||
} else {
|
||||
l.Infow("已加入订单激活队列", logger.Field("orderNo", req.OrderNo))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
l.Errorw("绑定事务提交失败", logger.Field("error", err.Error()))
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "insert error: %v", err.Error())
|
||||
}
|
||||
l.Infow("绑定完成", logger.Field("userId", u.Id), logger.Field("tier", tier), logger.Field("expiresAt", exp.Unix()))
|
||||
return &types.AttachAppleTransactionResponse{
|
||||
ExpiresAt: exp.Unix(),
|
||||
Tier: tier,
|
||||
}, 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,170 @@
|
||||
package apple
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
iapmodel "github.com/perfect-panel/server/internal/model/iap/apple"
|
||||
"github.com/perfect-panel/server/internal/model/payment"
|
||||
"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"
|
||||
)
|
||||
|
||||
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)
|
||||
// Try to load payment config to get API credentials
|
||||
var apiCfg iapapple.ServerAPIConfig
|
||||
// We need to find *any* apple payment config to get credentials.
|
||||
// In most cases, there is only one apple payment method.
|
||||
// We can try to find by platform "apple"
|
||||
payMethods, err := l.svcCtx.PaymentModel.FindListByPlatform(l.ctx, "apple")
|
||||
if err == nil && len(payMethods) > 0 {
|
||||
// Use the first available config
|
||||
pay := payMethods[0]
|
||||
var cfg payment.AppleIAPConfig
|
||||
if err := cfg.Unmarshal([]byte(pay.Config)); err == nil {
|
||||
apiCfg = iapapple.ServerAPIConfig{
|
||||
KeyID: cfg.KeyID,
|
||||
IssuerID: cfg.IssuerID,
|
||||
PrivateKey: cfg.PrivateKey,
|
||||
Sandbox: cfg.Sandbox,
|
||||
}
|
||||
// Fix private key format if needed (same as in attachTransactionByIdLogic)
|
||||
if !strings.Contains(apiCfg.PrivateKey, "\n") && strings.Contains(apiCfg.PrivateKey, "BEGIN PRIVATE KEY") {
|
||||
apiCfg.PrivateKey = strings.ReplaceAll(apiCfg.PrivateKey, " ", "\n")
|
||||
apiCfg.PrivateKey = strings.ReplaceAll(apiCfg.PrivateKey, "-----BEGIN\nPRIVATE\nKEY-----", "-----BEGIN PRIVATE KEY-----")
|
||||
apiCfg.PrivateKey = strings.ReplaceAll(apiCfg.PrivateKey, "-----END\nPRIVATE\nKEY-----", "-----END PRIVATE KEY-----")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback credentials if missing (dev/debug)
|
||||
if apiCfg.PrivateKey == "" {
|
||||
apiCfg.PrivateKey = `-----BEGIN PRIVATE KEY-----
|
||||
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgsVDj0g/D7uNCm8aC
|
||||
E4TuaiDT4Pgb1IuuZ69YdGNvcAegCgYIKoZIzj0DAQehRANCAARObgGumaESbPMM
|
||||
SIRDAVLcWemp0fMlnfDE4EHmqcD58arEJWsr3aWEhc4BHocOUIGjko0cVWGchrFa
|
||||
/T/KG1tr
|
||||
-----END PRIVATE KEY-----`
|
||||
apiCfg.KeyID = "2C4X3HVPM8"
|
||||
}
|
||||
if apiCfg.IssuerID == "" {
|
||||
apiCfg.IssuerID = "34f54810-5118-4b7f-8069-c8c1e012b7a9"
|
||||
}
|
||||
// Try to get BundleID
|
||||
if apiCfg.BundleID == "" && l.svcCtx.Config.Site.CustomData != "" {
|
||||
var customData struct {
|
||||
IapBundleId string `json:"iapBundleId"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(l.svcCtx.Config.Site.CustomData), &customData)
|
||||
apiCfg.BundleID = customData.IapBundleId
|
||||
}
|
||||
|
||||
return l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
||||
for _, txID := range req.Transactions {
|
||||
// 1. Try to verify as JWS first (if client sends JWS)
|
||||
var txp *iapapple.TransactionPayload
|
||||
var err error
|
||||
|
||||
// Try to parse as JWS
|
||||
if len(txID) > 50 && (strings.Contains(txID, ".") || strings.HasPrefix(txID, "ey")) {
|
||||
txp, err = iapapple.VerifyTransactionJWS(txID)
|
||||
} else {
|
||||
// 2. If not JWS, treat as TransactionID and fetch from Apple
|
||||
var jws string
|
||||
jws, err = iapapple.GetTransactionInfo(apiCfg, txID)
|
||||
if err == nil {
|
||||
txp, err = iapapple.VerifyTransactionJWS(jws)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil || txp == nil {
|
||||
l.Errorw("restore: invalid transaction", logger.Field("id", txID), logger.Field("error", err))
|
||||
continue
|
||||
}
|
||||
|
||||
m, ok := pm.Items[txp.ProductId]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// Check if already processed
|
||||
_, e := iapmodel.NewModel(l.svcCtx.DB, l.svcCtx.Redis).FindByOriginalId(l.ctx, txp.OriginalTransactionId)
|
||||
if e == nil {
|
||||
continue // Already processed, skip
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// Try to link with existing order if possible (Best Effort)
|
||||
// Strategy 1: appAccountToken (from JWS) -> OrderNo (UUID)
|
||||
if txp.AppAccountToken != "" {
|
||||
// appAccountToken is usually a UUID string
|
||||
// Try to find order by parsing UUID or matching direct orderNo (if we stored it as uuid)
|
||||
// Since our orderNo is string, we can try to search it.
|
||||
// However, AppAccountToken is strictly UUID format. If our orderNo is not UUID, we might need a mapping.
|
||||
// Assuming orderNo -> UUID conversion was consistent on client side.
|
||||
// Here we just try to update if we find an unpaid order with this ID (if orderNo was used as appAccountToken)
|
||||
_ = l.svcCtx.OrderModel.UpdateOrderStatus(l.ctx, txp.AppAccountToken, 2, tx)
|
||||
}
|
||||
|
||||
// Strategy 2: If we had a way to pass orderNo in restore request (optional field in future), we could use it here.
|
||||
// But for now, we only rely on appAccountToken or just skip order linking.
|
||||
|
||||
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
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user