Android Google Pay 集成

Android Google Pay 集成

官方文檔:https://developer.android.com/google/play/billing/billing_library_overview

Google Play支持商品內購和訂閱

這裏主要記錄了內購的集成過程,語言:Kotlin

集成

1. 添加依賴

dependencies {
    ...
    implementation 'com.android.billingclient:billing:1.2'
}

2. 添加權限

需要使用Google Play 內購功能,必須添加權限,否則無法支付。

<!-- Google Play 內購權限 -->
<uses-permission android:name="com.android.vending.BILLING" />

網絡及其他必要權限自行添加就好了。

3. 初始化

private var billingClient: BillingClient = BillingClient.newBuilder(context).setListener { responseCode: Int, purchases: MutableList<Purchase>? ->
        if (responseCode == BillingClient.BillingResponse.OK && purchases != null) {
            // TODO 支付完成
        } else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
            // Handle an error caused by a user cancelling the purchase flow.
            // TODO 用戶取消了支付
        } else if (responseCode == BillingClient.BillingResponse.ITEM_ALREADY_OWNED) {
            // Handle an error caused by a user cancelling the purchase flow.
            // TODO 商品已經購買過(重複購買了此商品,如果需要支持重複購買,需要將商品購買成功後消費掉)
        } else {
            // Handle any other error codes.
        }
    }.build()

4. 連接 Google Play Service

在使用支付功能之前,首先要連接Google Play Service,確保當前狀態支付是可用的,此操作對於國內用戶來說是需要梯子的,但是對於國外的用戶,就不用操心了,畢竟我們開發Google Play主要還是給國外用戶使用。

billingClient.startConnection(object : BillingClientStateListener {
        override fun onBillingSetupFinished(@BillingClient.BillingResponse billingResponseCode: Int) {
            // 連接成功
            if (billingResponseCode == BillingClient.BillingResponse.OK) {
                // The billing client is ready. You can query purchases here.

                // 5. Query for in-app product details.
                // 5. 查詢商品詳情
                
                // 6. 支付商品
                
            } else {
                // TODO 連接失敗
            }
        }

		 // 連接斷開
        override fun onBillingServiceDisconnected() {
            // Try to restart the connection on the next request to
            // Google Play by calling the startConnection() method.
        }
    })

5. 獲取商品信息

商品信息需要將帶有內購權限的apk上傳到GooglePlayConsole後,添加內購商品,設置商品ID,待商品生效後,移動端通過商品ID來查詢商品的詳細信息。

val params = SkuDetailsParams.newBuilder().apply {
    setSkusList(ArrayList<String>().apply {
        add("要查詢的商品ID") // 可以單個查詢也可以多個查詢
    }).setType(BillingClient.SkuType.INAPP)
}

billingClient.querySkuDetailsAsync(params.build()) { responseCode, skuDetailsList ->
    Logger.d("responseCode = $responseCode   skuDetailsList = ${skuDetailsList?.size}")
	// responseCode 爲響應碼
	// skuDetailsList 爲查詢的商品信息列表
}

6. 支付商品

skuDetails爲查詢到的商品信息

// 喚起GooglePay支付
val flowParams = BillingFlowParams.newBuilder()
        .setSkuDetails(skuDetails)
        .build()
billingClient.launchBillingFlow(activity, flowParams)

支付成功後,會在初始化的監聽接口回調支付結果,包含必要的支付結果信息。

7. 消費商品(非必須)

Google的商品默認是單次消費的,即只能購買一次,如果需求是可以多次購買的,比如充值等需求,那麼就需要在支付成功後將購買的商品消費掉。

billingClient.consumeAsync(purchaseToken){ responseCode: Int, purchaseToken: String ->
	
}
  • purchaseToken : 支付成功後返回的支付令牌

如果支付成功後沒有立即消費,需要後續手動消費掉,則先要查詢未消費的商品,有同步方法和異步方法:

// 查詢歷史購買 同步
val purchasesResult: Purchase.PurchasesResult = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
if (purchasesResult.responseCode == BillingClient.BillingResponse.OK) {
    purchasesResult.purchasesList?.forEach { purchase ->
        purchase.purchaseToken?.apply {
            // TODO 消費掉商品
        }
    }
}
// 查詢歷史購買 異步
billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP) { responseCode, purchasesList ->
    if (responseCode == BillingClient.BillingResponse.OK) {
        purchasesList?.forEach { purchase ->
            purchase.purchaseToken?.apply {
                // TODO 消費掉商品
            }
        }
    }
}

8. 校驗支付

校驗支付可以移動端校驗也可以後臺校驗,如果我們的商品有後臺管理,那麼無疑當然選擇通過後臺來校驗支付了,畢竟移動端比較容易被破解。

後臺校驗支付也有兩種方式,一種是通過配置GooglePlayAPI,通過OAuth去獲取訂單信息進行驗證,相對比較麻煩。

還有一種簡單的做法就是通過許可密鑰進行驗證,相對簡單一點,各有利弊,據說大部分都使用這種方式,我們圖省事,也是通過這種方式校驗。

許可密鑰可以在 GooglePlayConsole->選擇應用->開發工具->服務和API中找到。

創建商品

GooglePlayConsole->選擇應用->商店發佈->應用內商品

商品在上傳apk後可以添加創建,一般情況下,App上顯示的商品列表是由後臺維護的,列表包含配置好的商品ID,移動端的商品ID從後開接口獲取,這樣添加或移除商品後,只需要和後臺同步即可。

添加測試人員

GooglePlayConsole->設置->管理測試人員 管理測試人員。添加測試人員後,需要將邀請鏈接分別發送給測試人員,點擊接受邀請後纔可以生效。

Google Play 不區分正式環境還是沙盒環境,一切以賬號爲準,如果登錄的是測試人員的賬號,支付時會提示測試訂單,不會扣款。

混淆

-keep class com.android.vending.billing.**

此版本的應用未配置爲通過Google Play結算。

當前運行的版本和 Google Play 當前生效的版本不匹配導致的,官方介紹的測試方式,是開發完成後將apk上傳到Alpha版本(其他版本也可以),等到生效後,測試人員賬號可以再Google Play看到更新,更新後就可以正常測試了。這樣做的目的就是爲了等最新的版本號生效,如果版本號還沒有生效,就安裝在手機上運行,就會出現上面錯誤。

無法購買該商品

可能是商品已經失效了,我們遇到這個問題是出現在app因爲某些原因被停用

不支持該地區

中國地區應該是不支持Google Play這種支付方式的,測試的話,需要在Google Play 中,修改一個賬號的地區。

應用內敏感圖片資源

上傳Google Play的應用,應用內部不要包含敏感資源(例如大尺度的圖片等),應用上線後,google 還會對apk內部資源審查,不管資源有沒有用到,只要包含了敏感資源,都會導致被下架。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章