feat(支付): 新增Apple IAP支付支持
Build docker and publish / build (20.15.1) (push) Has been cancelled

实现Apple应用内购支付功能,包括:
1. 新增AppleIAP和ApplePay支付平台枚举
2. 添加IAP验证接口/v1/public/iap/verify处理初购验证
3. 实现Apple服务器通知处理逻辑/v1/iap/notifications
4. 新增JWS验签和JWKS公钥缓存功能
5. 复用现有订单系统处理IAP支付订单

相关文档已更新,包含接入方案和实现细节
This commit is contained in:
2025-12-09 00:53:25 -08:00
parent 4b6fcb338e
commit d95911d6bd
15 changed files with 654 additions and 34 deletions
+10 -5
View File
@@ -8,10 +8,15 @@ import (
)
func RegisterNotifyHandlers(router *gin.Engine, serverCtx *svc.ServiceContext) {
group := router.Group("/v1/notify/")
group.Use(middleware.NotifyMiddleware(serverCtx))
{
group.Any("/:platform/:token", notify.PaymentNotifyHandler(serverCtx))
}
group := router.Group("/v1/notify/")
group.Use(middleware.NotifyMiddleware(serverCtx))
{
group.Any(":platform/:token", notify.PaymentNotifyHandler(serverCtx))
}
iap := router.Group("/v1/iap")
{
iap.POST("/notifications", notify.AppleIAPNotifyHandler(serverCtx))
}
}
@@ -0,0 +1,20 @@
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"
)
// 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)
}
}
@@ -39,7 +39,7 @@ func PaymentNotifyHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
return
}
c.String(http.StatusOK, "%s", "success")
case payment.Stripe:
case payment.Stripe, payment.ApplePay:
l := notify.NewStripeNotifyLogic(c.Request.Context(), svcCtx)
if err := l.StripeNotify(c.Request, c.Writer); err != nil {
result.HttpResult(c, nil, err)
@@ -0,0 +1,29 @@
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)
}
}
+11 -3
View File
@@ -26,7 +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"
publicDocument "github.com/perfect-panel/server/internal/handler/public/document"
publicIAP "github.com/perfect-panel/server/internal/handler/public/iap"
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"
@@ -671,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))
{
@@ -680,7 +681,14 @@ 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))
@@ -0,0 +1,134 @@
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
}
+104
View File
@@ -0,0 +1,104 @@
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
}
@@ -86,7 +86,18 @@ func (l *PurchaseCheckoutLogic) PurchaseCheckout(req *types.CheckoutOrderRequest
case paymentPlatform.Stripe:
// Process Stripe payment - creates payment sheet for client-side processing
stripePayment, err := l.stripePayment(paymentConfig.Config, orderInfo, "")
stripePayment, err := l.stripePayment(paymentConfig.Config, orderInfo, "", "")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "stripePayment error: %v", err.Error())
}
resp = &types.CheckoutOrderResponse{
Type: "stripe", // Client should use Stripe SDK
Stripe: stripePayment,
}
case paymentPlatform.ApplePay:
// Process Apple Pay payment - uses Stripe with 'card' method
stripePayment, err := l.stripePayment(paymentConfig.Config, orderInfo, "", "card")
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "stripePayment error: %v", err.Error())
}
@@ -208,7 +219,7 @@ func (l *PurchaseCheckoutLogic) alipayF2fPayment(pay *payment.Payment, info *ord
// stripePayment processes Stripe payment by creating a payment sheet
// It supports various payment methods including WeChat Pay and Alipay through Stripe
func (l *PurchaseCheckoutLogic) stripePayment(config string, info *order.Order, identifier string) (*types.StripePayment, error) {
func (l *PurchaseCheckoutLogic) stripePayment(config string, info *order.Order, identifier string, forceMethod string) (*types.StripePayment, error) {
// Parse Stripe configuration from payment settings
stripeConfig := &payment.StripeConfig{}
@@ -217,6 +228,10 @@ func (l *PurchaseCheckoutLogic) stripePayment(config string, info *order.Order,
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Unmarshal error: %s", err.Error())
}
if forceMethod != "" {
stripeConfig.Payment = forceMethod
}
// Initialize Stripe client with API credentials
client := stripe.NewClient(stripe.Config{
SecretKey: stripeConfig.SecretKey,
+38 -20
View File
@@ -12,23 +12,25 @@ import (
var _ Model = (*customOrderModel)(nil)
var (
cacheOrderIdPrefix = "cache:order:id:"
cacheOrderNoPrefix = "cache:order:no:"
cacheOrderIdPrefix = "cache:order:id:"
cacheOrderNoPrefix = "cache:order:no:"
cacheOrderTradePrefix = "cache:order:trade:"
)
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)
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)
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
}
customOrderModel struct {
*defaultOrderModel
@@ -60,12 +62,14 @@ 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)
cacheKeys := []string{
orderIdKey,
orderNoKey,
}
return cacheKeys
orderNoKey := fmt.Sprintf("%s%v", cacheOrderNoPrefix, data.OrderNo)
tradeNoKey := fmt.Sprintf("%s%v", cacheOrderTradePrefix, data.TradeNo)
cacheKeys := []string{
orderIdKey,
orderNoKey,
tradeNoKey,
}
return cacheKeys
}
func (m *defaultOrderModel) Insert(ctx context.Context, data *Order, tx ...*gorm.DB) error {
@@ -106,6 +110,20 @@ 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) {
+12 -3
View File
@@ -72,9 +72,18 @@ type AppUserSubscbribeNode struct {
}
type AppleLoginCallbackRequest struct {
Code string `form:"code"`
IDToken string `form:"id_token"`
State string `form:"state"`
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"`
}
type Application struct {