GooglePay
GooglePay 是一個基於 Google Play Billing Library 封裝的 Android 支付庫,旨在簡化 Google 支付的接入流程,提供統一的接口管理一次性購買和訂閲服務。
GitHub
接入指南
本文檔提供了將 Google Pay 庫集成到您的 Android 應用程序中的詳細指南。
1. 添加依賴
在您的項目 build.gradle 文件中添加 JitPack 倉庫和依賴項。
根目錄 build.gradle:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
App 模塊 build.gradle:
dependencies {
implementation 'com.github.darryrzhong:GooglePay:8.1.0-1.1' // 請檢查最新版本
}
2. 初始化
在您的 Application 類中初始化 GooglePayClient。此設置配置了結算客户端、調試模式和訂閲設置。
示例 (GpApp.kt):
class GpApp : Application() {
override fun onCreate() {
super.onCreate()
GooglePayClient.getInstance()
.setDebug(true) // 啓用日誌
.setSubscriptionMode(SubscriptionMode.SingleMode) // 或 MultiModal (多訂閲模式)
.setSubscription(true) // 啓用訂閲支持
.setInterval(15) // 自動刷新間隔 (如果適用)
.registerActivitys(arrayListOf(MainActivity::class.java)) // 註冊主要 Activity
.initBillingClient(this, GooglePayServiceImpl.instance) // 使用上下文和服務實現進行初始化
}
}
3. 實現 GooglePayService
您必須實現 GooglePayService 接口以提供商品 ID 並處理購買驗證邏輯。
示例 (GooglePayServiceImpl.kt):
class GooglePayServiceImpl private constructor() : GooglePayService {
companion object {
val instance by lazy { GooglePayServiceImpl() }
}
// 返回在 Google Play Console 中配置的一次性消耗型商品 ID 列表
override suspend fun getOneTimeConsumableProducts(): List<String> =
suspendCancellableCoroutine { continuation ->
val productList = listOf(
"com.example.product.1",
"com.example.product.2"
)
continuation.resume(productList)
}
// 返回一次性非消耗型商品 ID 列表 (如果有)
override suspend fun getOneTimeNonConsumableProducts(): List<String> {
return arrayListOf()
}
// 返回訂閲商品 ID 列表
override suspend fun getSubscribeProducts(): List<String> =
suspendCancellableCoroutine { continuation ->
val subsList = listOf(
"com.example.vip.1month",
"com.example.vip.1year"
)
continuation.resume(subsList)
}
// 處理購買流程 (驗證和消耗/確認)
override suspend fun handlePurchasesProcess(
isPay: Boolean,
productType: BillingProductType,
purchases: Purchase
) {
// 1. 與您的後端服務器驗證購買交易
// ... 驗證邏輯 ...
// 2. 驗證通過後,消耗購買 (如果是消耗品) 或 確認購買 (如果是訂閲)
when (productType) {
BillingProductType.INAPP -> {
// 對於一次性消耗型商品
GooglePayClient.getInstance().getPayService<OneTimeService>()
.consumePurchases(purchases, isPay)
}
BillingProductType.SUBS -> {
// 對於訂閲商品
GooglePayClient.getInstance().getPayService<SubscriptionService>()
.consumePurchases(purchases, isPay)
}
}
}
override fun printLog(tag: String, msg: String) {
Log.d(tag, msg)
}
}
4. 一次性購買流程
發起一次性購買 (例如:遊戲貨幣、道具):
-
構建
BillingParams:accountId: 業務方標識用户的唯一 ID。productId: Google Play 商品 ID。chargeNo: 業務方生成的訂單號 (用於追蹤)。
-
啓動支付流程:
- 獲取
OneTimeService。 - 調用
launchBillingFlow。
- 獲取
示例:
val billingParams = BillingParams.Builder()
.setAccountId("user_123")
.setProductId("com.example.product.1")
.setChargeNo("order_456")
.build()
val result = GooglePayClient.getInstance().getPayService<OneTimeService>()
.launchBillingFlow(requireActivity(), billingParams)
if (result.code != AppBillingResponseCode.OK) {
// 處理錯誤 (例如:顯示 Toast 提示)
result.message.showTips(requireContext())
}
5. 訂閲流程
發起訂閲:
-
構建
BillingSubsParams:accountId: 用户唯一 ID。productId: 訂閲商品 ID。basePlanId: 基礎方案 ID (Billing Library 5+ 需要)。offerId: 優惠 ID (如果適用)。chargeNo: 業務訂單號 (可選,建議用於追蹤)。
-
啓動支付流程:
- 獲取
SubscriptionService。 - 調用
launchBillingFlow。
- 獲取
示例:
val billingSubsParams = BillingSubsParams.Builder()
.setAccountId("user_123")
.setProductId("com.example.vip.1month")
.setBasePlanId("base-plan-id") // 新版結算配置需要
.setOfferId("offer-id") // 可選
.setChargeNo("order_789") // 可選,建議用於追蹤
.build()
val result = GooglePayClient.getInstance().getPayService<SubscriptionService>()
.launchBillingFlow(requireActivity(), billingSubsParams)
if (result.code != AppBillingResponseCode.OK) {
// 處理錯誤
result.message.showTips(requireContext())
}
6. 事件處理
使用 observePayEvent 擴展函數監聽支付事件 (成功、失敗等)。這可以在 Activity、Fragment 或 Dialog 中完成。
示例:
observePayEvent { payEvent ->
when (payEvent) {
is BillingPayEvent.PaySuccessful -> {
// 支付成功
// 注意:消耗/確認操作在 GooglePayService.handlePurchasesProcess 中處理
"支付成功".showTips(requireContext())
}
is BillingPayEvent.PayFailed -> {
// 支付失敗
payEvent.message.showTips(requireContext())
}
is BillingPayEvent.PayConsumeSuccessful -> {
// 消耗成功 (內部事件)
}
is BillingPayEvent.PayConsumeFailed -> {
// 消耗失敗
}
}
}
7. 查詢商品
您可以查詢商品詳情 (價格、標題等) 以在 UI 中顯示。
一次性商品:
val products = GooglePayClient.getInstance().getPayService<OneTimeService>()
.queryProductDetails(listOf("com.example.product.1"))
// 使用結果更新 UI
訂閲商品:
val subsDetails = GooglePayClient.getInstance().getPayService<SubscriptionService>()
.querySubsOfferDetails(subsOfferParams)
8. 恢復購買
要恢復購買 (例如:用户重裝應用或更換設備時),調用 queryPurchases()。這將觸發 handlePurchasesProcess 處理任何未消耗/未確認的活躍購買,或者僅僅刷新本地緩存。
GooglePayClient.getInstance().queryPurchases()
9. 檢查 Google Play 可用性
當 Google Play 服務不可用時,庫內部會自動使用空實現進行處理,因此您的應用不會崩潰。不過,您仍然可以使用 isGoogleAvailable 來根據需要隱藏支付 UI 元素。
if (GooglePayClient.getInstance().isGoogleAvailable(context)) {
// 顯示支付 UI
} else {
// 隱藏支付 UI 或顯示其他內容
}
10. 生命週期管理與自動刷新
庫會自動處理 BillingClient 的生命週期管理。
自動刷新:
如果您通過 registerActivitys() 註冊了重要 Activity(如首頁或商城頁),庫將在以下情況自動刷新庫存並處理消耗(基於 setInterval 配置的間隔):
- 當這些 Activity 每次可見時。
- 每次應用回到前台時。
GooglePayClient.getInstance().endConnection() // 可選:應用終止時手動斷開連接
11. 重要注意事項
- 生命週期: 庫會處理
BillingClient的生命週期管理。 - 驗證: 務必在授予權益之前在您的後端服務器上驗證購買,以防止欺詐。
- 消耗/確認: Google 要求在 3 天內確認 (訂閲) 或消耗 (消耗品) 購買,否則將會退款。您實現的
GooglePayService中的handlePurchasesProcess是在驗證後觸發此操作的地方。
更多指南
- Google Play 結算系統入門指南
- GooglePay 消耗商品購買流程
- GooglePay 訂閲商品購買流程
- GooglePay: API 文檔