当我的 Android 应用程序启动时,我需要查询待处理的购买,以便我们的服务器可以处理它们。我目前正在使用 BillingClient.queryPurchaseHistoryAsync() 来执行此操作,并且工作正常。
但是,queryPurchaseHistoryAsync 已被弃用,Google 建议使用 BillingClient.queryPurchasesAsync() 代替。不幸的是,该调用不会返回处于 PENDING 状态的购买,大概是因为它仅使用本地缓存,并且 PENDING 状态仅由 Play 商店服务器知道。
所以我的问题是如何检索所有待处理的购买,而不依赖于已弃用的调用?
根据google文档([Google Doc][1])
val billingClient = BillingClient.newBuilder(context)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases() // Add this line
.build()
在应用程序启动时查询待处理的购买
使用
BillingClient.queryPurchasesAsync()
billingClient.queryPurchasesAsync(BillingClient.SkuType.INAPP) { billingResult, purchases ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
for (purchase in purchases) {
if (purchase.purchaseState == Purchase.PurchaseState.PENDING) {
// Handle pending purchase
handlePendingPurchase(purchase)
}
}
}
}
在
PurchasesUpdatedListener
处理待定购买
每当购买更新时,您的
PurchasesUpdatedListener
都会通知您,包括状态更改(例如“待处理”到“已购买”)。
val purchasesUpdatedListener = PurchasesUpdatedListener { billingResult, purchases ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
for (purchase in purchases) {
when (purchase.purchaseState) {
Purchase.PurchaseState.PENDING -> {
// Handle pending purchase
handlePendingPurchase(purchase)
}
Purchase.PurchaseState.PURCHASED -> {
// Handle completed purchase
if (!purchase.isAcknowledged) {
acknowledgePurchase(purchase)
}
}
Purchase.PurchaseState.UNSPECIFIED_STATE -> {
// Handle error or ignored state
}
}
}
} else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
// Handle user cancellation
} else {
// Handle other errors
}
}