MIT License

项目介绍

awa/go-iap 是一个托管在 GitHub 上的开源项目,主要使用 Go 编写,采用 MIT License 许可证,目前获得 1.1k 个 Star、242 次 Fork。

仓库全名
awa/go-iap
开源许可证
MIT License
Star 数
1.1k
Fork 数
242
未关闭 Issue
33

README 摘要

go-iap ====== go-iap verifies the purchase receipt via AppStore, GooglePlayStore, Amazon AppStore, HMS or MicrosoftStore. Current API Documents: Installation Quick Start In App Purchase (via App Store) Note: The verifyReceipt API has been deprecated as of 5 Jun 2023. Please use App Store Server API instead. In App Billing (via GooglePlay) In App Purchase (via Amazon App Store) In App Purchase (via Huawei Mobile…

完整内容见 GitHub 原始 README 或本页 。

常见问题

go-iap 用什么语言开发?

主要使用 Go 编写,采用 MIT License 许可证,目前有 1.1k 个 Star。

go-iap 可以免费商用吗?

仓库采用 MIT License 许可证,可免费使用与修改,商业使用请遵守许可证条款(例如保留版权声明与许可声明)。

如何获取 go-iap 的源码?

可以直接克隆仓库:git clone https://github.com/awa/go-iap.git,默认分支为 master;安装与运行步骤见仓库 README。

go-iap 最近还在维护吗?

仓库最近一次更新为 3 周前,当前有 33 个未关闭 Issue;Star 数为 1.1k,可作为社区活跃度的参考。

关于

GitHub 原始描述(英文)

go-iap verifies the purchase receipt via AppStore, GooglePlayStore, AmazonAppStore and Huawei HMS.

描述取自 GitHub 官方 API,保持仓库作者书写的原文。

简要分析

热度分
1612
价值分
714
活跃状态
活跃

语言占比

Go
Makefile

Release

README

go-iap

unit test

go-iap verifies the purchase receipt via AppStore, GooglePlayStore, Amazon AppStore, HMS or MicrosoftStore.

Current API Documents:

  • AppStore: GoDoc
  • AppStore Server API: GoDoc
  • GooglePlay: GoDoc
  • Amazon AppStore: GoDoc
  • Huawei HMS: GoDoc
  • Microsoft Store: GoDoc

Installation

go get github.com/awa/go-iap/appstore
go get github.com/awa/go-iap/playstore
go get github.com/awa/go-iap/amazon
go get github.com/awa/go-iap/hms
go get github.com/awa/go-iap/microsoftstore

Quick Start

In App Purchase (via App Store)

import(
    "github.com/awa/go-iap/appstore"
)

func main() {
	client := appstore.New()
	req := appstore.IAPRequest{
		ReceiptData: "your receipt data encoded by base64",
	}
	resp := &appstore.IAPResponse{}
	ctx := context.Background()
	err := client.Verify(ctx, req, resp)
}

Note: The verifyReceipt API has been deprecated as of 5 Jun 2023. Please use App Store Server API instead.

In App Billing (via GooglePlay)

import(
    "github.com/awa/go-iap/playstore"
)

func main() {
	// You need to prepare a public key for your Android app's in app billing
	// at https://console.developers.google.com.
	jsonKey, err := ioutil.ReadFile("jsonKey.json")
	if err != nil {
		log.Fatal(err)
	}

	client := playstore.New(jsonKey)
	ctx := context.Background()
	resp, err := client.VerifySubscriptionV2(ctx, "package", "purchaseToken")
}

In App Purchase (via Amazon App Store)

import(
    "github.com/awa/go-iap/amazon"
)

func main() {
	client := amazon.New("developerSecret")

	ctx := context.Background()
	resp, err := client.Verify(ctx, "userID", "receiptID")
}

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)
}

In App Store Server API

Note

  • The App Store Server API differentiates between a sandbox and a production environment based on the base URL:

  • If you’re unsure about the environment, follow these steps:

    • Initiate a call to the endpoint using the production URL. If the call is successful, the transaction identifier is associated with the production environment.
    • If you encounter an error code 4040010, indicating a TransactionIdNotFoundError, make a call to the endpoint using the sandbox URL.
    • If this call is successful, the transaction identifier is associated with the sandbox environment. If the call fails with the same error code, the transaction identifier doesn’t exist in either environment.
  • api.NewStoreClientWithSandboxFallback does this for you. It returns an *api.StoreClientWithSandboxFallback, which satisfies api.StoreAPIClient, so it is a drop-in replacement for a client built with api.NewStoreClient.

  • Sandbox fallback

An app distributed through App Review or TestFlight is a production build whose purchases are made in Sandbox, so the production host cannot find those transactions. This client queries production first and retries against Sandbox on TransactionIdNotFoundError.

import(
	"github.com/awa/go-iap/appstore/api"
)

func main() {
	c := &api.StoreConfig{
		KeyContent: []byte(ACCOUNTPRIVATEKEY),
		KeyID:      "FAKEKEYID",
		BundleID:   "fake.bundle.id",
		Issuer:     "xxxxx-xx-xx-xx-xxxxxxxxxx",
		// Sandbox is ignored: both hosts are built.
	}
	a := api.NewStoreClientWithSandboxFallback(c)
	ctx := context.Background()

	// Falls back to Sandbox when production reports the transaction missing.
	response, err := a.GetALLSubscriptionStatuses(ctx, "FAKETRANSACTIONID", nil)
}

The retry applies to the lookups Apple documents as returning TransactionIdNotFoundError: GetTransactionInfo, GetALLSubscriptionStatuses, GetTransactionHistory, GetRefundHistory and GetAppTransactionInfo. Every other method behaves exactly as it does on StoreClient.

Sandbox is also asked when production answers 401: that is how it refuses an app that has never shipped there, as an App Store Commerce Engineer confirmed. Such an app fails before the lookup, so TransactionIdNotFoundError never arrives — Apple’s documented procedure covers only that error.

When the App Store answers without an error code, the status reaches you through the error:

var withStatus interface{ StatusCode() int }
if errors.As(err, &withStatus) && withStatus.StatusCode() == http.StatusTooManyRequests {
	// back off
}

Nothing else is retried. 401 is overloaded, so reach for this client only where a Sandbox answer is acceptable. NewStoreClient never falls back.

  • GetTransactionInfo
import(
	"github.com/awa/go-iap/appstore/api"
)

//  For generate key file and download it, please refer to https://developer.apple.com/documentation/appstoreserverapi/creating_api_keys_to_use_with_the_app_store_server_api
const ACCOUNTPRIVATEKEY = `
    -----BEGIN PRIVATE KEY-----
    FAKEACCOUNTKEYBASE64FORMAT
    -----END PRIVATE KEY-----
    `
func main() {
	c := &api.StoreConfig{
		KeyContent: []byte(ACCOUNTPRIVATEKEY),  // Loads a .p8 certificate
		KeyID:      "FAKEKEYID",                // Your private key ID from App Store Connect (Ex: 2X9R4HXF34)
		BundleID:   "fake.bundle.id",           // Your app’s bundle ID
		Issuer:     "xxxxx-xx-xx-xx-xxxxxxxxxx",// Your issuer ID from the Keys page in App Store Connect (Ex: "57246542-96fe-1a63-e053-0824d011072a")
		Sandbox:    false,                      // default is Production
	}
	transactionId := "FAKETRANSACTIONID"
	a := api.NewStoreClient(c)
	ctx := context.Background()
	response, err := a.GetTransactionInfo(ctx, transactionId)

	transaction, err := a.ParseSignedTransaction(response.SignedTransactionInfo)
	if err != nil {
	    // error handling
	}

	if transaction.TransactionID == transactionId {
		// the transaction is valid
	}
}
  • GetTransactionHistory
import(
	"github.com/awa/go-iap/appstore/api"
)

//  For generate key file and download it, please refer to https://developer.apple.com/documentation/appstoreserverapi/creating_api_keys_to_use_with_the_app_store_server_api
const ACCOUNTPRIVATEKEY = `
    -----BEGIN PRIVATE KEY-----
    FAKEACCOUNTKEYBASE64FORMAT
    -----END PRIVATE KEY-----
    `
func main() {
	c := &api.StoreConfig{
		KeyContent: []byte(ACCOUNTPRIVATEKEY),  // Loads a .p8 certificate
		KeyID:      "FAKEKEYID",                // Your private key ID from App Store Connect (Ex: 2X9R4HXF34)
		BundleID:   "fake.bundle.id",           // Your app’s bundle ID
		Issuer:     "xxxxx-xx-xx-xx-xxxxxxxxxx",// Your issuer ID from App Store Connect (Users and Access > Integrations > In-App Purchase)(Ex: "57246542-96fe-1a63-e053-0824d011072a")
		Sandbox:    false,                      // default is Production
	}
	originalTransactionId := "FAKETRANSACTIONID"
	a := api.NewStoreClient(c)
	query := &url.Values{}
	query.Set("productType", "AUTO_RENEWABLE")
	query.Set("productType", "NON_CONSUMABLE")
	ctx := context.Background()
	responses, err := a.GetTransactionHistory(ctx, originalTransactionId, query)

	for _, response := range responses {
		transactions, err := a.ParseSignedTransactions(response.SignedTransactions)
	}
}

Parse Notification from App Store

import (
	"github.com/awa/go-iap/appstore"
	"github.com/golang-jwt/jwt/v5"
)

func main() {
	tokenStr := "SignedRenewalInfo Encode String" // or SignedTransactionInfo string
	token := jwt.Token{}
	client := appstore.New()
	err := client.ParseNotificationV2(tokenStr, &token)

	claims, ok := token.Claims.(jwt.MapClaims)
	for key, val := range claims {
		fmt.Printf("Key: %v, value: %v\n", key, val) // key value of SignedRenewalInfo
	}
}

ToDo

  • Validator for In App Purchase Receipt (AppStore)
  • Validator for Subscription token (GooglePlay)
  • Validator for Purchase Product token (GooglePlay)
  • More Tests

Support

In App Purchase

This validator supports the receipt type for iOS7 or above.

In App Billing

This validator uses Version 3 API.

In App Purchase (Amazon)

This validator uses RVS for IAP v2.0.

In App Purchase (HMS)

This validator uses Version 2 API.

In App Store Server API

This validator uses Version 1.0+

In App Purchase (Microsoft Store)

This validator uses Version 1.0

License

go-iap is licensed under the MIT.

评论

暂无评论