18 Commits

Author SHA1 Message Date
cd5a78348a „go.mod“ ändern 2020-05-20 10:22:53 +00:00
Sanjidul Hoque
dad27d5283 Merge pull request #3 from Purchase-Fly/car
Add cancellation reason field for notification
2020-05-14 22:07:31 +06:00
sanjid133
777e3c50ef Add cancellation reason field for notification 2020-05-14 22:05:15 +06:00
sanjid133
4f7b16717e fix auto renew status 2020-03-05 17:35:21 +06:00
sanjid133
a564d013c9 status field not present in initial_buy 2020-03-05 17:35:21 +06:00
sanjid133
134bcb9b89 auto renew status string 2020-03-05 17:35:21 +06:00
sanjid133
5cc0a53c63 Verfiy latest receipt 2020-03-05 17:35:21 +06:00
Minhaz Ahmed Syrus
22c0b76a09 Add missing subscription billing retry flag 2020-03-05 17:33:20 +06:00
Minhaz Ahmed Syrus
0ae05687d4 Add missing notification verification fields 2020-03-05 17:33:20 +06:00
Minhaz Ahmed Syrus
b04c08d22b Add missing subscription billing retry flag 2020-03-05 17:32:57 +06:00
Minhaz Ahmed Syrus
9b772f3398 Add missing notification verification fields 2020-03-05 17:32:19 +06:00
sanjid133
073874b26d Add renewal field 2020-03-05 17:31:39 +06:00
sanjid133
a14bd11b0c Verfiy latest receipt 2020-03-05 17:31:39 +06:00
sanjid133
7f77f5e33e Add missing is_upgrade field 2020-03-05 17:00:02 +06:00
Minhaz Ahmed Syrus
eacfb2d096 Add missing subscription billing retry flag 2020-03-05 17:00:02 +06:00
Minhaz Ahmed Syrus
91cd5b791c Add missing notification verification fields 2020-03-05 16:59:30 +06:00
Minhaz Ahmed Syrus
2700fc2ec0 Add missing subscription billing retry flag 2020-03-05 16:57:47 +06:00
Minhaz Ahmed Syrus
e4338cd607 Add missing notification verification fields 2020-03-05 16:57:47 +06:00
12 changed files with 35 additions and 1255 deletions

View File

@@ -12,7 +12,6 @@ Current API Documents:
* AppStore: [![GoDoc](https://godoc.org/github.com/awa/go-iap/appstore?status.svg)](https://godoc.org/github.com/awa/go-iap/appstore) * AppStore: [![GoDoc](https://godoc.org/github.com/awa/go-iap/appstore?status.svg)](https://godoc.org/github.com/awa/go-iap/appstore)
* GooglePlay: [![GoDoc](https://godoc.org/github.com/awa/go-iap/playstore?status.svg)](https://godoc.org/github.com/awa/go-iap/playstore) * GooglePlay: [![GoDoc](https://godoc.org/github.com/awa/go-iap/playstore?status.svg)](https://godoc.org/github.com/awa/go-iap/playstore)
* Amazon AppStore: [![GoDoc](https://godoc.org/github.com/awa/go-iap/amazon?status.svg)](https://godoc.org/github.com/awa/go-iap/amazon) * Amazon AppStore: [![GoDoc](https://godoc.org/github.com/awa/go-iap/amazon?status.svg)](https://godoc.org/github.com/awa/go-iap/amazon)
* Huawei HMS: [![GoDoc](https://godoc.org/github.com/awa/go-iap/hms?status.svg)](https://godoc.org/github.com/awa/go-iap/hms)
# Installation # Installation
@@ -20,7 +19,6 @@ Current API Documents:
go get github.com/awa/go-iap/appstore go get github.com/awa/go-iap/appstore
go get github.com/awa/go-iap/playstore go get github.com/awa/go-iap/playstore
go get github.com/awa/go-iap/amazon go get github.com/awa/go-iap/amazon
go get github.com/awa/go-iap/hms
``` ```
@@ -80,23 +78,6 @@ func main() {
} }
``` ```
### In App Purchase (via Huawei Mobile Services)
```
import(
"github.com/awa/go-iap/hms"
)
func main() {
// If "orderSiteURL" and/or "subscriptionSiteURL" are empty,
// they will be default to AppTouch German.
// Please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-common-statement-0000001050986127-V5 for details.
client := hms.New("clientID", "clientSecret", "orderSiteURL", "subscriptionSiteURL")
ctx := context.Background()
resp, err := client.VerifySubscription(ctx, "purchaseToken", "subscriptionID", 1)
}
```
# ToDo # ToDo
- [x] Validator for In App Purchase Receipt (AppStore) - [x] Validator for In App Purchase Receipt (AppStore)
- [x] Validator for Subscription token (GooglePlay) - [x] Validator for Subscription token (GooglePlay)
@@ -115,9 +96,6 @@ This validator uses [Version 3 API](http://developer.android.com/google/play/bil
### In App Purchase (Amazon) ### In App Purchase (Amazon)
This validator uses [RVS for IAP v2.0](https://developer.amazon.com/public/apis/earn/in-app-purchasing/docs-v2/verifying-receipts-in-iap-2.0). This validator uses [RVS for IAP v2.0](https://developer.amazon.com/public/apis/earn/in-app-purchasing/docs-v2/verifying-receipts-in-iap-2.0).
### In App Purchase (HMS)
This validator uses [Version 2 API](https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-common-statement-0000001050986127-V5).
# License # License
go-iap is licensed under the MIT. go-iap is licensed under the MIT.

View File

@@ -171,16 +171,14 @@ type (
// IAPResponseForIOS6 is iOS 6 style receipt schema. // IAPResponseForIOS6 is iOS 6 style receipt schema.
IAPResponseForIOS6 struct { IAPResponseForIOS6 struct {
AutoRenewProductID string `json:"auto_renew_product_id"` AutoRenewProductID string `json:"auto_renew_product_id"`
AutoRenewStatus int `json:"auto_renew_status"` AutoRenewStatus int `json:"auto_renew_status"`
CancellationReason string `json:"cancellation_reason,omitempty"` CancellationReason string `json:"cancellation_reason,omitempty"`
ExpirationIntent string `json:"expiration_intent,omitempty"` ExpirationIntent string `json:"expiration_intent,omitempty"`
IsInBillingRetryPeriod string `json:"is_in_billing_retry_period,omitempty"` IsInBillingRetryPeriod string `json:"is_in_billing_retry_period,omitempty"`
Receipt ReceiptForIOS6 `json:"receipt"` LatestReceiptInfo ReceiptForIOS6 `json:"latest_expired_receipt_info"`
LatestExpiredReceiptInfo ReceiptForIOS6 `json:"latest_expired_receipt_info"` Receipt ReceiptForIOS6 `json:"receipt"`
LatestReceipt string `json:"latest_receipt"` Status int `json:"status"`
LatestReceiptInfo ReceiptForIOS6 `json:"latest_receipt_info"`
Status int `json:"status"`
} }
ReceiptForIOS6 struct { ReceiptForIOS6 struct {

View File

@@ -21,9 +21,6 @@ const (
NotificationTypeDidChangeRenewalStatus NotificationType = "DID_CHANGE_RENEWAL_STATUS" NotificationTypeDidChangeRenewalStatus NotificationType = "DID_CHANGE_RENEWAL_STATUS"
// Subscription failed to renew due to a billing issue. // Subscription failed to renew due to a billing issue.
NotificationTypeDidFailToRenew NotificationType = "DID_FAIL_TO_RENEW" NotificationTypeDidFailToRenew NotificationType = "DID_FAIL_TO_RENEW"
// Indicates that App Store successfully refunded a transaction
NotificationTypeRefund NotificationType = "REFUND"
) )
type NotificationEnvironment string type NotificationEnvironment string
@@ -93,7 +90,7 @@ type SubscriptionNotification struct {
// HACK (msyrus): Separate Subscriptiton Notification from Notification verification response // HACK (msyrus): Separate Subscriptiton Notification from Notification verification response
Status int `json:"status,omitempty"` Status int `json:"status,omitempty"`
Receipt NotificationReceipt `json:"receipt"` Receipt NotificationReceipt `json:"recipt"`
SubscriptionRetryFlag string `json:"is_in_billing_retry_period"` SubscriptionRetryFlag string `json:"is_in_billing_retry_period"`
// Posted if the notification_type is RENEWAL or INTERACTIVE_RENEWAL, and only if the renewal is successful. // Posted if the notification_type is RENEWAL or INTERACTIVE_RENEWAL, and only if the renewal is successful.

View File

@@ -70,8 +70,6 @@ func HandleError(status int) error {
e = ErrReceiptIsForTest e = ErrReceiptIsForTest
case 21008: case 21008:
e = ErrReceiptIsForProduction e = ErrReceiptIsForProduction
case 21009:
e = ErrInternalDataAccessError
case 21010: case 21010:
e = ErrReceiptUnauthorized e = ErrReceiptUnauthorized
default: default:
@@ -91,7 +89,7 @@ func New() *Client {
ProductionURL: ProductionURL, ProductionURL: ProductionURL,
SandboxURL: SandboxURL, SandboxURL: SandboxURL,
httpCli: &http.Client{ httpCli: &http.Client{
Timeout: 30 * time.Second, Timeout: 10 * time.Second,
}, },
} }
return client return client
@@ -168,6 +166,7 @@ func (c *Client) parseResponse(resp *http.Response, result interface{}, ctx cont
if resp.StatusCode >= 500 { if resp.StatusCode >= 500 {
return Sandbox, fmt.Errorf("Received http status code %d from the App Store Sandbox: %w", resp.StatusCode, ErrAppStoreServer) return Sandbox, fmt.Errorf("Received http status code %d from the App Store Sandbox: %w", resp.StatusCode, ErrAppStoreServer)
} }
// 21007 is found when the receipt is from the test environment // 21007 is found when the receipt is from the test environment
return Sandbox, json.NewDecoder(resp.Body).Decode(result) return Sandbox, json.NewDecoder(resp.Body).Decode(result)
} }

View File

@@ -58,11 +58,6 @@ func TestHandleError(t *testing.T) {
in: 21008, in: 21008,
out: ErrReceiptIsForProduction, out: ErrReceiptIsForProduction,
}, },
{
name: "status 21009",
in: 21009,
out: ErrInternalDataAccessError,
},
{ {
name: "status 21010", name: "status 21010",
in: 21010, in: 21010,
@@ -96,7 +91,7 @@ func TestNew(t *testing.T) {
ProductionURL: ProductionURL, ProductionURL: ProductionURL,
SandboxURL: SandboxURL, SandboxURL: SandboxURL,
httpCli: &http.Client{ httpCli: &http.Client{
Timeout: 30 * time.Second, Timeout: 10 * time.Second,
}, },
} }

4
go.mod
View File

@@ -1,6 +1,6 @@
module github.com/awa/go-iap module git.deineagentur.com/DeineAgenturUG/go-iap
go 1.12 go 1.13
require ( require (
cloud.google.com/go v0.39.0 // indirect cloud.google.com/go v0.39.0 // indirect

View File

@@ -1,205 +0,0 @@
package hms
import (
"crypto/md5"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
// HMS OAuth url
const tokenURL = "https://oauth-login.cloud.huawei.com/oauth2/v3/token"
// AccessToken expires grace period in seconds.
// The actural ExpiredAt will be substracted with this number to avoid boundray problems.
const accessTokenExpiresGracePeriod = 60
// global variable to store API AccessToken.
// All clients within an instance share one AccessToken grantee scalebility and to avoid rate limit.
var applicationAccessTokens = make(map[[16]byte]ApplicationAccessToken)
// lock when writing to applicationAccessTokens map
var applicationAccessTokensLock sync.Mutex
// ApplicationAccessToken model, received from HMS OAuth API
// https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/open-platform-oauth-0000001050123437-V5#EN-US_TOPIC_0000001050123437__section12493191334711
type ApplicationAccessToken struct {
// App-level access token.
AccessToken string `json:"access_token"`
// Remaining validity period of an access token, in seconds.
ExpiresIn int64 `json:"expires_in"`
// This value is always Bearer, indicating the type of the returned access token.
// TokenType string `json:"token_type"`
// Save the timestamp when AccessToken is obtained
ExpiredAt int64 `json:"-"`
// Request header string
HeaderString string `json:"-"`
}
// Client implements VerifySignature, VerifyOrder and VerifySubscription methods
type Client struct {
clientID string
clientSecret string
clientIDSecretHash [16]byte
httpCli *http.Client
orderSiteURL string // site URL to request order information
subscriptionSiteURL string // site URL to request subscription information
}
// New returns client with credentials.
// Required client_id and client_secret which could be acquired from the HMS API Console.
// When user accountFlag is not equals to 1, orderSiteURL/subscriptionSiteURL are the site URLs that will be used to connect to HMS IAP API services.
// If orderSiteURL or subscriptionSiteURL are not set, default to AppTouch Germany site.
//
// Please refer https://developer.huawei.com/consumer/en/doc/start/api-console-guide
// and https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-common-statement-0000001050986127-V5 for details.
func New(clientID, clientSecret, orderSiteURL, subscriptionSiteURL string) *Client {
// Set default order / subscription iap site to AppTouch Germany if it is not provided
if !strings.HasPrefix(orderSiteURL, "http") {
orderSiteURL = "https://orders-at-dre.iap.dbankcloud.com"
}
if !strings.HasPrefix(subscriptionSiteURL, "http") {
subscriptionSiteURL = "https://subscr-at-dre.iap.dbankcloud.com"
}
// Create http client
return &Client{
clientID: clientID,
clientSecret: clientSecret,
clientIDSecretHash: md5.Sum([]byte(clientID + clientSecret)),
httpCli: &http.Client{
Timeout: 10 * time.Second,
},
orderSiteURL: orderSiteURL,
subscriptionSiteURL: subscriptionSiteURL,
}
}
// GetApplicationAccessTokenHeader obtain OAuth AccessToken from HMS
//
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/atdemo.go#L37
func (c *Client) GetApplicationAccessTokenHeader() (string, error) {
// To complie with the rate limit (1000/5min as of July 24th, 2020)
// new AccessTokens are requested only when it is expired.
// Please refer https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/open-platform-oauth-0000001050123437-V5 for detailes
if applicationAccessTokens[c.clientIDSecretHash].ExpiredAt > time.Now().Unix() {
return applicationAccessTokens[c.clientIDSecretHash].HeaderString, nil
}
urlValue := url.Values{"grant_type": {"client_credentials"}, "client_secret": {c.clientSecret}, "client_id": {c.clientID}}
resp, err := c.httpCli.PostForm(tokenURL, urlValue)
if err != nil {
return "", err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var atResponse ApplicationAccessToken
json.Unmarshal(bodyBytes, &atResponse)
if atResponse.AccessToken != "" {
// update expire time
atResponse.ExpiredAt = atResponse.ExpiresIn + time.Now().Unix() - accessTokenExpiresGracePeriod
// parse request header string
atResponse.HeaderString = fmt.Sprintf(
"Basic %s",
base64.StdEncoding.EncodeToString([]byte(
fmt.Sprintf("APPAT:%s",
atResponse.AccessToken,
),
)),
)
// save AccessToken info to global variable
applicationAccessTokensLock.Lock()
applicationAccessTokens[c.clientIDSecretHash] = atResponse
applicationAccessTokensLock.Unlock()
return atResponse.HeaderString, nil
}
return "", errors.New("Get token fail, " + string(bodyBytes))
}
// Returns root order URL by flag, prefixing with "https://"
func (c *Client) getRootOrderURLByFlag(flag int64) string {
switch flag {
case 1:
return "https://orders-at-dre.iap.dbankcloud.com"
}
return c.orderSiteURL
}
// Returns root subscription URL by flag, prefixing with "https://"
func (c *Client) getRootSubscriptionURLByFlag(flag int64) string {
switch flag {
case 1:
return "https://subscr-at-dre.iap.dbankcloud.com"
}
return c.subscriptionSiteURL
}
// get error based on result code returned from api
func (c *Client) getResponseErrorByCode(code string) error {
switch code {
case "0":
return nil
case "5":
return ErrorResponseInvalidParameter
case "6":
return ErrorResponseCritical
case "8":
return ErrorResponseProductNotBelongToUser
case "9":
return ErrorResponseConsumedProduct
case "11":
return ErrorResponseAbnormalUserAccount
default:
return ErrorResponseUnknown
}
}
// Errors
// ErrorResponseUnknown error placeholder for undocumented errors
var ErrorResponseUnknown error = errors.New("Unknown error from API response")
// ErrorResponseSignatureVerifyFailed failed to verify dataSignature against the response json string.
// https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/verifying-signature-returned-result-0000001050033088-V5
// var ErrorResponseSignatureVerifyFailed error = errors.New("Failed to verify dataSignature against the response json string")
// ErrorResponseInvalidParameter The parameter passed to the API is invalid.
// This error may also indicate that an agreement is not signed or parameters are not set correctly for the in-app purchase settlement in HUAWEI IAP, or the required permission is not in the list.
//
// Check whether the parameter passed to the API is correctly set. If so, check whether required settings in HUAWEI IAP are correctly configured.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-error-code-0000001050166248-V5
var ErrorResponseInvalidParameter error = errors.New("The parameter passed to the API is invalid")
// ErrorResponseCritical A critical error occurs during API operations.
//
// Rectify the fault based on the error information in the response. If the fault persists, contact Huawei technical support.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-error-code-0000001050166248-V5
var ErrorResponseCritical error = errors.New("A critical error occurs during API operations")
// ErrorResponseProductNotBelongToUser A user failed to consume or confirm a product because the user does not own the product.
//
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-error-code-0000001050166248-V5
var ErrorResponseProductNotBelongToUser error = errors.New("A user failed to consume or confirm a product because the user does not own the product")
// ErrorResponseConsumedProduct The product cannot be consumed or confirmed because it has been consumed or confirmed.
//
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-error-code-0000001050166248-V5
var ErrorResponseConsumedProduct error = errors.New("The product cannot be consumed or confirmed because it has been consumed or confirmed")
// ErrorResponseAbnormalUserAccount The user account is abnormal, for example, the user has been deregistered.
//
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-error-code-0000001050166248-V5
var ErrorResponseAbnormalUserAccount error = errors.New("The user account is abnormal, for example, the user has been deregistered")

View File

@@ -1,488 +0,0 @@
package hms
// InAppPurchaseData json model. Used when requesting In-App order and / or subscription verification.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
type InAppPurchaseData struct {
// App ID.
ApplicationID int64 `json:"applicationId"`
// For consumables or non-consumables, the value is always false.
// For subscriptions, possible values are:
// true: A subscription is in active state and will be automatically renewed on the next renewal date.
// false: A user has canceled the subscription. The user can access the subscribed content
// before the next renewal date but will be unable to access the content after the date
// unless the user enables automatic renewal. If a grace period is provided,
// this value remains true for the subscription as long as it is still in the grace period.
// The next settlement date is automatically extended every day until the grace period ends
// or the user changes the payment method.
AutoRenewing bool `json:"autoRenewing"`
// Order ID, which uniquely identifies a transaction and is generated by the Huawei IAP server during payment.
OrderID string `json:"orderId"`
// Product type. Possible values are:
// 0: consumable
// 1: non-consumable
// 2: subscription
Kind int64 `json:"kind"`
// App package name.
PackageName string `json:"packageName,omitempty"`
// Product ID. Each product must have a unique ID, which is maintained in the PMS or passed when the app initiates a purchase.
ProductID string `json:"productId"`
// Product name.
ProductName string `json:"productName,omitempty"`
// Timestamp of the purchase time, which is the number of milliseconds from 00:00:00 on January 1, 1970 to the purchase time.
PurchaseTime int64 `json:"purchaseTime,omitempty"`
// Transaction status. Possible values are:
// -1: initialized
// 0: purchased
// 1: canceled
// 2: refunded
PurchaseState int64 `json:"purchaseState"`
// Information stored on the merchant side, which is passed by the app when the payment API is called.
DeveloperPayload string `json:"developerPayload,omitempty"`
// Challenge defined when an app initiates a consumption request.
// The challenge uniquely identifies the consumption request and exists only for one-off products.
DeveloperChallenge string `json:"developerChallenge,omitempty"`
// Consumption status, which exists only for one-off products. Possible values are:
// 0: not consumed
// 1: consumed
ConsumptionState string `json:"consumptionState,omitempty"`
// Purchase token, which uniquely identifies the mapping between a product and a user.
// It is generated by the Huawei IAP server when the payment is complete.
// NOTE:
// * This parameter uniquely identifies the mapping between a product and a user.
// It does not change when the subscription is renewed.
// * Currently, the value contains 92 characters and its length may be expanded.
// If the value needs to be stored, you are advised to reserve 128 characters.
PurchaseToken string `json:"purchaseToken"`
// Purchase type. Possible values are:
// 0: in the sandbox
// 1: in the promotion period (currently unsupported)
// This parameter is not returned during formal purchase.
// To avoid default value issues. check if PurchaseType != nil first, then read *PurchaseType.
PurchaseType *int64 `json:"purchaseType,omitempty"`
// Currency. The value must comply with the ISO 4217 standard.
Currency string `json:"currency,omitempty"`
// Value after the actual price of a product is multiplied by 100. The actual price is accurate to two decimal places.
// For example, if the value of this parameter is 501, the actual product price is 5.01.
Price int64 `json:"price,omitempty"`
// Country or region code, which is used to identify a country or region. The value must comply with the ISO 3166 standard.
Country string `json:"country,omitempty"`
// Payment method. Possible values are:
// 0: HUAWEI Point
// 3: credit card
// 4: Alipay
// 6: carrier billing
// 13: PayPal
// 16: debit card
// 17: WeChat Pay
// 19: gift card
// 20: balance
// 21: HUAWEI Point card
// 24: WorldPay
// 31: Huawei Pay
// 32: Ant Credit Pay
// 200: M-Pesa
PayType string `json:"payType,omitempty"`
// Transaction order ID.
PayOrderID string `json:"payOrderId,omitempty"`
// Account type. Possible values are:
// 0: HUAWEI ID
// 1: AppTouch user account
AccountFlag int64 `json:"accountFlag,omitempty"`
// ===== The following parameters are returned only in the subscription scenario. =====
// Order ID generated by the Huawei IAP server during fee deduction for the previous renewal.
// The parameter value is the same as that of orderId when a subscription is purchased for the first time.
LastOrderID string `json:"lastOrderId"`
// ID of the subscription group to which a subscription belongs.
ProductGroup string `json:"productGroup,omitempty"`
// Timestamp of the purchase time, which is the number of milliseconds from 00:00:00 on January 1, 1970 to the purchase time.
//
// If the purchase is not complete, this parameter is left empty.
// PurchaseTime int64 `json:"purchaseTime,omitempty"`
// Timestamp of the first fee deduction time, which is the number of
// milliseconds from 00:00:00 on January 1, 1970 to the first successful fee deduction time.
OriPurchaseTime int64 `json:"oriPurchaseTime,omitempty"`
// Subscription ID.
//
// NOTE: This parameter uniquely identifies the mapping between a product and a user. It does not change when the subscription is renewed.
SubscriptionID string `json:"subscriptionId,omitempty"`
// Original subscription ID. If this value is not empty, the current subscription is switched from another one.
// It can be linked to the original subscription information.
OriSubscriptionID string `json:"oriSubscriptionId,omitempty"`
// Purchase quantity.
Quantity int64 `json:"quantity,omitempty"`
// Days of a paid subscription, excluding the free trial period and promotion period.
DaysLasted int64 `json:"daysLasted,omitempty"`
// Number of successful renewal periods. How many time the subscription has been renewed, excludes promotion.
// If the value is 0 or does not exist, no renewal has been performed successfully.
NumOfPeriods int64 `json:"numOfPeriods,omitempty"`
// Number of successful renewal periods with promotion.
NumOfDiscount int64 `json:"numOfDiscount,omitempty"`
// Timestamp of the subscription expiration time. In milliseconds.
//
// For an automatic renewal receipt where the fee has been deducted successfully, this time indicates the renewal date or expiration date.
// If the value is a past time, the subscription has expired.
ExpirationDate int64 `json:"expirationDate,omitempty"`
// Reason why a subscription expires. Possible values are:
// 1: canceled by a user
// 2: product being unavailable
// 3: abnormal user signing information
// 4: billing error
// 5: price increase disagreed with by a user
// 6: unknown error
// If there are multiple exceptions, a smaller number indicates a higher priority (1 > 2 > 3...).
ExpirationIntent int64 `json:"expirationIntent,omitempty"`
// Indicates whether the system is still trying to renew an expired subscription. Possible values are:
// 0: no
// 1: yes
RetryFlag int64 `json:"retryFlag,omitempty"`
// Indicates whether a subscription is in a renewal period with promotion. Possible values are:
// 0: no
// 1: yes
IntroductoryFlag int64 `json:"introductoryFlag,omitempty"`
// Indicates whether a subscription is in a free trial period. Possible values are:
// 0: no
// 1: yes
TrialFlag int64 `json:"trialFlag,omitempty"`
// Time when a subscription is revoked. A refund is made and the service is unavailable immediately.
// This value is returned when a user:
// a. makes a complaint and revokes a subscription through the customer service personnel; or
// b. performs subscription upgrade or crossgrade that immediately takes effect and revokes the previous subscription.
// Note: If a receipt is revoked, it is deemed that the purchase is not complete.
CancelTime int64 `json:"cancelTime,omitempty"`
// Cause of subscription cancellation. Possible values are:
// 0: other causes. For example, a user mistakenly purchases a subscription and has to cancel it.
// 1: A user encounters a problem within the app and cancels the subscription.
// 2: A user performs subscription upgrade or crossgrade.
// Note: If this parameter is left empty but the cancelTime parameter has a value,
// the cancellation is caused by an operation such as upgrade.
CancelReason int64 `json:"cancelReason,omitempty"`
// App information. This parameter is reserved.
AppInfo string `json:"appInfo,omitempty"`
// Indicates whether a user has disabled the subscription notification function. Possible values are:
// 0: no
// 1: yes
// If the user disables the subscription notification function, no subscription notification will be sent to this user.
NotifyClosed int64 `json:"notifyClosed,omitempty"`
// Renewal status. Possible values are:
// 1: The subscription renewal is normal.
// 0: The user cancels subscription renewal.
// For auto-renewable subscriptions, this parameter is valid for both valid and expired subscriptions. However, it does not represent users' subscription status. Generally, when the value is 0, the app can provide other subscription options for the user, for example, recommending another subscription with a lower level in the same group. The value 0 indicates that a user proactively cancels the subscription.
RenewStatus int64 `json:"renewStatus,omitempty"`
// User opinion on the price increase of a product. Possible values are:
// 1: The user has agreed with the price increase.
// 0: The user does not take any action. After the subscription expires, it becomes invalid.
PriceConsentStatus int64 `json:"priceConsentStatus,omitempty"`
// Price used upon the next renewal. It is provided as a reference for users when the priceConsentStatus parameter is returned.
RenewPrice int64 `json:"renewPrice,omitempty"`
// true: A user has been charged for a product, the product has not expired, and no refund has been made. In this case, you can provide services for the user.
// false: The purchase of a product is not finished, the product has expired, or a refund has been made for the product after its purchase.
//
// NOTE
// If a user has canceled a subscription, the subIsvalid parameter value is still true until the subscription expires.
SubIsValid bool `json:"subIsvalid,omitempty"`
// Indicates whether to postpone the settlement date.
// 1: yes
DeferFlag int64 `json:"deferFlag,omitempty"`
// Subscription cancellation initiator. Possible values are:
// 0: user
// 1: developer
// 2: Huawei
CancelWay int64 `json:"cancelWay,omitempty"`
// Timestamp (milliseconds in UTC) when you set a subscription renewal to be stopped in the future.
// The subscription is still valid within the validity period, but the renewal will be stopped in the future. No refund is required.
// NOTE:
// cancelWay and cancellationTime are displayed when a subscription renewal stops (no refund is involved).
CancellationTime int64 `json:"cancellationTime,omitempty"`
// Number of days for retaining a subscription relationship after the subscription is canceled.
CancelledSubKeepDays int64 `json:"cancelledSubKeepDays,omitempty"`
// Confirmation status. Possible values are:
// 0: not confirmed
// 1: confirmed
// If this parameter is left empty, no confirmation is required.
Confirmed int64 `json:"confirmed,omitempty"`
// Timestamp (milliseconds in UTC) when a paused subscription is resumed.
ResumeTime int64 `json:"resumeTime,omitempty"`
// Cancellation reason. Possible values are:
// 0: others
// 1: too high fee
// 2: technical problem, for example, product not provided
// 5: in the blocklist because of fraud
// 7: subscription switchover
// 9: service being rarely used and not required
// 10: other better apps
SurveyReason int64 `json:"surveyReason,omitempty"`
// When the value of surveyReason is 0, this parameter is used to collect the cancellation reason entered by users.
SurveyDetails string `json:"surveyDetails,omitempty"`
}
// CanceledPurchaseList response from query canceled or refunded purchase list
//
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-cancel-or-refund-record-0000001050746117-V5
type CanceledPurchaseList struct {
// Result code. Possible values are:
// 0: success
// Other values: failure. For details about the result codes, please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-error-code-0000001050166248-V5
ResponseCode string `json:"responseCode"`
// Response description.
ResponseMessage string `json:"responseMessage,omitempty"`
// List of canceled or refunded purchase information, in JSON strings. Each string indicates a purchase record.
//
// For details about the purchase information format, please refer to CanceledPurchase{}
CancelledPurchaseList string `json:"cancelledPurchaseList,omitempty"`
// Token to query data on the next page. If a value is returned, pass it in the next query request to query data on the next page.
ContinuationToken string `json:"continuationToken,omitempty"`
}
// CanceledPurchase individual canceled purchase information, for CanceledPurchaseList.
//
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-cancel-or-refund-record-0000001050746117-V5
type CanceledPurchase struct {
// Unique order ID of a subscription or subscription renewal.
OrderID string `json:"orderId"`
// Product ID.
ProductID string `json:"productId"`
// Purchase token.
PurchaseToken string `json:"purchaseToken"`
// Purchase timestamp in UTC.
PurchaseTime int64 `json:"purchaseTime"`
// Cancellation or refund timestamp in UTC.
CancelledTime int64 `json:"cancelledTime"`
// Cancellation or refund initiator. Possible values are:
// 0: user
// 1: developer
// 2: Huawei
CancelledSource int64 `json:"cancelledSource"`
// Cancellation or refund reason. Possible values are:
// 0: others
// 1: user repentance
// 2: product not provided
// 3: abnormal app service
// 4: accidental purchase
// 5: fraud
// 6: chargeback
// 7: upgrade or downgrade
// 8: user service area change
CancelledReason int64 `json:"cancelledReason"`
}
// Below are all constants that can be used to determine different parameter states in IAP Purchase Data
// Constants for InAppPurchaseData.Kind product type
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataKindConsumable int64 = 0
InAppPurchaseDataKindNonConsumable int64 = 1
InAppPurchaseDataKindSubscription int64 = 2
)
// Constants for InAppPurchaseData.PurchaseState
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataPurchaseStateInitialized int64 = -1
InAppPurchaseDataPurchaseStatePurchased int64 = 0
InAppPurchaseDataPurchaseStateCanceled int64 = 1
InAppPurchaseDataPurchaseStateRefunded int64 = 2
)
// Constants for InAppPurchaseData.ConsumptionState
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataConsumptionStateNotConsumed string = "0"
InAppPurchaseDataConsumptionStateConsumed string = "0"
)
// Constants for InAppPurchaseData.PurchaseType indicates if the product is purchased through sandbox environment or promotion.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
//
// Note: You should always check InAppPurchaseData.PurchaseType != nil first.
const (
InAppPurchaseDataPurchaseTypeSandbox int64 = 0
InAppPurchaseDataPurchaseTypePromotion int64 = 1
)
// Constants for InAppPurchaseData.PayType payment methods when buying the product.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5#EN-US_TOPIC_0000001050986133__section135412662210
const (
InAppPurchaseDataPayTypeHuaweiPoint string = "0"
InAppPurchaseDataPayTypeCreditCard string = "3"
InAppPurchaseDataPayTypeAlipay string = "4"
InAppPurchaseDataPayTypeCarrier string = "6"
InAppPurchaseDataPayTypePayPal string = "13"
InAppPurchaseDataPayTypeDebitCard string = "16"
InAppPurchaseDataPayTypeWeChatPay string = "17"
InAppPurchaseDataPayTypeGiftCard string = "19"
InAppPurchaseDataPayTypeBalance string = "20"
InAppPurchaseDataPayTypeHuaweiPointCard string = "21"
InAppPurchaseDataPayTypeWorldPay string = "24"
InAppPurchaseDataPayTypeHuaweiPay string = "31"
InAppPurchaseDataPayTypeAntCreditPay string = "32"
InAppPurchaseDataPayTypeMPesa string = "200" // M-Pesa
)
// Constants for InAppPurchaseData.AccountFlag Account type.
// See https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-common-statement-0000001050986127-V5#EN-US_TOPIC_0000001050986127__section1741234185817 for details.
const (
InAppPurchaseDataAccountFlagHuaweiID int64 = 0
InAppPurchaseDataAccountFlagAppTouch int64 = 1
)
// Constants for InAppPurchaseData.ExpirationIntent Reasons why a subscription expires.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataExpirationIntentCanceledByUser int64 = 1
InAppPurchaseDataExpirationIntentProductUnavaliable int64 = 2
InAppPurchaseDataExpirationIntentAbnormalUserSigning int64 = 3
InAppPurchaseDataExpirationIntentBillingError int64 = 4
InAppPurchaseDataExpirationIntentPriceIncreaseDisagreed int64 = 5
InAppPurchaseDataExpirationIntentUnknownError int64 = 6
)
// Constants for InAppPurchaseData.RetryFlag Indicates whether the system still tries to renew an expired subscription.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataRetryFlagNo int64 = 0
InAppPurchaseDataRetryFlagYes int64 = 1
)
// Constants for InAppPurchaseData.IntroductoryFlag Indicates whether a subscription is in the renewal period with promotion or not.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataIntroductoryFlagNo int64 = 0
InAppPurchaseDataIntroductoryFlagYes int64 = 1
)
// Constants for InAppPurchaseData.TrialFlag Indicates whether a subscription is in the free trial period or not.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataTrialFlagNo int64 = 0
InAppPurchaseDataTrialFlagYes int64 = 1
)
// Constants for InAppPurchaseData.CancelReason Causes of subscription cancellation.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
//
// Note: You should check SubIsValid first.
const (
InAppPurchaseDataCancelReasonOther int64 = 0 // Other causes. For example, a user mistakenly purchases a subscription and has to cancel it.
InAppPurchaseDataCancelReasonUserIssue int64 = 1 // A user encounters a problem within the app and cancels the subscription.
InAppPurchaseDataCancelReasonUpgradeOrCrossgrade int64 = 2 // A user performs subscription upgrade or crossgrade.
)
// Constants for InAppPurchaseData.NotifyClosed Indicates whether a user has disabled the subscription notification function.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataNotifyClosedNo int64 = 0
InAppPurchaseDataNotifyClosedYes int64 = 1
)
// Constants for InAppPurchaseData.RenewStatus Indecates whether the auto-renewal is canceled or not.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataRenewStatusCanceledByUser int64 = 0 // A user proactively canceled the subscription auto-renewal.
InAppPurchaseDataRenewStatusNormal int64 = 1 // The subscription will be auto-renewed.
)
// Constants for InAppPurchaseData.PriceConsentStatus User opinions collected when the product price increased.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataPriceConsentStatusNoResponse int64 = 0 // The user did not give any comfirmation. Subscription will be terminated without renewal after expires.
InAppPurchaseDataPriceConsentStatusAgreed int64 = 1 // The user has agreed with the price increase.
)
// Constants for InAppPurchaseData.DeferFlag Indicates whether to postpone the settlement date.
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
const (
InAppPurchaseDataDeferFlagYes int64 = 1
)
// Constants for InAppPurchaseData.CancelWay how does the subscription be canceled
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5
//
// Note: You should check SubIsValid first.
const (
InAppPurchaseDataCancelWayByUser int64 = 0
InAppPurchaseDataCancelWayByDeveloper int64 = 1
InAppPurchaseDataCancelWayByHuawei int64 = 2
)
// Constants for CanceledPurchase.CancelledSource
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-cancel-or-refund-record-0000001050746117-V5
const (
CanceledPurchaseCancelledSourceByUser int64 = 0
CanceledPurchaseCancelledSourceByDeveloper int64 = 1
CanceledPurchaseCancelledSourceByHuawei int64 = 2
)
// Constants for CanceledPurchase.CancelledReason
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-cancel-or-refund-record-0000001050746117-V5
const (
CanceledPurchaseCancelledReasonOther int64 = 0
CanceledPurchaseCancelledReasonUserRepentance int64 = 1
CanceledPurchaseCancelledReasonProductNotProvided int64 = 2
CanceledPurchaseCancelledReasonAbnormal int64 = 3
CanceledPurchaseCancelledReasonAccidental int64 = 4
CanceledPurchaseCancelledReasonFraud int64 = 5
CanceledPurchaseCancelledReasonChargeback int64 = 6
CanceledPurchaseCancelledReasonUpgradeOrDowngrade int64 = 7
CanceledPurchaseCancelledReasonServiceAreaChanged int64 = 8
)

View File

@@ -1,104 +0,0 @@
package hms
import (
"context"
"encoding/json"
"fmt"
"log"
)
// CancelSubscriptionRenewal Cancel a aubscription from auto-renew when expired.
// Note that this does not cancel the current subscription.
// If you want to revoke a subscription, use Client.RevokeSubscription() instead.
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/subscription.go#L54
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-cancel-subscription-0000001050746115-V5
func (c *Client) CancelSubscriptionRenewal(ctx context.Context, purchaseToken, subscriptionID string, accountFlag int64) (success bool, responseMessage string, err error) {
bodyMap := map[string]string{
"subscriptionId": subscriptionID,
"purchaseToken": purchaseToken,
}
var resp ModifySubscriptionResponse
success, resp, err = c.modifySubscriptionQuery(ctx, bodyMap, accountFlag, "/sub/applications/v2/purchases/stop")
responseMessage = resp.ResponseMessage
return
}
// ExtendSubscription extend the current subscription expiration date without chanrging the customer.
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/subscription.go#L68
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-refund-subscription-fee-0000001050986131-V5
func (c *Client) ExtendSubscription(ctx context.Context, purchaseToken, subscriptionID string, currentExpirationTime, desiredExpirationTime int64, accountFlag int64) (success bool, responseMessage string, newExpirationTime int64, err error) {
bodyMap := map[string]string{
"subscriptionId": subscriptionID,
"purchaseToken": purchaseToken,
"currentExpirationTime": fmt.Sprintf("%v", currentExpirationTime),
"desiredExpirationTime": fmt.Sprintf("%v", desiredExpirationTime),
}
var resp ModifySubscriptionResponse
success, resp, err = c.modifySubscriptionQuery(ctx, bodyMap, accountFlag, "/sub/applications/v2/purchases/delay")
responseMessage = resp.ResponseMessage
newExpirationTime = resp.NewExpirationTime
return
}
// RefundSubscription refund a subscription payment.
// Note that this does not cancel the current subscription.
// If you want to revoke a subscription, use Client.RevokeSubscription() instead.
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/subscription.go#L84
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-refund-subscription-fee-0000001050986131-V5
func (c *Client) RefundSubscription(ctx context.Context, purchaseToken, subscriptionID string, accountFlag int64) (success bool, responseMessage string, err error) {
bodyMap := map[string]string{
"subscriptionId": subscriptionID,
"purchaseToken": purchaseToken,
}
var resp ModifySubscriptionResponse
success, resp, err = c.modifySubscriptionQuery(ctx, bodyMap, accountFlag, "/sub/applications/v2/purchases/returnFee")
responseMessage = resp.ResponseMessage
return
}
// RevokeSubscription will revoke and issue a refund on a subscription immediately.
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/subscription.go#L99
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-unsubscribe-0000001051066056-V5
func (c *Client) RevokeSubscription(ctx context.Context, purchaseToken, subscriptionID string, accountFlag int64) (success bool, responseMessage string, err error) {
bodyMap := map[string]string{
"subscriptionId": subscriptionID,
"purchaseToken": purchaseToken,
}
var resp ModifySubscriptionResponse
success, resp, err = c.modifySubscriptionQuery(ctx, bodyMap, accountFlag, "/sub/applications/v2/purchases/withdrawal")
responseMessage = resp.ResponseMessage
return
}
// ModifySubscriptionResponse JSON response from {rootUrl}/sub/applications/v2/purchases/stop|delay|returnFee|withdrawal
type ModifySubscriptionResponse struct {
ResponseCode string `json:"responseCode"`
ResponseMessage string `json:"responseMessage;omitempty"`
NewExpirationTime int64 `json:"newExpirationTime;omitempty"`
}
// public method to query {rootUrl}/sub/applications/v2/purchases/stop|delay|returnFee|withdrawal
func (c *Client) modifySubscriptionQuery(ctx context.Context, requestBodyMap map[string]string, accountFlag int64, uri string) (success bool, response ModifySubscriptionResponse, err error) {
url := c.getRootSubscriptionURLByFlag(accountFlag) + uri
bodyBytes, err := c.sendJSONRequest(ctx, url, requestBodyMap)
if err != nil {
return false, response, err
}
// debug
log.Println("url:", url)
log.Println("request:", requestBodyMap)
log.Printf("%s", bodyBytes)
if err := json.Unmarshal(bodyBytes, &response); err != nil {
return false, response, err
}
switch response.ResponseCode {
case "0":
return true, response, nil
default:
return false, response, c.getResponseErrorByCode(response.ResponseCode)
}
}

View File

@@ -1,103 +0,0 @@
package hms
// SubscriptionNotification Request parameters when a developer server is called by HMS API.
//
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-notifications-about-subscription-events-0000001050706084-V5
type SubscriptionNotification struct {
// Notification message, which is a JSON string. For details, please refer to statusUpdateNotification.
StatusUpdateNotification string `json:"statusUpdateNotification"`
// Signature string for the StatusUpdateNotification parameter. The signature algorithm is SHA256withRSA.
//
// After your server receives the signature string, you need to use the public payment key to verify the signature of StatusUpdateNotification in JSON format.
// For details, please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/verifying-signature-returned-result-0000001050033088-V5
//
// For details about how to obtain the public key, please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/query-payment-info-0000001050166299-V5
NotifycationSignature string `json:"notifycationSignature"`
}
// StatusUpdateNotification JSON content when unmarshal NotificationRequest.StatusUpdateNotification
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-notifications-about-subscription-events-0000001050706084-V5#EN-US_TOPIC_0000001050706084__section18290165220716
type StatusUpdateNotification struct {
// Environment for sending a notification. Value could be one of either:
// "PROD": general production environment
// "SandBox": sandbox testing environment
Environment string `json:"environment"`
// Notification event type. For details, please refer to const NotificationTypeInitialBuy etc.
NotificationType int64 `json:"notificationType"`
// Subscription ID
SubscriptionID string `json:"subscriptionId"`
// Timestamp, which is passed only when notificationType is CANCEL(1).
CancellationDate int64 `json:"cancellationDate,omitempty"`
// Order ID used for payment during subscription renewal.
OrderID string `json:"orderId"`
// PurchaseToken of the latest receipt, which is passed only when notificationType is INITIAL_BUY(0), RENEWAL(2), or INTERACTIVE_RENEWAL(3) and the renewal is successful.
LatestReceipt string `json:"latestReceipt,omitempty"`
// Latest receipt, which is a JSON string. This parameter is left empty when notificationType is CANCEL(1).
// For details about the parameters contained, please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-data-model-0000001050986133-V5#EN-US_TOPIC_0000001050986133__section264617465219
LatestReceiptInfo string `json:"latestReceiptInfo,omitempty"`
// Signature string for the LatestReceiptInfo parameter. The signature algorithm is SHA256withRSA.
//
// After your server receives the signature string, you need to use the public payment key to verify the signature of LatestReceiptInfo in JSON format.
// For details, please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/verifying-signature-returned-result-0000001050033088-V5
//
// For details about how to obtain the public key, please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/query-payment-info-0000001050166299-V5
LatestReceiptInfoSignature string `json:"latestReceiptInfoSignature,omitempty"`
// Token of the latest expired receipt. This parameter has a value only when NotificationType is RENEWAL(2) or INTERACTIVE_RENEWAL(3).
LatestExpiredReceipt string `json:"latestExpiredReceipt,omitempty"`
// Latest expired receipt, which is a JSON string. This parameter has a value only when NotificationType is RENEWAL(2) or INTERACTIVE_RENEWAL(3).
LatestExpiredReceiptInfo string `json:"latestExpiredReceiptInfo,omitempty"`
// Signature string for the LatestExpiredReceiptInfo parameter. The signature algorithm is SHA256withRSA.
//
// After your server receives the signature string, you need to use the public payment key to verify the signature of LatestExpiredReceiptInfo in JSON format.
// For details, please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/verifying-signature-returned-result-0000001050033088-V5
//
// For details about how to obtain the public key, please refer to https://developer.huawei.com/consumer/en/doc/HMSCore-Guides-V5/query-payment-info-0000001050166299-V5
LatestExpiredReceiptInfoSignature string `json:"latestExpiredReceiptInfoSignature,omitempty"`
// Renewal status. Value could be one of either:
// 1: The subscription renewal is normal.
// 0: The user has canceled subscription renewal.
AutoRenewStatus int64 `json:"autoRenewStatus"`
// Refund order ID. This parameter has a value only when NotificationType is CANCEL(1).
RefundPayOrderID string `json:"refundPayOrderId,omitempty"`
// Product ID.
ProductID string `json:"productId"`
// App ID.
ApplicationID string `json:"applicationId,omitempty"`
// Expiration reason. This parameter has a value only when NotificationType is RENEWAL(2) or INTERACTIVE_RENEWAL(3), and the renewal is successful.
ExpirationIntent int64 `json:"expirationIntent,omitempty"`
}
// Constants for StatusUpdateNotification.NotificationType
// https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-notifications-about-subscription-events-0000001050706084-V5#EN-US_TOPIC_0000001050706084__section18290165220716
const (
NotificationTypeInitialBuy int64 = 0
NotificationTypeCancel int64 = 1
NotificationTypeRenewal int64 = 2
NotificationTypeInteractiveRenewal int64 = 3
NotificationTypeNewRenewalPref int64 = 4
NotificationTypeRenewalStopped int64 = 5
NotificationTypeRenewalRestored int64 = 6
NotificationTypeRenewalRecurring int64 = 7
NotificationTypeInGracePeriod int64 = 8
NotificationTypeOnHold int64 = 9
NotificationTypePaused int64 = 10
NotificationTypePausePlanChanged int64 = 11
NotificationTypePriceChangeConfirmed int64 = 12
NotificationTypeDeferred int64 = 13
)

View File

@@ -1,257 +0,0 @@
package hms
import (
"bytes"
"context"
"crypto"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
// VerifySignature validate inapp order or subscription data signature. Returns nil if pass.
//
// Document: https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/verifying-signature-returned-result-0000001050033088-V5
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/demo.go#L60
func VerifySignature(base64EncodedPublicKey string, data string, signature string) (err error) {
publicKeyByte, err := base64.StdEncoding.DecodeString(base64EncodedPublicKey)
if err != nil {
return err
}
pub, err := x509.ParsePKIXPublicKey(publicKeyByte)
if err != nil {
return err
}
hashed := sha256.Sum256([]byte(data))
signatureByte, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return err
}
return rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA256, hashed[:], signatureByte)
}
// SubscriptionVerifyResponse JSON response after requested {rootUrl}/sub/applications/v2/purchases/get
type SubscriptionVerifyResponse struct {
ResponseCode string `json:"responseCode"` // Response code, if = "0" means succeed, for others see https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-error-code-0000001050166248-V5
ResponseMessage string `json:"responseMessage,omitempty"` // Response descriptions, especially when error
InappPurchaseData string `json:"inappPurchaseData,omitempty"` // InappPurchaseData JSON string
}
// VerifySubscription gets subscriptions info with subscriptionId and purchaseToken.
//
// Document: https://developer.huawei.com/consumer/en/doc/development/HMSCore-References-V5/api-subscription-verify-purchase-token-0000001050706080-V5
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/subscription.go#L40
func (c *Client) VerifySubscription(ctx context.Context, purchaseToken, subscriptionID string, accountFlag int64) (InAppPurchaseData, error) {
var iap InAppPurchaseData
dataString, err := c.GetSubscriptionDataString(ctx, purchaseToken, subscriptionID, accountFlag)
if err != nil {
return iap, err
}
if err := json.Unmarshal([]byte(dataString), &iap); err != nil {
return iap, err
}
return iap, nil
}
// GetSubscriptionDataString gets subscriptions response data string.
//
// Document: https://developer.huawei.com/consumer/en/doc/development/HMSCore-References-V5/api-subscription-verify-purchase-token-0000001050706080-V5
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/subscription.go#L40
func (c *Client) GetSubscriptionDataString(ctx context.Context, purchaseToken, subscriptionID string, accountFlag int64) (string, error) {
bodyMap := map[string]string{
"subscriptionId": subscriptionID,
"purchaseToken": purchaseToken,
}
url := c.getRootSubscriptionURLByFlag(accountFlag) + "/sub/applications/v2/purchases/get"
bodyBytes, err := c.sendJSONRequest(ctx, url, bodyMap)
if err != nil {
// log.Printf("GetSubscriptionDataString(): Encounter error: %s", err)
return "", err
}
var resp SubscriptionVerifyResponse
if err := json.Unmarshal(bodyBytes, &resp); err != nil {
return "", err
}
if err := c.getResponseErrorByCode(resp.ResponseCode); err != nil {
return "", err
}
return resp.InappPurchaseData, nil
}
// OrderVerifyResponse JSON response from {rootUrl}/applications/purchases/tokens/verify
type OrderVerifyResponse struct {
ResponseCode string `json:"responseCode"` // Response code, if = "0" means succeed, for others see https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/server-error-code-0000001050166248-V5
ResponseMessage string `json:"responseMessage,omitempty"` // Response descriptions, especially when error
PurchaseTokenData string `json:"purchaseTokenData,omitempty"` // InappPurchaseData JSON string
DataSignature string `json:"dataSignature,omitempty"` // Signature to verify PurchaseTokenData string
}
// VerifyOrder gets order (single item purchase) info with productId and purchaseToken.
//
// Note that this method does not verify the DataSignature, thus security is relied on HTTPS solely.
//
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-order-verify-purchase-token-0000001050746113-V5
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/order.go#L41
func (c *Client) VerifyOrder(ctx context.Context, purchaseToken, productID string, accountFlag int64) (InAppPurchaseData, error) {
var iap InAppPurchaseData
dataString, _, err := c.GetOrderDataString(ctx, purchaseToken, productID, accountFlag)
if err != nil {
return iap, err
}
if err := json.Unmarshal([]byte(dataString), &iap); err != nil {
return iap, err
}
return iap, nil
}
// GetOrderDataString gets order (single item purchase) response data as json string and dataSignature
//
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-order-verify-purchase-token-0000001050746113-V5
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/order.go#L41
func (c *Client) GetOrderDataString(ctx context.Context, purchaseToken, productID string, accountFlag int64) (purchaseTokenData, dataSignature string, err error) {
bodyMap := map[string]string{
"purchaseToken": purchaseToken,
"productId": productID,
}
url := c.getRootOrderURLByFlag(accountFlag) + "/applications/purchases/tokens/verify"
bodyBytes, err := c.sendJSONRequest(ctx, url, bodyMap)
if err != nil {
// log.Printf("GetOrderDataString(): Encounter error: %s", err)
return "", "", err
}
var resp OrderVerifyResponse
if err := json.Unmarshal(bodyBytes, &resp); err != nil {
return "", "", err
}
if err := c.getResponseErrorByCode(resp.ResponseCode); err != nil {
return "", "", err
}
return resp.PurchaseTokenData, resp.DataSignature, nil
}
// Helper function to send http json request and get response bodyBytes.
//
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/demo.go#L33
func (c *Client) sendJSONRequest(ctx context.Context, url string, bodyMap map[string]string) (bodyBytes []byte, err error) {
bodyString, err := json.Marshal(bodyMap)
if err != nil {
return
}
req, err := http.NewRequest("POST", url, bytes.NewReader(bodyString))
if err != nil {
return
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", "application/json; charset=UTF-8")
atHeader, err := c.GetApplicationAccessTokenHeader()
if err == nil {
req.Header.Set("Authorization", atHeader)
} else {
return
}
resp, err := c.httpCli.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
bodyBytes, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return
}
// GetCanceledOrRefundedPurchases gets all revoked purchases in CanceledPurchaseList{}.
// This method allow fetch over 1000 results regardles the cap implied by HMS API. Though you should still limit maxRows to a certain number to increate preformance.
//
// In case of an error, this method might return some fetch results if maxRows greater than 1000 or equals 0.
//
// Source code originated from https://github.com/HMS-Core/hms-iap-serverdemo/blob/92241f97fed1b68ddeb7cb37ea4ca6e6d33d2a87/demo/order.go#L52
// Document: https://developer.huawei.com/consumer/en/doc/HMSCore-References-V5/api-cancel-or-refund-record-0000001050746117-V5
func (c *Client) GetCanceledOrRefundedPurchases(
// context of request
ctx context.Context,
// start time timestamp in milliseconds, if =0, will default to 1 month ago.
startAt int64,
// end time timestamp in milliseconds, if =0, will default to now.
endAt int64,
// rows to return. default to 1000 if maxRows>1000 or equals to 0.
maxRows int,
// Token returned in the last query to query the data on the next page.
continuationToken string,
// Query type. Ignore this parameter when continuationToken is passed. The options are as follows:
// 0: Queries purchase information about consumables and non-consumables. This is the default value.
// 1: Queries all purchase information about consumables, non-consumables, and subscriptions.
productType int64,
// Account flag to determine which API URL to use.
accountFlag int64,
) (canceledPurchases []CanceledPurchase, newContinuationToken string, responseCode string, responseMessage string, err error) {
// default values
if maxRows > 1000 || maxRows < 1 {
maxRows = 1000
}
switch endAt {
case 0:
endAt = time.Now().UnixNano() / 1000000
case startAt:
endAt++
}
bodyMap := map[string]string{
"startAt": fmt.Sprintf("%v", startAt),
"endAt": fmt.Sprintf("%v", endAt),
"maxRows": fmt.Sprintf("%v", maxRows),
"continuationToken": continuationToken,
"type": fmt.Sprintf("%v", productType),
}
url := c.getRootOrderURLByFlag(accountFlag) + "/applications/v2/purchases/cancelledList"
bodyBytes, err := c.sendJSONRequest(ctx, url, bodyMap)
if err != nil {
// log.Printf("GetCanceledOrRefundedPurchases(): Encounter error: %s", err)
}
var cpl CanceledPurchaseList // temporary variable to store api query result
err = json.Unmarshal(bodyBytes, &cpl)
if err != nil {
return canceledPurchases, continuationToken, cpl.ResponseCode, cpl.ResponseMessage, err
}
if cpl.ResponseCode != "0" {
return canceledPurchases, continuationToken, cpl.ResponseCode, cpl.ResponseMessage, c.getResponseErrorByCode(cpl.ResponseCode)
}
err = json.Unmarshal([]byte(cpl.CancelledPurchaseList), &canceledPurchases)
if err != nil {
return canceledPurchases, continuationToken, cpl.ResponseCode, cpl.ResponseMessage, err
}
return canceledPurchases, cpl.ContinuationToken, cpl.ResponseCode, cpl.ResponseMessage, nil
}

View File

@@ -1,63 +1,33 @@
package playstore package playstore
// https://developer.android.com/google/play/billing/rtdn-reference#sub
type SubscriptionNotificationType int
const (
SubscriptionNotificationTypeRecovered SubscriptionNotificationType = iota + 1
SubscriptionNotificationTypeRenewed
SubscriptionNotificationTypeCanceled
SubscriptionNotificationTypePurchased
SubscriptionNotificationTypeAccountHold
SubscriptionNotificationTypeGracePeriod
SubscriptionNotificationTypeRestarted
SubscriptionNotificationTypePriceChangeConfirmed
SubscriptionNotificationTypeDeferred
SubscriptionNotificationTypePaused
SubscriptionNotificationTypePauseScheduleChanged
SubscriptionNotificationTypeRevoked
SubscriptionNotificationTypeExpired
)
// https://developer.android.com/google/play/billing/rtdn-reference#one-time
type OneTimeProductNotificationType int
const (
OneTimeProductNotificationTypePurchased OneTimeProductNotificationType = iota + 1
OneTimeProductNotificationTypeCanceled
)
// DeveloperNotification is sent by a Pub/Sub topic. // DeveloperNotification is sent by a Pub/Sub topic.
// Detailed description is following. // Detailed description is following.
// https://developer.android.com/google/play/billing/rtdn-reference#json_specification // https://developer.android.com/google/play/billing/realtime_developer_notifications.html#json_specification
type DeveloperNotification struct { type DeveloperNotification struct {
Version string `json:"version"` Version string `json:"version"`
PackageName string `json:"packageName"` PackageName string `json:"packageName"`
EventTimeMillis string `json:"eventTimeMillis"` EventTimeMillis string `json:"eventTimeMillis"`
SubscriptionNotification SubscriptionNotification `json:"subscriptionNotification,omitempty"` SubscriptionNotification SubscriptionNotification `json:"subscriptionNotification,omitempty"`
OneTimeProductNotification OneTimeProductNotification `json:"oneTimeProductNotification,omitempty"` TestNotification SubscriptionNotification `json:"testNotification,omitempty"`
TestNotification TestNotification `json:"testNotification,omitempty"`
} }
// SubscriptionNotification has subscription status as notificationType, token and subscription id // SubscriptionNotification has subscription status as notificationType, toke and subscription id
// to confirm status by calling Google Android Publisher API. // to confirm status by calling Google Android Publisher API.
type SubscriptionNotification struct { type SubscriptionNotification struct {
Version string `json:"version"` Version string `json:"version"`
NotificationType SubscriptionNotificationType `json:"notificationType,omitempty"` NotificationType NotificationType `json:"notificationType,omitempty"`
PurchaseToken string `json:"purchaseToken,omitempty"` PurchaseToken string `json:"purchaseToken,omitempty"`
SubscriptionID string `json:"subscriptionId,omitempty"` SubscriptionID string `json:"subscriptionId,omitempty"`
} }
// OneTimeProductNotification has one-time product status as notificationType, token and sku (product id) type NotificationType int
// to confirm status by calling Google Android Publisher API.
type OneTimeProductNotification struct {
Version string `json:"version"`
NotificationType OneTimeProductNotificationType `json:"notificationType,omitempty"`
PurchaseToken string `json:"purchaseToken,omitempty"`
SKU string `json:"sku,omitempty"`
}
// TestNotification is the test publish that are sent only through the Google Play Developer Console const (
type TestNotification struct { NotificationTypeRecovered NotificationType = iota + 1
Version string `json:"version"` NotificationTypeRenewed
} NotificationTypeCanceled
NotificationTypePurchased
NotificationTypeAccountHold
NotificationTypeGracePeriod
NotificationTypeReactivated
)