Android-queryPurchaseHistoryAsync购买列表在其他设备上为空

时间:2018-06-20 06:08:21

标签: android in-app-purchase in-app-billing

我正在尝试对我的应用实施新的Google Play结算,并尝试使用queryPurchaseHistoryAsync()方法来检索我已经购买的应用内商品,并且Purchase列表始终为空0个元素。

代码在我购买了该商品的设备上运行正常,但是在其他具有相同Google帐户的设备上,此代码什么也没返回。

Documentation中的queryPurchaseHistoryAsync()也应与Google同步以获取购买历史记录,但由于某种原因,它似乎不同步。

我的代码是:

BillingClient billingClient = BillingClient.newBuilder(getApplicationContext()).setListener(new PurchasesUpdatedListener() {
    @Override
    public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> purchases) {
        if(responseCode == BillingClient.BillingResponse.OK) {
            //Do something
        }
    }
}).build();
billingClient.startConnection(new BillingClientStateListener() {
    @Override
    public void onBillingSetupFinished(int responseCode) {
        if(responseCode == BillingClient.BillingResponse.OK) {
            //Response is OK and working fine
        } 
    }

    @Override
    public void onBillingServiceDisconnected() {
        //Do something
    }
});

billingClient.queryPurchaseHistoryAsync(BillingClient.SkuType.INAPP, new PurchaseHistoryResponseListener() {
    @Override
    public void onPurchaseHistoryResponse(int responseCode, List<Purchase> purchasesList) {
        if(responseCode == BillingClient.BillingResponse.OK) {
            //Always returning 0 size() of purchasesList
            Toast.makeText(getApplicationContext(), "There are " + purchasesList.size() + " items you've purchased.", Toast.LENGTH_LONG).show();
        }
    }
});

我到底在哪里弄错了这段代码?

非常感谢您。

2 个答案:

答案 0 :(得分:6)

onBillingSetupFinished()之后调用 queryPurchaseHistoryAsync()吗?

似乎您在源代码上调用onBillingSetupFinished()之前先调用queryPurchaseHistoryAsync()。

您可以在this doc

中检查以下代码
private BillingClient mBillingClient;
...
mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build();
mBillingClient.startConnection(new BillingClientStateListener() {
    @Override
    public void onBillingSetupFinished(@BillingResponse int billingResponseCode) {
        if (billingResponseCode == BillingResponse.OK) {
            // The billing client is ready. You can query purchases here.

        }
    }
    @Override
    public void onBillingServiceDisconnected() { }
});

答案 1 :(得分:0)

要消耗所有未消耗的物品,可以在 onBillingSetupFinished

中运行此代码段
val purchases = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
for (purchase in purchases.purchasesList ?: emptyList()){
    val consumeParams =
        ConsumeParams.newBuilder()
            .setPurchaseToken(purchase.purchaseToken)
            .build()
    billingClient.consumeAsync(consumeParams){ billingResultAfterConsumed , string ->
        //Talk to your server / local database to deliver the consumable to the user
    }
}