api

package
v0.0.0-...-0481e0b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 15, 2023 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TransactionReasonPurchase = "PURCHASE"
	TransactionReasonRenewal  = "RENEWAL"
)
View Source
const (
	UndeclaredExtendReasonCode = iota
	CustomerSatisfaction
	OtherReasons
	ServiceIssueOrOutage
)
View Source
const (
	HostSandBox    = "https://api.storekit-sandbox.itunes.apple.com"
	HostProduction = "https://api.storekit.itunes.apple.com"

	PathLookUp                              = "/inApps/v1/lookup/{orderId}"
	PathTransactionHistory                  = "/inApps/v1/history/{originalTransactionId}"
	PathTransactionInfo                     = "/inApps/v1/transactions/{transactionId}"
	PathRefundHistory                       = "/inApps/v2/refund/lookup/{originalTransactionId}"
	PathGetALLSubscriptionStatus            = "/inApps/v1/subscriptions/{originalTransactionId}"
	PathConsumptionInfo                     = "/inApps/v1/transactions/consumption/{originalTransactionId}"
	PathExtendSubscriptionRenewalDate       = "/inApps/v1/subscriptions/extend/{originalTransactionId}"
	PathExtendSubscriptionRenewalDateForAll = "/inApps/v1/subscriptions/extend/mass/"
	PathGetStatusOfSubscriptionRenewalDate  = "/inApps/v1/subscriptions/extend/mass/{productId}/{requestIdentifier}"
	PathGetNotificationHistory              = "/inApps/v1/notifications/history"
	PathRequestTestNotification             = "/inApps/v1/notifications/test"
	PathGetTestNotificationStatus           = "/inApps/v1/notifications/test/{testNotificationToken}"
)

Variables

View Source
var (
	// Retryable errors
	AccountNotFoundRetryableError               = newError(4040002, "Account not found. Please try again.")
	AppNotFoundRetryableError                   = newError(4040004, "App not found. Please try again.")
	GeneralInternalRetryableError               = newError(5000001, "An unknown error occurred. Please try again.")
	OriginalTransactionIdNotFoundRetryableError = newError(4040006, "Original transaction id not found. Please try again.")
	// Errors
	AccountNotFoundError                             = newError(4040001, "Account not found.")
	AppNotFoundError                                 = newError(4040003, "App not found.")
	FamilySharedSubscriptionExtensionIneligibleError = newError(4030007, "Subscriptions that users obtain through Family Sharing can't get a renewal date extension directly.")
	GeneralInternalError                             = newError(5000000, "An unknown error occurred.")
	GeneralBadRequestError                           = newError(4000000, "Bad request.")
	InvalidAppIdentifierError                        = newError(4000002, "Invalid request app identifier.")
	InvalidEmptyStorefrontCountryCodeListError       = newError(4000027, "Invalid request. If provided, the list of storefront country codes must not be empty.")
	InvalidExtendByDaysError                         = newError(4000009, "Invalid extend by days value.")
	InvalidExtendReasonCodeError                     = newError(4000010, "Invalid extend reason code.")
	InvalidOriginalTransactionIdError                = newError(4000008, "Invalid original transaction id.")
	InvalidRequestIdentifierError                    = newError(4000011, "Invalid request identifier.")
	InvalidRequestRevisionError                      = newError(4000005, "Invalid request revision.")
	InvalidRevokedError                              = newError(4000030, "Invalid request. The revoked parameter is invalid.")
	InvalidStatusError                               = newError(4000031, "Invalid request. The status parameter is invalid.")
	InvalidStorefrontCountryCodeError                = newError(4000028, "Invalid request. A storefront country code was invalid.")
	InvalidTransactionIdError                        = newError(4000006, "Invalid transaction id.")
	OriginalTransactionIdNotFoundError               = newError(4040005, "Original transaction id not found.")
	RateLimitExceededError                           = newError(4290000, "Rate limit exceeded.")
	StatusRequestNotFoundError                       = newError(4040009, "The server didn't find a subscription-renewal-date extension request for this requestIdentifier and productId combination.")
	SubscriptionExtensionIneligibleError             = newError(4030004, "Forbidden - subscription state ineligible for extension.")
	SubscriptionMaxExtensionError                    = newError(4030005, "Forbidden - subscription has reached maximum extension count.")
	TransactionIdNotFoundError                       = newError(4040010, "Transaction id not found.")
	// Notification test and history errors
	InvalidEndDateError                     = newError(4000016, "Invalid request. The end date is not a timestamp value represented in milliseconds.")
	InvalidNotificationTypeError            = newError(4000018, "Invalid request. The notification type or subtype is invalid.")
	InvalidPaginationTokenError             = newError(4000014, "Invalid request. The pagination token is invalid.")
	InvalidStartDateError                   = newError(4000015, "Invalid request. The start date is not a timestamp value represented in milliseconds.")
	InvalidTestNotificationTokenError       = newError(4000020, "Invalid request. The test notification token is invalid.")
	InvalidInAppOwnershipTypeError          = newError(4000026, "Invalid request. The in-app ownership type parameter is invalid.")
	InvalidProductIdError                   = newError(4000023, "Invalid request. The product id parameter is invalid.")
	InvalidProductTypeError                 = newError(4000022, "Invalid request. The product type parameter is invalid.")
	InvalidSortError                        = newError(4000021, "Invalid request. The sort parameter is invalid.")
	InvalidSubscriptionGroupIdentifierError = newError(4000024, "Invalid request. The subscription group identifier parameter is invalid.")
	MultipleFiltersSuppliedError            = newError(4000019, "Invalid request. Supply either a transaction id or a notification type, but not both.")
	PaginationTokenExpiredError             = newError(4000017, "Invalid request. The pagination token is expired.")
	ServerNotificationURLNotFoundError      = newError(4040007, "No App Store Server Notification URL found for provided app. Check that a URL is configured in App Store Connect for this environment.")
	StartDateAfterEndDateError              = newError(4000013, "Invalid request. The end date precedes the start date or the dates are the same.")
	StartDateTooFarInPastError              = newError(4000012, "Invalid request. The start date is earlier than the allowed start date.")
	TestNotificationNotFoundError           = newError(4040008, "Either the test notification token is expired or the notification and status are not yet available.")
)

All Error lists in https://developer.apple.com/documentation/appstoreserverapi/error_codes.

View Source
var (
	ErrAuthKeyInvalidPem  = errors.New("token: AuthKey must be a valid .p8 PEM file")
	ErrAuthKeyInvalidType = errors.New("token: AuthKey must be of type ecdsa.PrivateKey")
)

Authorize Tokens For App Store Server API Request Doc: https://developer.apple.com/documentation/appstoreserverapi/generating_tokens_for_api_requests

Functions

This section is empty.

Types

type Cert

type Cert struct {
}

type ConsumptionRequestBody

type ConsumptionRequestBody struct {
	AccountTenure            int    `json:"accountTenure"`
	AppAccountToken          string `json:"appAccountToken"`
	ConsumptionStatus        int    `json:"consumptionStatus"`
	CustomerConsented        bool   `json:"customerConsented"`
	DeliveryStatus           int    `json:"deliveryStatus"`
	LifetimeDollarsPurchased int    `json:"lifetimeDollarsPurchased"`
	LifetimeDollarsRefunded  int    `json:"lifetimeDollarsRefunded"`
	Platform                 int    `json:"platform"`
	PlayTime                 int    `json:"playTime"`
	SampleContentProvided    bool   `json:"sampleContentProvided"`
	UserStatus               int    `json:"userStatus"`
}

ConsumptionRequestBody https://developer.apple.com/documentation/appstoreserverapi/consumptionrequest

type Error

type Error struct {
	// contains filtered or unexported fields
}

func (*Error) As

func (e *Error) As(target interface{}) bool

func (*Error) Error

func (e *Error) Error() string

func (*Error) ErrorCode

func (e *Error) ErrorCode() int

func (*Error) ErrorMessage

func (e *Error) ErrorMessage() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Retryable

func (e *Error) Retryable() bool

type ExtendRenewalDateRequest

type ExtendRenewalDateRequest struct {
	ExtendByDays      int              `json:"extendByDays"`
	ExtendReasonCode  ExtendReasonCode `json:"extendReasonCode"`
	RequestIdentifier string           `json:"requestIdentifier"`
}

ExtendRenewalDateRequest https://developer.apple.com/documentation/appstoreserverapi/extendrenewaldaterequest

type FirstSendAttemptResult

type FirstSendAttemptResult string

https://developer.apple.com/documentation/appstoreserverapi/firstsendattemptresult

const (
	FirstSendAttemptResultSuccess                     FirstSendAttemptResult = "SUCCESS"
	FirstSendAttemptResultCircularRedirect            FirstSendAttemptResult = "CIRCULAR_REDIRECT"
	FirstSendAttemptResultInvalidResponse             FirstSendAttemptResult = "INVALID_RESPONSE"
	FirstSendAttemptResultNoResponse                  FirstSendAttemptResult = "NO_RESPONSE"
	FirstSendAttemptResultOther                       FirstSendAttemptResult = "OTHER"
	FirstSendAttemptResultPrematureClose              FirstSendAttemptResult = "PREMATURE_CLOSE"
	FirstSendAttemptResultSocketIssue                 FirstSendAttemptResult = "SOCKET_ISSUE"
	FirstSendAttemptResultTimedOut                    FirstSendAttemptResult = "TIMED_OUT"
	FirstSendAttemptResultTlsIssue                    FirstSendAttemptResult = "TLS_ISSUE"
	FirstSendAttemptResultUnsupportedCharset          FirstSendAttemptResult = "UNSUPPORTED_CHARSET"
	FirstSendAttemptResultUnsupportedHTTPRESPONSECODE FirstSendAttemptResult = "UNSUCCESSFUL_HTTP_RESPONSE_CODE"
)

type HistoryResponse

type HistoryResponse struct {
	AppAppleId         int      `json:"appAppleId"`
	BundleId           string   `json:"bundleId"`
	Environment        string   `json:"environment"`
	HasMore            bool     `json:"hasMore"`
	Revision           string   `json:"revision"`
	SignedTransactions []string `json:"signedTransactions"`
}

HistoryResponse https://developer.apple.com/documentation/appstoreserverapi/historyresponse

type IAPType

type IAPType string

IAPType https://developer.apple.com/documentation/appstoreserverapi/type

const (
	AutoRenewable IAPType = "Auto-Renewable Subscription"
	NonConsumable IAPType = "Non-Consumable"
	Consumable    IAPType = "Consumable"
	NonRenewable  IAPType = "Non-Renewing Subscription"
)

type JWSDecodedHeader

type JWSDecodedHeader struct {
	Alg string   `json:"alg,omitempty"`
	Kid string   `json:"kid,omitempty"`
	X5C []string `json:"x5c,omitempty"`
}

JWSDecodedHeader https://developer.apple.com/documentation/appstoreserverapi/jwsdecodedheader

type JWSRenewalInfoDecodedPayload

type JWSRenewalInfoDecodedPayload struct {
}

type JWSTransaction

type JWSTransaction struct {
	TransactionID               string            `json:"transactionId,omitempty"`
	OriginalTransactionId       string            `json:"originalTransactionId,omitempty"`
	WebOrderLineItemId          string            `json:"webOrderLineItemId,omitempty"`
	BundleID                    string            `json:"bundleId,omitempty"`
	ProductID                   string            `json:"productId,omitempty"`
	SubscriptionGroupIdentifier string            `json:"subscriptionGroupIdentifier,omitempty"`
	PurchaseDate                int64             `json:"purchaseDate,omitempty"`
	OriginalPurchaseDate        int64             `json:"originalPurchaseDate,omitempty"`
	ExpiresDate                 int64             `json:"expiresDate,omitempty"`
	Quantity                    int64             `json:"quantity,omitempty"`
	Type                        IAPType           `json:"type,omitempty"`
	AppAccountToken             string            `json:"appAccountToken,omitempty"`
	InAppOwnershipType          string            `json:"inAppOwnershipType,omitempty"`
	SignedDate                  int64             `json:"signedDate,omitempty"`
	OfferType                   int64             `json:"offerType,omitempty"`
	OfferIdentifier             string            `json:"offerIdentifier,omitempty"`
	RevocationDate              int64             `json:"revocationDate,omitempty"`
	RevocationReason            int               `json:"revocationReason,omitempty"`
	IsUpgraded                  bool              `json:"isUpgraded,omitempty"`
	Storefront                  string            `json:"storefront"`
	StorefrontId                string            `json:"storefrontId"`
	TransactionReason           TransactionReason `json:"transactionReason"`
}

JWSTransaction https://developer.apple.com/documentation/appstoreserverapi/jwstransaction

func (JWSTransaction) Valid

func (J JWSTransaction) Valid() error

type LastTransactionsItem

type LastTransactionsItem struct {
	OriginalTransactionId string `json:"originalTransactionId"`
	Status                int    `json:"status"`
	SignedRenewalInfo     string `json:"signedRenewalInfo"`
	SignedTransactionInfo string `json:"signedTransactionInfo"`
}

type MassExtendRenewalDateRequest

type MassExtendRenewalDateRequest struct {
	RequestIdentifier      string   `json:"requestIdentifier"`
	ExtendByDays           int      `json:"extendByDays"`
	ExtendReasonCode       int      `json:"extendReasonCode"`
	ProductId              string   `json:"productId"`
	StorefrontCountryCodes []string `json:"storefrontCountryCodes"`
}

MassExtendRenewalDateRequest https://developer.apple.com/documentation/appstoreserverapi/massextendrenewaldaterequest

type NotificationHistoryRequest

type NotificationHistoryRequest struct {
	StartDate             int64                       `json:"startDate"`
	EndDate               int64                       `json:"endDate"`
	OriginalTransactionId string                      `json:"originalTransactionId,omitempty"`
	NotificationType      appstore.NotificationTypeV2 `json:"notificationType,omitempty"`
	NotificationSubtype   appstore.SubtypeV2          `json:"notificationSubtype,omitempty"`
	OnlyFailures          bool                        `json:"onlyFailures"`
	TransactionId         string                      `json:"transactionId"`
}

NotificationHistoryRequest https://developer.apple.com/documentation/appstoreserverapi/notificationhistoryrequest

type NotificationHistoryResponseItem

type NotificationHistoryResponseItem struct {
	SignedPayload          string                 `json:"signedPayload"`
	FirstSendAttemptResult FirstSendAttemptResult `json:"firstSendAttemptResult"`
	SendAttempts           []SendAttemptItem      `json:"sendAttempts"`
}

NotificationHistoryResponseItem https://developer.apple.com/documentation/appstoreserverapi/notificationhistoryresponseitem

type NotificationHistoryResponses

type NotificationHistoryResponses struct {
	HasMore             bool                              `json:"hasMore"`
	PaginationToken     string                            `json:"paginationToken"`
	NotificationHistory []NotificationHistoryResponseItem `json:"notificationHistory"`
}

NotificationHistoryResponses https://developer.apple.com/documentation/appstoreserverapi/notificationhistoryresponse

type OrderLookupResponse

type OrderLookupResponse struct {
	Status             int      `json:"status"`
	SignedTransactions []string `json:"signedTransactions"`
}

OrderLookupResponse https://developer.apple.com/documentation/appstoreserverapi/orderlookupresponse

type RefundLookupResponse

type RefundLookupResponse struct {
	HasMore            bool     `json:"hasMore"`
	Revision           string   `json:"revision"`
	SignedTransactions []string `json:"signedTransactions"`
}

RefundLookupResponse https://developer.apple.com/documentation/appstoreserverapi/refundlookupresponse

type SendAttemptItem

type SendAttemptItem struct {
	AttemptDate       int64                  `json:"attemptDate"`
	SendAttemptResult FirstSendAttemptResult `json:"sendAttemptResult"`
}

SendAttemptItem https://developer.apple.com/documentation/appstoreserverapi/sendattemptitem

type SendTestNotificationResponse

type SendTestNotificationResponse struct {
	TestNotificationToken string `json:"testNotificationToken"`
}

SendTestNotificationResponse https://developer.apple.com/documentation/appstoreserverapi/sendtestnotificationresponse

type StatusResponse

type StatusResponse struct {
	Environment string                            `json:"environment"`
	AppAppleId  int                               `json:"appAppleId"`
	BundleId    string                            `json:"bundleId"`
	Data        []SubscriptionGroupIdentifierItem `json:"data"`
}

StatusResponse https://developer.apple.com/documentation/appstoreserverapi/get_all_subscription_statuses

type StoreClient

type StoreClient struct {
	Token *Token
	// contains filtered or unexported fields
}

func NewStoreClient

func NewStoreClient(config *StoreConfig) *StoreClient

NewStoreClient create a appstore server api client

func NewStoreClientWithHTTPClient

func NewStoreClientWithHTTPClient(config *StoreConfig, httpClient *http.Client) *StoreClient

NewStoreClientWithHTTPClient NewWithClient creates an App Store server api client with a custom http client.

func (*StoreClient) Do

func (a *StoreClient) Do(ctx context.Context, method string, url string, body io.Reader) (int, []byte, error)

Do Per doc: https://developer.apple.com/documentation/appstoreserverapi#topics

func (*StoreClient) ExtendSubscriptionRenewalDate

func (a *StoreClient) ExtendSubscriptionRenewalDate(ctx context.Context, originalTransactionId string, body ExtendRenewalDateRequest) (statusCode int, err error)

ExtendSubscriptionRenewalDate https://developer.apple.com/documentation/appstoreserverapi/extend_a_subscription_renewal_date

func (*StoreClient) GetALLSubscriptionStatuses

func (a *StoreClient) GetALLSubscriptionStatuses(ctx context.Context, originalTransactionId string, query *url.Values) (rsp *StatusResponse, err error)

GetALLSubscriptionStatuses https://developer.apple.com/documentation/appstoreserverapi/get_all_subscription_statuses

func (*StoreClient) GetNotificationHistory

func (a *StoreClient) GetNotificationHistory(ctx context.Context, body NotificationHistoryRequest) (responses []NotificationHistoryResponseItem, err error)

GetNotificationHistory https://developer.apple.com/documentation/appstoreserverapi/get_notification_history Note: Notification history is available starting on June 6, 2022. Use a startDate of June 6, 2022 or later in your request.

func (*StoreClient) GetRefundHistory

func (a *StoreClient) GetRefundHistory(ctx context.Context, originalTransactionId string) (responses []*RefundLookupResponse, err error)

GetRefundHistory https://developer.apple.com/documentation/appstoreserverapi/get_refund_history

func (*StoreClient) GetSubscriptionRenewalDataStatus

func (a *StoreClient) GetSubscriptionRenewalDataStatus(ctx context.Context, productId, requestIdentifier string) (statusCode int, err error)

GetSubscriptionRenewalDataStatus https://developer.apple.com/documentation/appstoreserverapi/get_status_of_subscription_renewal_date_extensions

func (*StoreClient) GetTestNotificationStatus

func (a *StoreClient) GetTestNotificationStatus(ctx context.Context, testNotificationToken string) (int, []byte, error)

GetTestNotificationStatus https://developer.apple.com/documentation/appstoreserverapi/get_test_notification_status

func (*StoreClient) GetTransactionHistory

func (a *StoreClient) GetTransactionHistory(ctx context.Context, originalTransactionId string, query *url.Values) (responses []*HistoryResponse, err error)

GetTransactionHistory https://developer.apple.com/documentation/appstoreserverapi/get_transaction_history

func (*StoreClient) GetTransactionInfo

func (a *StoreClient) GetTransactionInfo(ctx context.Context, transactionId string) (rsp *TransactionInfoResponse, err error)

GetTransactionInfo https://developer.apple.com/documentation/appstoreserverapi/get_transaction_info

func (*StoreClient) ParseSignedTransaction

func (a *StoreClient) ParseSignedTransaction(transaction string) (*JWSTransaction, error)

ParseSignedTransaction parse one jws singed transaction for API like GetTransactionInfo

func (*StoreClient) ParseSignedTransactions

func (a *StoreClient) ParseSignedTransactions(transactions []string) ([]*JWSTransaction, error)

ParseSignedTransactions parse the jws singed transactions Per doc: https://datatracker.ietf.org/doc/html/rfc7515#section-4.1.6

func (*StoreClient) SendConsumptionInfo

func (a *StoreClient) SendConsumptionInfo(ctx context.Context, originalTransactionId string, body ConsumptionRequestBody) (statusCode int, err error)

SendConsumptionInfo https://developer.apple.com/documentation/appstoreserverapi/send_consumption_information

func (*StoreClient) SendRequestTestNotification

func (a *StoreClient) SendRequestTestNotification(ctx context.Context) (int, []byte, error)

SendRequestTestNotification https://developer.apple.com/documentation/appstoreserverapi/request_a_test_notification

type StoreConfig

type StoreConfig struct {
	KeyContent []byte // Loads a .p8 certificate
	KeyID      string // Your private key ID from App Store Connect (Ex: 2X9R4HXF34)
	BundleID   string // Your app’s bundle ID
	Issuer     string // Your issuer ID from the Keys page in App Store Connect (Ex: "57246542-96fe-1a63-e053-0824d011072a")
	Sandbox    bool   // default is Production
}

type SubscriptionGroupIdentifierItem

type SubscriptionGroupIdentifierItem struct {
	SubscriptionGroupIdentifier string                 `json:"subscriptionGroupIdentifier"`
	LastTransactions            []LastTransactionsItem `json:"lastTransactions"`
}

type Token

type Token struct {
	sync.Mutex

	KeyContent []byte // Loads a .p8 certificate
	KeyID      string // Your private key ID from App Store Connect (Ex: 2X9R4HXF34)
	BundleID   string // Your app’s bundle ID
	Issuer     string // Your issuer ID from the Keys page in App Store Connect (Ex: "57246542-96fe-1a63-e053-0824d011072a")
	Sandbox    bool   // default is Production

	// internal variables
	AuthKey   *ecdsa.PrivateKey // .p8 private key
	ExpiredAt int64             // The token’s expiration time, in UNIX time. Tokens that expire more than 60 minutes after the time in iat are not valid (Ex: 1623086400)
	Bearer    string            // Authorized bearer token
}

Token represents an Apple Provider Authentication Token (JSON Web Token).

func (*Token) Expired

func (t *Token) Expired() bool

Expired checks to see if the token has expired.

func (*Token) Generate

func (t *Token) Generate() error

Generate creates a new token.

func (*Token) GenerateIfExpired

func (t *Token) GenerateIfExpired() (string, error)

GenerateIfExpired checks to see if the token is about to expire and generates a new token.

func (*Token) WithConfig

func (t *Token) WithConfig(c *StoreConfig)

type TransactionInfoResponse

type TransactionInfoResponse struct {
	SignedTransactionInfo string `json:"signedTransactionInfo"`
}

TransactionInfoResponse https://developer.apple.com/documentation/appstoreserverapi/transactioninforesponse

type TransactionReason

type TransactionReason string

TransactionReason indicates the cause of a purchase transaction, https://developer.apple.com/documentation/appstoreservernotifications/transactionreason

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL