Documentation
¶
Overview ¶
Package storeverify is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package storeverify is the NSGo-free server side of App Store in-app purchases: it verifies StoreKit 2 signed transactions (JWS) and App Store Server Notifications V2 payloads against Apple Root CA - G3 and Apple's certificate OIDs, serves an HTTP notification webhook matching Apple's retry semantics, and signs subscription promotional offers with an In-App Purchase key (ES256).
Index ¶
- Constants
- Variables
- func AppleRootCAG3() *x509.Certificate
- func DefaultRoots() *x509.CertPool
- type AppStore
- func (a *AppStore) NotificationHandler(onNotification func(context.Context, Notification) error) http.Handler
- func (a *AppStore) SignPromotionalOffer(key OfferKey, productID, offerID, appAccountToken string) (PromotionalOffer, error)
- func (a *AppStore) VerifyNotification(signedPayload string) (Notification, error)
- func (a *AppStore) VerifyRenewalInfo(jws string) (RenewalInfo, error)
- func (a *AppStore) VerifyTransaction(jws string) (Transaction, error)
- type Environment
- type Notification
- type NotificationSummary
- type OfferKey
- type PromotionalOffer
- type RenewalInfo
- type Transaction
Examples ¶
Constants ¶
const ( NotificationConsumptionRequest = "CONSUMPTION_REQUEST" NotificationDidChangeRenewalPref = "DID_CHANGE_RENEWAL_PREF" NotificationDidChangeRenewalStatus = "DID_CHANGE_RENEWAL_STATUS" NotificationDidFailToRenew = "DID_FAIL_TO_RENEW" NotificationDidRenew = "DID_RENEW" NotificationExpired = "EXPIRED" NotificationExternalPurchaseToken = "EXTERNAL_PURCHASE_TOKEN" NotificationGracePeriodExpired = "GRACE_PERIOD_EXPIRED" NotificationOfferRedeemed = "OFFER_REDEEMED" NotificationOneTimeCharge = "ONE_TIME_CHARGE" NotificationPriceIncrease = "PRICE_INCREASE" NotificationRefund = "REFUND" NotificationRefundDeclined = "REFUND_DECLINED" NotificationRefundReversed = "REFUND_REVERSED" NotificationRenewalExtended = "RENEWAL_EXTENDED" NotificationRenewalExtension = "RENEWAL_EXTENSION" NotificationRevoke = "REVOKE" NotificationSubscribed = "SUBSCRIBED" NotificationTest = "TEST" )
App Store Server Notifications V2 notification types.
const ( SubtypeAccepted = "ACCEPTED" SubtypeAutoRenewDisabled = "AUTO_RENEW_DISABLED" SubtypeAutoRenewEnabled = "AUTO_RENEW_ENABLED" SubtypeBillingRecovery = "BILLING_RECOVERY" SubtypeBillingRetry = "BILLING_RETRY" SubtypeDowngrade = "DOWNGRADE" SubtypeFailure = "FAILURE" SubtypeGracePeriod = "GRACE_PERIOD" SubtypeInitialBuy = "INITIAL_BUY" SubtypePending = "PENDING" SubtypePriceIncrease = "PRICE_INCREASE" SubtypeProductNotForSale = "PRODUCT_NOT_FOR_SALE" SubtypeResubscribe = "RESUBSCRIBE" SubtypeSummary = "SUMMARY" SubtypeUpgrade = "UPGRADE" SubtypeVoluntary = "VOLUNTARY" )
Common App Store Server Notifications V2 subtypes.
Variables ¶
var ( // ErrInvalidConfig reports a missing or invalid verifier/signer configuration. ErrInvalidConfig = errors.New("storeverify: invalid configuration") // ErrInvalidJWS reports a malformed JWS, unsupported algorithm, corrupt payload or failed signature check. ErrInvalidJWS = errors.New("storeverify: invalid JWS") // ErrInvalidChain reports an x5c certificate chain that is missing, wrong length, missing Apple's OIDs, expired, broken or not anchored in a trusted root. ErrInvalidChain = errors.New("storeverify: invalid certificate chain") // ErrBundleMismatch reports a payload whose bundleId does not match AppStore.BundleID. ErrBundleMismatch = errors.New("storeverify: bundle ID mismatch") // ErrAppAppleIDMismatch reports a payload whose appAppleId does not match AppStore.AppAppleID. ErrAppAppleIDMismatch = errors.New("storeverify: app Apple ID mismatch") // ErrEnvironmentMismatch reports a payload whose environment is not permitted by AppStore.Environments. ErrEnvironmentMismatch = errors.New("storeverify: environment not allowed") // ErrInvalidOffer reports invalid inputs to SignPromotionalOffer or ParseOfferKey. ErrInvalidOffer = errors.New("storeverify: invalid promotional offer") )
Sentinel errors returned (wrapped with context) by AppStore verification and signing methods.
Functions ¶
func AppleRootCAG3 ¶
func AppleRootCAG3() *x509.Certificate
AppleRootCAG3 returns a parsed copy of the embedded Apple Root CA - G3 certificate.
func DefaultRoots ¶
DefaultRoots returns a fresh CertPool containing the embedded Apple Root CA - G3 certificate used by AppStore when AppStore.Roots is nil.
Types ¶
type AppStore ¶
type AppStore struct {
// BundleID is the app's bundle identifier (for example "com.example.game"). Required.
BundleID string
// AppAppleID is the app's numeric identifier in App Store Connect. Required when
// verifying Production notifications, and checked whenever both AppAppleID and
// the payload's appAppleId are non-zero.
AppAppleID int64
// Environments lists the App Store environments accepted by this verifier.
// When empty, only EnvProduction is accepted (fail closed against Sandbox and Xcode).
Environments []Environment
// Roots holds the trusted root certificates for x5c verification.
// When nil, the embedded Apple Root CA - G3 certificate is used.
Roots *x509.CertPool
// Now overrides the current time for certificate checks when a payload carries no
// signedDate and for promotional offer timestamps. Nil uses time.Now.
Now func() time.Time
}
AppStore verifies Apple App Store StoreKit 2 JWS transactions and Server Notifications V2 payloads, and signs subscription promotional offers for one app.
An AppStore value is safe for concurrent use by multiple goroutines once configured.
func (*AppStore) NotificationHandler ¶
func (a *AppStore) NotificationHandler(onNotification func(context.Context, Notification) error) http.Handler
NotificationHandler returns an http.Handler for Apple's App Store Server Notifications V2 POST webhook ({"signedPayload":"<jws>"}).
HTTP status semantics match Apple's delivery and retry contract:
- 200 OK: the notification verified and onNotification returned nil; Apple stops retrying.
- 400 Bad Request: malformed JSON, missing signedPayload, or JWS/chain/bundle/environment verification failure.
- 405 Method Not Allowed: non-POST request.
- 500 Internal Server Error: misconfigured AppStore, nil callback, or onNotification returned an error; Apple retries Production notifications at 1, 12, 24, 48 and 72 hours.
Callbacks must be idempotent on Notification.NotificationUUID because Apple can deliver the same notification more than once on retries or network timeouts.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"github.com/nsgo-dev/game/pkg/online/storeverify"
)
func main() {
verifier := &storeverify.AppStore{
BundleID: "com.example.game",
AppAppleID: 6449012345,
Environments: []storeverify.Environment{storeverify.EnvProduction},
}
mux := http.NewServeMux()
mux.Handle("/webhooks/appstore", verifier.NotificationHandler(func(ctx context.Context, n storeverify.Notification) error {
switch n.NotificationType {
case storeverify.NotificationRefund:
// Revoke n.Transaction.TransactionID for n.Transaction.AppAccountToken.
case storeverify.NotificationDidRenew:
// Extend subscription until n.Transaction.ExpiresDate.
case storeverify.NotificationExpired:
// Mark subscription expired for n.Transaction.AppAccountToken.
}
return nil
}))
fmt.Println(mux != nil)
}
Output: true
func (*AppStore) SignPromotionalOffer ¶
func (a *AppStore) SignPromotionalOffer(key OfferKey, productID, offerID, appAccountToken string) (PromotionalOffer, error)
SignPromotionalOffer signs a StoreKit 2 subscription promotional offer for productID and offerID using Apple's In-App Purchase key (ES256, ASN.1 DER signature).
appAccountToken is the UUID passed to StoreKit (for example accounts.AppAccountToken(accountID)), or "" if the purchase carries no account token; uppercase UUIDs are normalized to lowercase before signing as Apple requires.
Example ¶
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"fmt"
"github.com/nsgo-dev/game/pkg/online/accounts"
"github.com/nsgo-dev/game/pkg/online/storeverify"
)
func main() {
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
panic(err)
}
app := &storeverify.AppStore{
BundleID: "com.example.game",
AppAppleID: 6449012345,
}
key := storeverify.OfferKey{KeyID: "ABC123DEF4", PrivateKey: priv}
token := accounts.AppAccountToken("0123456789abcdef0123456789abcdef")
offer, err := app.SignPromotionalOffer(key, "com.example.pass.monthly", "winback_50", token)
if err != nil {
panic(err)
}
fmt.Println(offer.ID, offer.KeyID, len(offer.Signature) > 0)
}
Output: winback_50 ABC123DEF4 true
func (*AppStore) VerifyNotification ¶
func (a *AppStore) VerifyNotification(signedPayload string) (Notification, error)
VerifyNotification verifies an App Store Server Notification V2 signedPayload JWS, checks its bundle ID, environment and AppAppleID, and independently verifies any nested signedTransactionInfo and signedRenewalInfo JWS payloads.
func (*AppStore) VerifyRenewalInfo ¶
func (a *AppStore) VerifyRenewalInfo(jws string) (RenewalInfo, error)
VerifyRenewalInfo verifies an App Store JWS subscription renewal info payload and returns the decoded RenewalInfo.
func (*AppStore) VerifyTransaction ¶
func (a *AppStore) VerifyTransaction(jws string) (Transaction, error)
VerifyTransaction verifies a StoreKit 2 JWS transaction string against the x5c certificate chain, Apple's OIDs, trusted roots, ES256 signature, BundleID, AppAppleID (when present) and allowed Environments, and returns the decoded Transaction.
type Environment ¶
type Environment string
Environment identifies the App Store environment reported inside a signed transaction, renewal info or notification.
const ( // EnvProduction is the live App Store environment. EnvProduction Environment = "Production" // EnvSandbox is the App Store Sandbox environment (TestFlight and sandbox Apple Accounts). EnvSandbox Environment = "Sandbox" // EnvXcode is Xcode's local StoreKit Testing environment. Never include EnvXcode // in a production server's AppStore.Environments: local Xcode JWS tokens do not // chain to Apple Root CA - G3. EnvXcode Environment = "Xcode" )
type Notification ¶
type Notification struct {
NotificationType string
Subtype string
NotificationUUID string
Version string
SignedDate time.Time
Environment Environment
BundleID string
BundleVersion string
AppAppleID int64
Status int
ConsumptionRequestReason string
// Transaction is the verified inner signedTransactionInfo, or nil when absent (such as TEST notifications).
Transaction *Transaction
// RenewalInfo is the verified inner signedRenewalInfo, or nil when absent.
RenewalInfo *RenewalInfo
// Summary is non-nil for RENEWAL_EXTENSION / SUMMARY notifications.
Summary *NotificationSummary
}
Notification is a verified App Store Server Notification V2 payload, together with its verified inner Transaction and RenewalInfo when present.
type NotificationSummary ¶
type NotificationSummary struct {
ProductID string
RequestIdentifier string
StorefrontCountryCodes []string
SucceededCount int64
FailedCount int64
}
NotificationSummary holds summary fields carried by bulk RENEWAL_EXTENSION / SUMMARY notifications.
type OfferKey ¶
type OfferKey struct {
// KeyID is the key identifier assigned in App Store Connect (typically 10 characters).
KeyID string
// PrivateKey is the ECDSA P-256 private key from the App Store Connect .p8 file.
PrivateKey *ecdsa.PrivateKey
}
OfferKey holds an App Store Connect In-App Purchase key (.p8) used to sign subscription promotional offers with ES256.
type PromotionalOffer ¶
type PromotionalOffer struct {
ID string `json:"id"`
KeyID string `json:"keyId"`
Nonce string `json:"nonce"`
Signature []byte `json:"signature"`
Timestamp int64 `json:"timestamp"`
}
PromotionalOffer is a server-signed App Store subscription promotional offer. Its fields and JSON tags match NSGo's core.PromotionalOffer (without importing NSGo) so a game server can marshal it as JSON and a client can unmarshal it directly into core.PromotionalOffer for liveops.Purchases.BuyOffer.
type RenewalInfo ¶
type RenewalInfo struct {
OriginalTransactionID string
AutoRenewProductID string
ProductID string
AutoRenewStatus int
ExpirationIntent int
GracePeriodExpiresDate time.Time
IsInBillingRetryPeriod bool
OfferIdentifier string
OfferType int
OfferDiscountType string
PriceIncreaseStatus *int
SignedDate time.Time
Environment Environment
RecentSubscriptionStartDate time.Time
RenewalDate time.Time
RenewalPrice int64
Currency string
EligibleWinBackOfferIDs []string
}
RenewalInfo is a verified App Store subscription renewal info decoded from a JWS payload.
type Transaction ¶
type Transaction struct {
TransactionID string
OriginalTransactionID string
WebOrderLineItemID string
BundleID string
ProductID string
SubscriptionGroupID string
PurchaseDate time.Time
OriginalPurchaseDate time.Time
ExpiresDate time.Time
RevocationDate time.Time
SignedDate time.Time
Quantity int
Type string
AppAccountToken string
InAppOwnershipType string
Environment Environment
TransactionReason string
Storefront string
StorefrontID string
Price int64
Currency string
OfferType int
OfferIdentifier string
OfferDiscountType string
RevocationReason *int
IsUpgraded bool
AppAppleID int64
}
Transaction is a verified App Store StoreKit 2 transaction decoded from a JWS payload.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package wechatpay is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
|
Package wechatpay is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/. |
|
pgstore
Package pgstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
|
Package pgstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/. |
|
sqlitestore
Package sqlitestore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
|
Package sqlitestore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/. |
|
sqlstore
Package sqlstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
|
Package sqlstore is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/. |
|
storetest
Package storetest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
|
Package storetest is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/. |