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
-87
View File
@@ -1,87 +0,0 @@
package appleiap
import (
"crypto/ecdsa"
"crypto/elliptic"
"encoding/base64"
"encoding/json"
"errors"
"math/big"
"net/http"
"sync"
"time"
)
type jwk struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Crv string `json:"crv"`
X string `json:"x"`
Y string `json:"y"`
}
type jwks struct {
Keys []jwk `json:"keys"`
}
type cacheEntry struct {
keys map[string]*ecdsa.PublicKey
exp time.Time
}
var (
mu sync.Mutex
cache = map[string]*cacheEntry{}
)
func endpoint(env string) string {
if env == "sandbox" {
return "https://api.storekit-sandbox.itunes.apple.com/inApps/v1/keys"
}
return "https://api.storekit.itunes.apple.com/inApps/v1/keys"
}
func fetch(env string) (map[string]*ecdsa.PublicKey, error) {
resp, err := http.Get(endpoint(env))
if err != nil {
return nil, err
}
defer resp.Body.Close()
var set jwks
if err := json.NewDecoder(resp.Body).Decode(&set); err != nil {
return nil, err
}
m := make(map[string]*ecdsa.PublicKey)
for _, k := range set.Keys {
if k.Kty != "EC" || k.Crv != "P-256" || k.X == "" || k.Y == "" || k.Kid == "" {
continue
}
xb, err := base64.RawURLEncoding.DecodeString(k.X)
if err != nil { continue }
yb, err := base64.RawURLEncoding.DecodeString(k.Y)
if err != nil { continue }
var x, y big.Int
x.SetBytes(xb)
y.SetBytes(yb)
m[k.Kid] = &ecdsa.PublicKey{Curve: elliptic.P256(), X: &x, Y: &y}
}
if len(m) == 0 {
return nil, errors.New("empty jwks")
}
return m, nil
}
func GetKey(env, kid string) (*ecdsa.PublicKey, error) {
mu.Lock()
defer mu.Unlock()
c := cache[env]
if c == nil || time.Now().After(c.exp) {
keys, err := fetch(env)
if err != nil { return nil, err }
cache[env] = &cacheEntry{ keys: keys, exp: time.Now().Add(10 * time.Minute) }
c = cache[env]
}
k := c.keys[kid]
if k == nil { return nil, errors.New("key not found") }
return k, nil
}
-29
View File
@@ -1,29 +0,0 @@
package appleiap
import (
"errors"
"github.com/golang-jwt/jwt/v5"
)
func verifyWithEnv(env, token string) (jwt.MapClaims, error) {
parsed, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
h, ok := t.Header["kid"].(string)
if !ok { return nil, errors.New("kid missing") }
return GetKey(env, h)
})
if err != nil { return nil, err }
if !parsed.Valid { return nil, errors.New("invalid jws") }
c, ok := parsed.Claims.(jwt.MapClaims)
if !ok { return nil, errors.New("claims invalid") }
return c, nil
}
func VerifyWithEnv(env, token string) (jwt.MapClaims, error) { return verifyWithEnv(env, token) }
func VerifyAutoEnv(token string) (jwt.MapClaims, string, error) {
c, err := verifyWithEnv("production", token)
if err == nil { return c, "production", nil }
c2, err2 := verifyWithEnv("sandbox", token)
if err2 == nil { return c2, "sandbox", nil }
return nil, "", err
}
+6
View File
@@ -0,0 +1,6 @@
package apple
import "errors"
var ErrInvalidJWS = errors.New("invalid jws")
+55
View File
@@ -0,0 +1,55 @@
package apple
import (
"encoding/base64"
"encoding/json"
"strings"
"time"
)
func ParseTransactionJWS(jws string) (*TransactionPayload, error) {
parts := strings.Split(jws, ".")
if len(parts) != 3 {
return nil, ErrInvalidJWS
}
payloadB64 := parts[1]
// add padding if required
switch len(payloadB64) % 4 {
case 2:
payloadB64 += "=="
case 3:
payloadB64 += "="
}
data, err := base64.RawURLEncoding.DecodeString(payloadB64)
if err != nil {
return nil, err
}
var raw map[string]interface{}
if err = json.Unmarshal(data, &raw); err != nil {
return nil, err
}
var resp TransactionPayload
if v, ok := raw["bundleId"].(string); ok {
resp.BundleId = v
}
if v, ok := raw["productId"].(string); ok {
resp.ProductId = v
}
if v, ok := raw["transactionId"].(string); ok {
resp.TransactionId = v
}
if v, ok := raw["originalTransactionId"].(string); ok {
resp.OriginalTransactionId = v
}
if v, ok := raw["purchaseDate"].(float64); ok {
resp.PurchaseDate = time.UnixMilli(int64(v))
} else if v, ok := raw["purchaseDate"].(int64); ok {
resp.PurchaseDate = time.UnixMilli(v)
}
if v, ok := raw["revocationDate"].(float64); ok {
t := time.UnixMilli(int64(v))
resp.RevocationDate = &t
}
return &resp, nil
}
+35
View File
@@ -0,0 +1,35 @@
package apple
import (
"encoding/base64"
"encoding/json"
"testing"
"time"
)
func TestParseTransactionJWS(t *testing.T) {
payload := map[string]interface{}{
"bundleId": "co.airoport.app.ios",
"productId": "com.airport.vpn.pass.30d",
"transactionId": "1000000000001",
"originalTransactionId": "1000000000000",
"purchaseDate": float64(time.Now().UnixMilli()),
}
data, _ := json.Marshal(payload)
b64 := base64.RawURLEncoding.EncodeToString(data)
jws := "header." + b64 + ".signature"
p, err := ParseTransactionJWS(jws)
if err != nil {
t.Fatalf("parse error: %v", err)
}
if p.ProductId != payload["productId"] {
t.Fatalf("productId not match")
}
if p.BundleId != payload["bundleId"] {
t.Fatalf("bundleId not match")
}
if p.OriginalTransactionId != payload["originalTransactionId"] {
t.Fatalf("originalTransactionId not match")
}
}
+39
View File
@@ -0,0 +1,39 @@
package apple
import (
"encoding/json"
"time"
)
type ProductMapping struct {
DurationDays int64 `json:"durationDays"`
Tier string `json:"tier"`
Description string `json:"description"`
PriceText string `json:"priceText"`
SubscribeId int64 `json:"subscribeId"`
}
type ProductMap struct {
Items map[string]ProductMapping `json:"iapProductMap"`
}
func ParseProductMap(customData string) (*ProductMap, error) {
if customData == "" {
return &ProductMap{Items: map[string]ProductMapping{}}, nil
}
var obj ProductMap
if err := json.Unmarshal([]byte(customData), &obj); err != nil {
return &ProductMap{Items: map[string]ProductMapping{}}, nil
}
if obj.Items == nil {
obj.Items = map[string]ProductMapping{}
}
return &obj, nil
}
func CalcExpire(start time.Time, days int64) time.Time {
if days <= 0 {
return time.UnixMilli(0)
}
return start.Add(time.Duration(days) * 24 * time.Hour)
}
+13
View File
@@ -0,0 +1,13 @@
package apple
import "time"
type TransactionPayload struct {
BundleId string `json:"bundleId"`
ProductId string `json:"productId"`
TransactionId string `json:"transactionId"`
OriginalTransactionId string `json:"originalTransactionId"`
PurchaseDate time.Time `json:"purchaseDate"`
RevocationDate *time.Time`json:"revocationDate"`
}
+1 -13
View File
@@ -10,7 +10,6 @@ const (
EPay
Balance
CryptoSaaS
AppleIAP
UNSUPPORTED Platform = -1
)
@@ -20,7 +19,6 @@ var platformNames = map[string]Platform{
"AlipayF2F": AlipayF2F,
"EPay": EPay,
"balance": Balance,
"AppleIAP": AppleIAP,
"unsupported": UNSUPPORTED,
}
@@ -49,7 +47,7 @@ func GetSupportedPlatforms() []types.PlatformInfo {
"public_key": "Publishable key",
"secret_key": "Secret key",
"webhook_secret": "Webhook secret",
"payment": "Payment Method, only supported card/alipay/wechat_pay/apple_pay",
"payment": "Payment Method, only supported card/alipay/wechat_pay",
},
},
{
@@ -82,15 +80,5 @@ func GetSupportedPlatforms() []types.PlatformInfo {
"secret_key": "Secret Key",
},
},
{
Platform: AppleIAP.String(),
PlatformUrl: "https://developer.apple.com/help/app-store-connect/",
PlatformFieldDescription: map[string]string{
"issuer_id": "App Store Connect Issuer ID",
"key_id": "App Store Connect Key ID",
"private_key": "Private Key (ES256)",
"environment": "Environment: Sandbox/Production",
},
},
}
}