pay

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

README

整体流程简述

参考文档:https://help.apple.com/app-store-connect/#/devb57be10e7

  1. app从服务端获取待支付订单ID(这个订单ID是自己服务端产生的订单信息)和待付费productId(如果在苹果上配置了多个productId,则需要从服务端拉取自己的商品和苹果商品关联信息,这里的是指在苹果的productId);
  2. app根据productId,发起应用内支付;
  3. app得到支付成功结果,并将支付结果的receipt信息以及第一步的待支付订单ID发回自己的服务端,服务端调用SDK的Verify,得到校验结果(表示该支付信息是否是苹果处理的);
  4. 如果校验成功则表示苹果支付完成,根据第三步传回的订单ID来处理自己的后续业务逻辑; 综上:当使用苹果的应用内支付时,其实是由自己的客户端APP来发起的“支付结果通知”请求来推动业务支付流程的数据流转。

Apple

Apple ApiClient

初始化Apple客户端

privateKeyByte, err := os.ReadFile(privateKeyFile)
if err != nil {
  return
}
// 初始化通联客户端
// iss:issuer ID
// bid:bundle ID
// kid:private key ID
// privateKeyFile:私钥文件读取后的字节内容
// isProduction:是否是正式环境
api, err := pay.NewApiClient(iss, bid, keyID, privateKeyByte,false)

App Store Server API Client Function

Apple Function

  • apple.VerifyReceipt() => 验证支付凭证
  • apple.ExtractClaims() => 解析signedPayload
  • apple.DecodeSignedPayload() => 解析notification signedPayload

Apple支付回调用状态说明

notificationtype: https://developer.apple.com/documentation/appstoreservernotifications/notificationtype

subtype: https://developer.apple.com/documentation/appstoreservernotifications/subtype

notification_type notification_type说明 subtype subtype说明
DID_CHANGE_RENEWAL_PREF 用户对其订阅计划进行了更改 UPGRADE 用户升级其订阅,或交叉分级到具有相同持续时间的订阅。升级立即生效,开始新的计费周期,用户将收到上一周期未使用部分的按比例退款
DOWNGRADE 用户降级其订阅或交叉分级到具有不同持续时间的订阅。降级将在下一个续订日期生效,并且不会影响当前有效的计划
则用户将其续订首选项更改回当前订阅,从而有效地取消降级
DID_CHANGE_RENEWAL_STATUS 用户对其订阅计划进行了更改 AUTO_RENEW_ENABLED 则用户重新启用订阅自动续订
AUTO_RENEW_DISABLED 则用户禁用了订阅自动续费,或者用户申请退款后App Store禁用了订阅自动续费
DID_FAIL_TO_RENEW 订阅由于计费问题而未能续订(通知用户他们的账单信息可能存在问题。App Store 将在 60 天内继续重试计费,或者直到用户解决计费问题或取消订阅(以先到者为准)) GRACE_PERIOD 则在宽限期内继续提供服务
则说明订阅不在宽限期内,您可以停止提供订阅服务
DID_RENEW 订阅已成功续订 BILLING_RECOVERY 则之前续订失败的过期订阅已成功续订
则活动订阅已成功自动续订新的交易周期。为客户提供对订阅内容或服务的访问权限
EXPIRED 订阅已过期 VOLUNTARY 则订阅在用户禁用订阅续订后过期
BILLING_RETRY 则订阅已过期,因为计费重试期已结束,但没有成功的计费事务
PRICE_INCREASE 则订阅已过期,因为用户不同意需要用户同意的价格上涨
PRODUCT_NOT_FOR_SALE 则订阅已过期,因为在订阅尝试续订时该产品不可购买
GRACE_PERIOD_EXPIRED 通知用户他们的账单信息可能存在问题。App Store 将在 60 天内继续重试计费,或者直到用户解决计费问题或取消订阅(以先到者为准)。 指示计费宽限期已结束而无需续订订阅,因此您可以关闭对服务或内容的访问。
OFFER_REDEEMED 用户兑换了促销优惠或优惠代码 INITIAL_BUY 则用户兑换了首次购买的优惠
RESUBSCRIBE 则用户兑换了重新订阅非活动订阅的优惠
UPGRADE 则用户兑换了升级其有效订阅的优惠,该优惠立即生效
DOWNGRADE 则用户兑换了降级其有效订阅的优惠,该优惠将在下一个续订日期生效
无subtype 如果用户兑换了其有效订阅的优惠
PRICE_INCREASE 系统已通知用户自动续订订阅价格上涨 PENDING 如果涨价需要用户同意,是subtype指PENDING用户没有对涨价做出回应,或者ACCEPTED用户已经同意涨价
ACCEPTED 如果涨价不需要用户同意,那subtype就是ACCEPTED
REFUND 包含退款交易的时间戳。并标识原始交易和产品。其中包含原因。revocationDateoriginalTransactionIdproductIdrevocationReason 指示App Store已成功对消费品应用内购买、非消费品应用内购买、自动续订订阅或非续订订阅的交易进行退款
REFUND_DECLINED 指示App Store拒绝了应用开发者使用以下任一方法发起的退款请求
REFUND_REVERSED 此通知类型可适用于任何应用内购买类型:消耗型、非消耗型、非续订订阅和自动续订订阅。对于自动续订订阅,当App Store撤销退款时,续订日期保持不变 表明App Store由于客户提出的争议而撤销了之前授予的退款。如果您的应用因相关退款而撤销了内容或服务,则需要恢复它们
RENEWAL_EXTENDED 指示App Store延长了特定订阅的订阅续订日期。您可以通过调用App Store Server API中的延长订阅续订日期或为所有活跃订阅者延长订阅续订日期来请求订阅续订日期延期
RENEWAL_EXTENSION App Store正在尝试通过调用为所有活跃订阅者延长订阅续订日期来延长您请求的订阅续订日期 SUMMARY App Store已完成为所有符合条件的订阅者延长续订日期
FAILURE 则特定订阅的续订日期延长未成功
REVOKE 指示用户有权通过“家人共享”进行应用内购买的通知类型不再可通过共享进行。当购买者禁用产品的家庭共享、购买者(或家庭成员)离开家庭群组或购买者要求并收到退款时,App Store会发送此通知。您的应用程序也会收到呼叫。家庭共享适用于非消耗性应用内购买和自动续订订阅。
SUBSCRIBED 用户订阅了产品 INITIAL_BUY 用户要么首次购买了订阅,要么通过家庭共享首次获得了对该订阅的访问权限
RESUBSCRIBE 用户要么续订了订阅,要么通过家庭共享获得了对相同订阅或同一订阅组内的另一个订阅的访问权限
TEST 当您通过调用请求测试通知端点请求时,App Store服务器发送的通知类型。调用该端点来测试您的服务器是否正在接收通知。仅当您提出请求时,您才会收到此通知。有关故障排除信息,请参阅获取测试通知状态端点。

Documentation

Index

Constants

View Source
const (
	// UrlSandbox is the URL when testing your app in the sandbox and while your application is in review
	UrlSandbox = "https://sandbox.itunes.apple.com/verifyReceipt"
	// UrlProd is the URL when your app is live in the App Store
	UrlProd = "https://buy.itunes.apple.com/verifyReceipt"
)

Variables

This section is empty.

Functions

func ExtractClaims

func ExtractClaims(signedPayload string, tran jwt.Claims) (err error)

ExtractClaims 解析jws格式数据 signedPayload:jws格式数据 tran:指针类型的结构体,用于接收解析后的数据

Types

type AllSubscriptionStatusesData

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

type ApiClient

type ApiClient struct {
	//https://appstoreconnect.apple.com/access/api/subs
	// Your issuer ID from the Key page in App Store Connect (exp: "57246542-96fe-1a63-e053-0824d011072a")
	Iss string
	//Your app’s bundle ID (exp: "com.example.testbundleid2021")
	Bid string
	//Your private key ID from App Store Connect (Ex: 2X9R4HXF34)
	KeyID string
	//Is it a formal environment
	IsProduction bool
	//Parsing private keys
	PrivateKey *ecdsa.PrivateKey
	//Request client
	Client *requests.Client
}

func NewApiClient

func NewApiClient(iss, bid, keyID string, privateKey []byte, isProduction bool) (api *ApiClient, err error)

func (*ApiClient) GetAllSubscriptionStatuses

func (a *ApiClient) GetAllSubscriptionStatuses(transactionId string) (resp *ResponseAllSubscriptionStatuses, err error)

GetAllSubscriptionStatuses Get All Subscription Statuses Doc: https://developer.apple.com/documentation/appstoreserverapi/get_all_subscription_statuses

func (*ApiClient) GetNotificationHistory

func (a *ApiClient) GetNotificationHistory(paginationToken string) (resp *ResponseNotificationHistory, err error)

GetNotificationHistory Get Notification History rsp.NotificationHistory[x].SignedPayload use apple.DecodeSignedPayload() to decode Doc: https://developer.apple.com/documentation/appstoreserverapi/get_notification_history

func (*ApiClient) GetRefundHistory

func (a *ApiClient) GetRefundHistory(transactionId, revision string) (rsp *ResponseRefundHistory, err error)

GetRefundHistory Get Refund History Doc: https://developer.apple.com/documentation/appstoreserverapi/get_refund_history

func (*ApiClient) GetTransactionHistory

func (a *ApiClient) GetTransactionHistory(transactionId string, body apple.BodyMap) (resp *ResponseTransactionHistory, err error)

GetTransactionHistory Get Transaction History Doc: https://developer.apple.com/documentation/appstoreserverapi/get_transaction_history

func (*ApiClient) GetTransactionInfo

func (a *ApiClient) GetTransactionInfo(transactionId string) (resp *ResponseTransactionInfo, err error)

GetTransactionInfo Get Transaction Info Doc: https://developer.apple.com/documentation/appstoreserverapi/get_transaction_info

func (*ApiClient) LookUpOrderId

func (a *ApiClient) LookUpOrderId(orderId string) (resp *ResponseLookUpOrderId, err error)

LookUpOrderId Look Up Order ID Doc: https://developer.apple.com/documentation/appstoreserverapi/look_up_order_id

func (*ApiClient) SendConsumptionInformation

func (a *ApiClient) SendConsumptionInformation(transactionId string) (err error)

SendConsumptionInformation Send Consumption Information Doc: https://developer.apple.com/documentation/appstoreserverapi/send_consumption_information

func (*ApiClient) WithTokenGet

func (a *ApiClient) WithTokenGet(path string, data, d any) error

func (*ApiClient) WithTokenPost

func (a *ApiClient) WithTokenPost(path string, data, d any) error

func (*ApiClient) WithTokenPut

func (a *ApiClient) WithTokenPut(path string, data, d any) error

type ApiClientConfig

type ApiClientConfig struct {
	ISS          string `json:"iss"`
	BID          string `json:"bid"`
	KeyID        string `json:"keyID"`
	PrivateKey   string `json:"privateKey"`
	IsProduction bool   `json:"isProduction"`
}

func (*ApiClientConfig) NewApi

func (config *ApiClientConfig) NewApi() (api *ApiClient, err error)

type CustomClaims

type CustomClaims struct {
	jwt.Claims
	Iss string `json:"iss"`
	Iat int64  `json:"iat"`
	Exp int64  `json:"exp"`
	Aud string `json:"aud"`
	Bid string `json:"bid"`
}

type Data

type Data struct {
	AppAppleID            int    `json:"appAppleId"`
	BundleID              string `json:"bundleId"`
	BundleVersion         string `json:"bundleVersion"`
	Environment           string `json:"environment"`
	SignedRenewalInfo     string `json:"signedRenewalInfo"`
	SignedTransactionInfo string `json:"signedTransactionInfo"`
}

Data https://developer.apple.com/documentation/appstoreservernotifications/data

type InApp

type InApp struct {
	// The time the App Store refunded a transaction or revoked it from family sharing, in a date-time format similar to the ISO 8601. This field is present only for refunded or revoked transactions.
	CancellationDate string `json:"cancellation_date"`

	// The time the App Store refunded a transaction or revoked it from family sharing, in UNIX epoch time format, in milliseconds. This field is present only for refunded or revoked transactions. Use this time format for processing dates. The time the App Store refunded a transaction or revoked it from family sharing, in UNIX epoch time format, in milliseconds. This field is present only for refunded or revoked transactions. Use this time format for processing dates.
	// https://developer.apple.com/documentation/appstorereceipts/cancellation_date_ms
	CancellationDateTimestamp string `json:"cancellation_date_ms"`

	// The time Apple customer support canceled a transaction, in the Pacific Time zone. This field is only present for refunded transactions.
	CancellationDatePST string `json:"cancellation_date_pst"`

	// The reason for a refunded transaction. When a customer cancels a transaction, the App Store gives them a refund and provides a value for this key. A value of “1” indicates that the customer canceled their transaction due to an actual or perceived issue within your app. A value of “0” indicates that the transaction was canceled for another reason; for example, if the customer made the purchase accidentally.
	// Possible values: 1, 0
	CancellationReason string `json:"cancellation_reason"`

	// The time a subscription expires or when it will renew, in a date-time format similar to the ISO 8601.
	ExpiresDate string `json:"expires_date"`

	// The time a subscription expires or when it will renew, in UNIX epoch time format, in milliseconds. Use this time format for processing dates.
	// https://developer.apple.com/documentation/appstorereceipts/expires_date_ms
	ExpiresDateTimestamp string `json:"expires_date_ms"`

	// The time a subscription expires or when it will renew, in the Pacific Time zone.
	ExpiresDatePST string `json:"expires_date_pst"`

	// An indicator of whether an auto-renewable subscription is in the introductory price period.
	// https://developer.apple.com/documentation/appstorereceipts/is_in_intro_offer_period
	IsInIntroOfferPeriod string `json:"is_in_intro_offer_period"`

	// An indication of whether a subscription is in the free trial period.
	// https://developer.apple.com/documentation/appstorereceipts/is_trial_period
	IsTrialPeriod string `json:"is_trial_period"`

	// The time of the original in-app purchase, in a date-time format similar to ISO 8601.
	OriginalPurchaseDate string `json:"original_purchase_date"`

	// The time of the original in-app purchase, in UNIX epoch time format, in milliseconds. For an auto-renewable subscription, this value indicates the date of the subscription's initial purchase. The original purchase date applies to all product types and remains the same in all transactions for the same product ID. This value corresponds to the original transaction’s transactionDate property in StoreKit. Use this time format for processing dates.
	OriginalPurchaseDateTimestamp string `json:"original_purchase_date_ms"`

	// The time of the original in-app purchase, in the Pacific Time zone.
	OriginalPurchaseDatePST string `json:"original_purchase_date_pst"`

	// The transaction identifier of the original purchase.
	// https://developer.apple.com/documentation/appstorereceipts/original_transaction_id
	OriginalTransactionId string `json:"original_transaction_id"`

	// The unique identifier of the product purchased. You provide this value when creating the product in App Store Connect, and it corresponds to the productIdentifier property of the SKPayment object stored in the transaction's payment property.
	ProductId string `json:"product_id"`

	// The identifier of the subscription offer redeemed by the user.
	// https://developer.apple.com/documentation/appstorereceipts/promotional_offer_id
	PromotionalOfferId string `json:"promotional_offer_id"`

	// The time the App Store charged the user's account for a purchased or restored product, or the time the App Store charged the user’s account for a subscription purchase or renewal after a lapse, in a date-time format similar to ISO 8601.
	PurchaseDate string `json:"purchase_date"`

	// For consumable, non-consumable, and non-renewing subscription products, the time the App Store charged the user's account for a purchased or restored product, in the UNIX epoch time format, in milliseconds. For auto-renewable subscriptions, the time the App Store charged the user’s account for a subscription purchase or renewal after a lapse, in the UNIX epoch time format, in milliseconds. Use this time format for processing dates.
	PurchaseDateTimestamp string `json:"purchase_date_ms"`

	// The time the App Store charged the user's account for a purchased or restored product, or the time the App Store charged the user’s account for a subscription purchase or renewal after a lapse, in the Pacific Time zone.
	PurchaseDatePST string `json:"purchase_date_pst"`

	// The number of consumable products purchased. This value corresponds to the quantity property of the SKPayment object stored in the transaction's payment property. The value is usually “1” unless modified with a mutable payment. The maximum value is 10.
	Quantity string `json:"quantity"`

	// A unique identifier for a transaction such as a purchase, restore, or renewal. See transaction_id for more information.
	TransactionId string `json:"transaction_id"`

	// A unique identifier for purchase events across devices, including subscription-renewal events. This value is the primary key for identifying subscription purchases.
	WebOrderLineItemId string `json:"web_order_line_item_id"`
}

InApp is the in-app purchase receipt fields for all in-app purchase transactions. https://developer.apple.com/documentation/appstorereceipts/responsebody/receipt/in_app

func (*InApp) ExpiresDateTime

func (p *InApp) ExpiresDateTime() (time.Time, error)

func (*InApp) OriginalPurchaseDateTime

func (p *InApp) OriginalPurchaseDateTime() (time.Time, error)

func (*InApp) PurchaseDateTime

func (p *InApp) PurchaseDateTime() (time.Time, error)

type LastTransactionsItem

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

func (*LastTransactionsItem) DecodeRenewalInfo

func (d *LastTransactionsItem) DecodeRenewalInfo() (ri *RenewalInfo, err error)

func (*LastTransactionsItem) DecodeTransactionInfo

func (d *LastTransactionsItem) DecodeTransactionInfo() (ti *TransactionInfo, err error)

type LatestReceiptInfo

type LatestReceiptInfo struct {
	// The time Apple customer support canceled a transaction, in a date-time format similar to the ISO 8601. This field is only present for refunded transactions.
	CancellationDate string `json:"cancellation_date"`

	// The time Apple customer support canceled a transaction, or the time an auto-renewable subscription plan was upgraded, in UNIX epoch time format, in milliseconds. This field is only present for refunded transactions. Use this time format for processing dates.
	// https://developer.apple.com/documentation/appstorereceipts/cancellation_date_ms
	CancellationDateTimestamp string `json:"cancellation_date_ms"`

	// The time Apple customer support canceled a transaction, in the Pacific Time zone. This field is only present for refunded transactions.
	CancellationDatePST string `json:"cancellation_date_pst"`

	// The reason for a refunded transaction. When a customer cancels a transaction, the App Store gives them a refund and provides a value for this key. A value of “1” indicates that the customer canceled their transaction due to an actual or perceived issue within your app. A value of “0” indicates that the transaction was canceled for another reason; for example, if the customer made the purchase accidentally.
	// Possible values: 1, 0
	CancellationReason string `json:"cancellation_reason"`

	// The time a subscription expires or when it will renew, in a date-time format similar to the ISO 8601.
	ExpiresDate string `json:"expires_date"`

	// The time a subscription expires or when it will renew, in UNIX epoch time format, in milliseconds. Use this time format for processing dates.
	// https://developer.apple.com/documentation/appstorereceipts/expires_date_ms
	ExpiresDateTimestamp string `json:"expires_date_ms"`

	// The time a subscription expires or when it will renew, in the Pacific Time zone.
	ExpiresDatePST string `json:"expires_date_pst"`

	// A value that indicates whether the user is the purchaser of the product, or is a family member with access to the product through Family Sharing.
	// https://developer.apple.com/documentation/appstorereceipts/in_app_ownership_type
	InAppOwnershipType string `json:"in_app_ownership_type"`

	// An indicator of whether an auto-renewable subscription is in the introductory price period.
	// Possible values: true, false
	IsInIntroOfferPeriod string `json:"is_in_intro_offer_period"`

	// An indicator of whether a subscription is in the free trial period.
	// https://developer.apple.com/documentation/appstorereceipts/is_trial_period
	IsTrialPeriod string `json:"is_trial_period"`

	// An indicator that a subscription has been canceled due to an upgrade. This field is only present for upgrade transactions.
	// Value: true
	IsUpgraded string `json:"is_upgraded"`

	// The reference name of a subscription offer that you configured in App Store Connect. This field is present when a customer redeemed a subscription offer code. For more information about offer codes
	// https://help.apple.com/app-store-connect/#/dev6a098e4b1
	// https://developer.apple.com/documentation/storekit/original_api_for_in-app_purchase/subscriptions_and_offers/implementing_offer_codes_in_your_app
	OfferCodeRefName string `json:"offer_code_ref_name"`

	// The time of the original app purchase, in a date-time format similar to ISO 8601.
	OriginalPurchaseDate string `json:"original_purchase_date"`

	// The time of the original app purchase, in UNIX epoch time format, in milliseconds. Use this time format for processing dates. For an auto-renewable subscription, this value indicates the date of the subscription’s initial purchase. The original purchase date applies to all product types and remains the same in all transactions for the same product ID. This value corresponds to the original transaction’s transactionDate property in StoreKit.
	OriginalPurchaseDateTimestamp string `json:"original_purchase_date_ms"`

	// The time of the original app purchase, in the Pacific Time zone.
	OriginalPurchaseDatePST string `json:"original_purchase_date_pst"`

	// The transaction identifier of the original purchase.
	// https://developer.apple.com/documentation/appstorereceipts/original_transaction_id
	OriginalTransactionId string `json:"original_transaction_id"`

	// The unique identifier of the product purchased. You provide this value when creating the product in App Store Connect, and it corresponds to the productIdentifier property of the SKPayment object stored in the transaction’s payment property.
	ProductId string `json:"product_id"`

	// The identifier of the subscription offer redeemed by the user.
	// https://developer.apple.com/documentation/appstorereceipts/promotional_offer_id
	PromotionalOfferId string `json:"promotional_offer_id"`

	// The time the App Store charged the user’s account for a purchased or restored product, or the time the App Store charged the user’s account for a subscription purchase or renewal after a lapse, in a date-time format similar to ISO 8601.
	PurchaseDate string `json:"purchase_date"`

	// For consumable, non-consumable, and non-renewing subscription products, the time the App Store charged the user’s account for a purchased or restored product, in the UNIX epoch time format, in milliseconds. For auto-renewable subscriptions, the time the App Store charged the user’s account for a subscription purchase or renewal after a lapse, in the UNIX epoch time format, in milliseconds. Use this time format for processing dates.
	PurchaseDateTimestamp string `json:"purchase_date_ms"`

	// The time the App Store charged the user’s account for a purchased or restored product, or the time the App Store charged the user’s account for a subscription purchase or renewal after a lapse, in the Pacific Time zone.
	PurchaseDatePST string `json:"purchase_date_pst"`

	// The number of consumable products purchased. This value corresponds to the quantity property of the SKPayment object stored in the transaction’s payment property. The value is usually “1” unless modified with a mutable payment. The maximum value is 10.
	Quantity string `json:"quantity"`

	// The identifier of the subscription group to which the subscription belongs. The value for this field is identical to the subscriptionGroupIdentifier property in SKProduct.
	// https://developer.apple.com/documentation/storekit/skproduct/2981047-subscriptiongroupidentifier
	SubscriptionGroupIdentifier string `json:"subscription_group_identifier"`

	// A unique identifier for purchase events across devices, including subscription-renewal events. This value is the primary key for identifying subscription purchases.
	WebOrderLineItemId string `json:"web_order_line_item_id"`

	// A unique identifier for a transaction such as a purchase, restore, or renewal
	TransactionId string `json:"transaction_id"`

	// https://developer.apple.com/documentation/appstorereceipts/app_account_token
	AppAccountToken string `json:"app_account_token"`
}

LatestReceiptInfo https://developer.apple.com/documentation/appstorereceipts/responsebody/latest_receipt_info

func (*LatestReceiptInfo) ExpiresDateTime

func (p *LatestReceiptInfo) ExpiresDateTime() (time.Time, error)

func (*LatestReceiptInfo) PurchaseDateTime

func (p *LatestReceiptInfo) PurchaseDateTime() (time.Time, error)

type NotificationItem

type NotificationItem struct {
	SendAttempts  []*SendAttemptItem `json:"sendAttempts"`
	SignedPayload string             `json:"signedPayload"`
}

type NotificationV2Payload

type NotificationV2Payload struct {
	jwt.StandardClaims
	NotificationType string `json:"notificationType"`
	Subtype          string `json:"subtype"`
	NotificationUUID string `json:"notificationUUID"`
	Version          string `json:"version"`
	Data             *Data  `json:"data"`
}

NotificationV2Payload https://developer.apple.com/documentation/appstoreservernotifications/responsebodyv2decodedpayload

func DecodeSignedPayload

func DecodeSignedPayload(signedPayload string) (payload *NotificationV2Payload, err error)

DecodeSignedPayload 解析SignedPayload数据

func (*NotificationV2Payload) DecodeRenewalInfo

func (d *NotificationV2Payload) DecodeRenewalInfo() (ri *RenewalInfo, err error)

func (*NotificationV2Payload) DecodeTransactionInfo

func (d *NotificationV2Payload) DecodeTransactionInfo() (ti *TransactionInfo, err error)

type NotificationV2SignedPayloadResponse

type NotificationV2SignedPayloadResponse struct {
	Payload         *NotificationV2Payload `json:"payload"`
	RenewalInfo     *RenewalInfo           `json:"renewal_info"`
	TransactionInfo *TransactionInfo       `json:"transaction_info"`
}

func NotificationV2SignedPayload

func NotificationV2SignedPayload(signedPayload string) (resp *NotificationV2SignedPayloadResponse, err error)

type PendingRenewalInfo

type PendingRenewalInfo struct {
	// The value for this key corresponds to the productIdentifier property of the product that the customer’s subscription renews.
	AutoRenewProductId string `json:"auto_renew_product_id"`

	// The current renewal status for the auto-renewable subscription.
	// https://developer.apple.com/documentation/appstorereceipts/auto_renew_status
	AutoRenewStatus string `json:"auto_renew_status"`

	// The reason a subscription expired. This field is only present for a receipt that contains an expired auto-renewable subscription.
	// https://developer.apple.com/documentation/appstorereceipts/expiration_intent
	ExpirationIntent string `json:"expiration_intent"`

	// The time at which the grace period for subscription renewals expires, in a date-time format similar to the ISO 8601.
	GracePeriodExpiresDate string `json:"grace_period_expires_date"`

	// The time at which the grace period for subscription renewals expires, in UNIX epoch time format, in milliseconds. This key is only present for apps that have Billing Grace Period enabled and when the user experiences a billing error at the time of renewal. Use this time format for processing dates.
	GracePeriodExpiresDateTimestamp string `json:"grace_period_expires_date_ms"`

	// The time at which the grace period for subscription renewals expires, in the Pacific Time zone.
	GracePeriodExpiresDatePST string `json:"grace_period_expires_date_pst"`

	// A flag that indicates Apple is attempting to renew an expired subscription automatically. This field is only present if an auto-renewable subscription is in the billing retry state.
	// https://developer.apple.com/documentation/appstorereceipts/is_in_billing_retry_period
	IsInBillingRetryPeriod string `json:"is_in_billing_retry_period"`

	// The reference name of a subscription offer that you configured in App Store Connect. This field is present when a customer redeemed a subscription offer code
	// https://developer.apple.com/documentation/appstorereceipts/offer_code_ref_name
	OfferCodeRefName string `json:"offer_code_ref_name"`

	// The transaction identifier of the original purchase.
	OriginalTransactionId string `json:"original_transaction_id"`

	// The price consent status for a subscription price increase. This field is only present if the customer was notified of the price increase. The default value is "0" and changes to "1" if the customer consents.
	// Possible values: 1, 0
	PriceConsentStatus string `json:"price_consent_status"`

	// The unique identifier of the product purchased. You provide this value when creating the product in App Store Connect, and it corresponds to the productIdentifier property of the SKPayment object stored in the transaction's payment property.
	// https://developer.apple.com/documentation/storekit/skpayment
	ProductId string `json:"product_id"`

	// The identifier of the promotional offer for an auto-renewable subscription that the user redeemed. You provide this value in the Promotional Offer Identifier field when you create the promotional offer in App Store Connect.
	// https://developer.apple.com/documentation/appstorereceipts/promotional_offer_id
	Promotionalofferid string `json:"promotional_offer_id"`
}

PendingRenewalInfo https://developer.apple.com/documentation/appstorereceipts/responsebody/pending_renewal_info

type Receipt

type Receipt struct {
	// See app_item_id.
	AdamId int64 `json:"adam_id"`

	// Generated by App Store Connect and used by the App Store to uniquely identify the app purchased. Apps are assigned this identifier only in production. Treat this value as a 64-bit long integer.
	AppItemId int64 `json:"app_item_id"`

	// The app’s version number. The app's version number corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in macOS) in the Info.plist. In production, this value is the current version of the app on the device based on the receipt_creation_date_ms. In the sandbox, the value is always "1.0".
	ApplicationVersion string `json:"application_version"`

	// The bundle identifier for the app to which the receipt belongs. You provide this string on App Store Connect. This corresponds to the value of CFBundleIdentifier in the Info.plist file of the app.
	BundleId string `json:"bundle_id"`

	// A unique identifier for the app download transaction.
	DownloadId int64 `json:"download_id"`

	// The time the receipt expires for apps purchased through the Volume Purchase Program, in a date-time format similar to the ISO 8601.
	ExpirationDate string `json:"expiration_date"`

	// The time the receipt expires for apps purchased through the Volume Purchase Program, in UNIX epoch time format, in milliseconds. If this key is not present for apps purchased through the Volume Purchase Program, the receipt does not expire. Use this time format for processing dates.
	ExpirationDateTimestamp string `json:"expiration_date_ms"`

	// The time the receipt expires for apps purchased through the Volume Purchase Program, in the Pacific Time zone.
	ExpirationDatePST string `json:"expiration_date_pst"`

	// An array that contains the in-app purchase receipt fields for all in-app purchase transactions.
	InApp []*InApp `json:"in_app,omitempty"`

	// The version of the app that the user originally purchased. This value does not change, and corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in macOS) in the Info.plist file of the original purchase. In the sandbox environment, the value is always "1.0".
	OriginalApplicationVersion string `json:"original_application_version"`

	// The time of the original app purchase, in a date-time format similar to ISO 8601.
	OriginalPurchaseDate string `json:"original_purchase_date"`

	// The time of the original app purchase, in UNIX epoch time format, in milliseconds. Use this time format for processing dates.
	OriginalPurchaseDateTimestamp string `json:"original_purchase_date_ms"`

	// The time of the original app purchase, in the Pacific Time zone.
	OriginalPurchaseDatePST string `json:"original_purchase_date_pst"`

	// The time the user ordered the app available for pre-order, in a date-time format similar to ISO 8601.
	PreorderDate string `json:"preorder_date"`

	// The time the user ordered the app available for pre-order, in UNIX epoch time format, in milliseconds. This field is only present if the user pre-orders the app. Use this time format for processing dates.
	PreorderDateTimestamp string `json:"preorder_date_ms"`

	// The time the user ordered the app available for pre-order, in the Pacific Time zone.
	PreorderDatePST string `json:"preorder_date_pst"`

	// The time the App Store generated the receipt, in a date-time format similar to ISO 8601.
	ReceiptCreationDate string `json:"receipt_creation_date"`

	// The time the App Store generated the receipt, in UNIX epoch time format, in milliseconds. Use this time format for processing dates. This value does not change.
	ReceiptCreationDateTimestamp string `json:"receipt_creation_date_ms"`

	// The time the App Store generated the receipt, in the Pacific Time zone.
	ReceiptCreationDatePST string `json:"receipt_creation_date_pst"`

	// The type of receipt generated. The value corresponds to the environment in which the app or VPP purchase was made.
	//  Possible values: Production, ProductionVPP, ProductionSandbox, ProductionVPPSandbox
	ReceiptType string `json:"receipt_type"`

	// The time the request to the verifyReceipt endpoint was processed and the response was generated, in a date-time format similar to ISO 8601.
	RequestDate string `json:"request_date"`

	// The time the request to the verifyReceipt endpoint was processed and the response was generated, in UNIX epoch time format, in milliseconds. Use this time format for processing dates.
	RequestDateTimestamp string `json:"request_date_ms"`

	// The time the request to the verifyReceipt endpoint was processed and the response was generated, in the Pacific Time zone.
	RequestDatePST string `json:"request_date_pst"`

	// An arbitrary number that identifies a revision of your app. In the sandbox, this key's value is 0.
	VersionExternalIdentifier int64 `json:"version_external_identifier"`
}

Receipt is the decoded version of the encoded receipt data sent with the request to the App Store https://developer.apple.com/documentation/appstorereceipts/responsebody/receipt

type RenewalInfo

type RenewalInfo struct {
	jwt.StandardClaims
	AutoRenewProductId          string `json:"autoRenewProductId"`
	AutoRenewStatus             int64  `json:"autoRenewStatus"`
	Environment                 string `json:"environment"`
	ExpirationIntent            int64  `json:"expirationIntent"`
	GracePeriodExpiresDate      int64  `json:"gracePeriodExpiresDate"`
	IsInBillingRetryPeriod      bool   `json:"isInBillingRetryPeriod"`
	OfferIdentifier             string `json:"offerIdentifier"`
	OfferType                   int64  `json:"offerType"` // 1:An introductory offer. 2:A promotional offer. 3:An offer with a subscription offer code.
	OriginalTransactionId       string `json:"originalTransactionId"`
	PriceIncreaseStatus         int64  `json:"priceIncreaseStatus"` // 0: The customer hasn’t responded to the subscription price increase. 1:The customer consented to the subscription price increase.
	ProductId                   string `json:"productId"`
	RecentSubscriptionStartDate int64  `json:"recentSubscriptionStartDate"`
	RenewalDate                 int64  `json:"renewalDate,omitempty"` // The UNIX time, in milliseconds, that the most recent auto-renewable subscription purchase expires.
	SignedDate                  int64  `json:"signedDate"`
}

RenewalInfo https://developer.apple.com/documentation/appstoreservernotifications/jwsrenewalinfodecodedpayload

type ResponseAllSubscriptionStatuses

type ResponseAllSubscriptionStatuses struct {
	ResponseErrorMessage
	AppAppleId  int                            `json:"appAppleId"`
	BundleId    string                         `json:"bundleId"`
	Environment string                         `json:"environment"`
	Data        []*AllSubscriptionStatusesData `json:"data"`
}

type ResponseErrorMessage

type ResponseErrorMessage struct {
	ErrorCode    int    `json:"errorCode,omitempty"`
	ErrorMessage string `json:"errorMessage,omitempty"`
}

type ResponseLookUpOrderId

type ResponseLookUpOrderId struct {
	ResponseErrorMessage
	Status             int                 `json:"status,omitempty"` // 0-valid,1-invalid
	SignedTransactions []SignedTransaction `json:"signedTransactions,omitempty"`
}

type ResponseNotificationHistory

type ResponseNotificationHistory struct {
	ResponseErrorMessage
	HasMore             bool                `json:"hasMore"`
	PaginationToken     string              `json:"paginationToken"`
	NotificationHistory []*NotificationItem `json:"notificationHistory"`
}

type ResponseRefundHistory

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

type ResponseTransactionHistory

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

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

type ResponseTransactionInfo

type ResponseTransactionInfo struct {
	ResponseErrorMessage
	SignedTransactionInfo string `json:"signedTransactionInfo"`
}

ResponseTransactionInfo Doc: https://developer.apple.com/documentation/appstoreserverapi/transactioninforesponse

func (*ResponseTransactionInfo) DecodeSignedTransaction

func (t *ResponseTransactionInfo) DecodeSignedTransaction() (ti *TransactionsItem, err error)

type SendAttemptItem

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

type SignedTransaction

type SignedTransaction string

func (*SignedTransaction) DecodeSignedTransaction

func (s *SignedTransaction) DecodeSignedTransaction() (ti *TransactionsItem, err error)

type TransactionInfo

type TransactionInfo struct {
	jwt.StandardClaims
	AppAccountToken             string `json:"appAccountToken"`
	BundleId                    string `json:"bundleId"`
	Environment                 string `json:"environment"`
	ExpiresDate                 int64  `json:"expiresDate"`
	InAppOwnershipType          string `json:"inAppOwnershipType"` // FAMILY_SHARED  PURCHASED
	IsUpgraded                  bool   `json:"isUpgraded"`
	OfferIdentifier             string `json:"offerIdentifier"`
	OfferType                   int64  `json:"offerType"` // 1:An introductory offer. 2:A promotional offer. 3:An offer with a subscription offer code.
	OriginalPurchaseDate        int64  `json:"originalPurchaseDate"`
	OriginalTransactionId       string `json:"originalTransactionId"`
	ProductId                   string `json:"productId"`
	PurchaseDate                int64  `json:"purchaseDate"`
	Quantity                    int64  `json:"quantity"`
	RevocationDate              int64  `json:"revocationDate"`
	RevocationReason            int    `json:"revocationReason"`
	SignedDate                  int64  `json:"signedDate"` // Auto-Renewable Subscription: An auto-renewable subscription.  Non-Consumable: A non-consumable in-app purchase.  Consumable: A consumable in-app purchase.  Non-Renewing Subscription: A non-renewing subcription.
	SubscriptionGroupIdentifier string `json:"subscriptionGroupIdentifier"`
	TransactionId               string `json:"transactionId"`
	TransactionReason           string `json:"transactionReason"`
	Type                        string `json:"type"`
	WebOrderLineItemId          string `json:"webOrderLineItemId"`
	Storefront                  string `json:"storefront"`
	StorefrontId                string `json:"storefrontId"`
}

TransactionInfo https://developer.apple.com/documentation/appstoreservernotifications/jwstransactiondecodedpayload

func (*TransactionInfo) ExpiresDateTime

func (p *TransactionInfo) ExpiresDateTime() (time.Time, error)

func (*TransactionInfo) OriginalPurchaseDateTime

func (p *TransactionInfo) OriginalPurchaseDateTime() (time.Time, error)

func (*TransactionInfo) PurchaseDateTime

func (p *TransactionInfo) PurchaseDateTime() (time.Time, error)

type TransactionsItem

type TransactionsItem struct {
	jwt.StandardClaims
	TransactionId               string `json:"transactionId"`
	OriginalTransactionId       string `json:"originalTransactionId"`
	WebOrderLineItemId          string `json:"webOrderLineItemId"`
	BundleId                    string `json:"bundleId"`
	ProductId                   string `json:"productId"`
	SubscriptionGroupIdentifier string `json:"subscriptionGroupIdentifier"`
	PurchaseDate                int64  `json:"purchaseDate"`
	OriginalPurchaseDate        int64  `json:"originalPurchaseDate"`
	ExpiresDate                 int64  `json:"expiresDate"`
	Quantity                    int    `json:"quantity"`
	Type                        string `json:"type"`
	InAppOwnershipType          string `json:"inAppOwnershipType"`
	SignedDate                  int64  `json:"signedDate"`
	OfferType                   int    `json:"offerType"`
	Environment                 string `json:"environment"`
	AppAccountToken             string `json:"appAccountToken"`
}

TransactionsItem Doc: https://developer.apple.com/documentation/appstoreserverapi/jwstransactiondecodedpayload

type VerifyRequest

type VerifyRequest struct {
	// Receipt app解析出的票据信息
	Receipt string `json:"receipt-data"`

	// Password App的秘钥
	Password string `json:"password,omitempty"`

	// ExcludeOldTranscations Set this value to true for the response to include only the latest renewal transaction for any subscriptions. Use this field only for app receipts that contain auto-renewable subscriptions.
	ExcludeOldTranscations bool `json:"exclude-old-transactions"`
}

VerifyRequest 校验请求体 https://developer.apple.com/documentation/appstorereceipts/requestbody

type VerifyResponse

type VerifyResponse struct {
	// Environment is which the receipt was generated. Possible values: Sandbox, Production
	Environment string `json:"environment"`

	// IsRetryable is an indicator that an error occurred during the request. A value of 1 indicates a temporary issue; retry validation for this receipt at a later time. A value of 0 indicates an unresolvable issue; do not retry validation for this receipt. Only applicable to status codes 21100-21199.
	IsRetryable bool `json:"is-retryable"`

	// LatestReceipt The latest Base64 encoded app receipt. Only returned for receipts that contain auto-renewable subscriptions
	LatestReceipt string `json:"latest_receipt,omitempty"`

	// LatestReceiptInfo is an array that contains all in-app purchase transactions. This excludes transactions for consumable products that have been marked as finished by your app. Only returned for receipts that contain auto-renewable subscriptions.
	LatestReceiptInfo []*LatestReceiptInfo `json:"latest_receipt_info,omitempty"`

	// PendingRenewalInfo ,in the JSON file, an array where each element contains the pending renewal information for each auto-renewable subscription identified by the product_id. Only returned for app receipts that contain auto-renewable subscriptions.
	PendingRenewalInfo []*PendingRenewalInfo `json:"pending_renewal_info,omitempty"`

	// Receipt is a JSON representation of the receipt that was sent for verification.
	Receipt *Receipt `json:"receipt,omitempty"`

	// Status either 0 if the receipt is valid, or a status code if there is an error. The status code reflects the status of the app receipt as a whole. See status for possible status codes and descriptions.
	// =0时就表示校验成功
	Status int `json:"status"`
}

VerifyResponse 校验响应体 https://developer.apple.com/documentation/appstorereceipts/responsebody

func VerifyReceipt

func VerifyReceipt(ctx context.Context, url, pwd, receipt string) (resp *VerifyResponse, err error)

VerifyReceipt 请求APP Store 校验支付请求,实际测试时发现这个文档介绍的返回信息只有那个status==0表示成功可以用,其他的返回信息跟文档对不上 url:取 UrlProd 或 UrlSandbox pwd:苹果APP秘钥,https://help.apple.com/app-store-connect/#/devf341c0f01 文档:https://developer.apple.com/documentation/appstorereceipts/verifyreceipt

func (*VerifyResponse) LatestReceiptInfoOrderByExpiresDate

func (v *VerifyResponse) LatestReceiptInfoOrderByExpiresDate() []*LatestReceiptInfo

Jump to

Keyboard shortcuts

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