BillingClient – queryProductDetailsAsync returns error statuses (2, 6, 12) many times

I’m using billing client in my game in order to let people purchase in app item.

According to my logs, many users aren’t able to purchase the item, as purchase flow doesn’t start.

Logs show that most of the users that launch the purchase flow, getting “stuck” at queryProductDetailsAsync method, which results in errors:

int SERVICE_UNAVAILABLE = 2;
int ERROR = 6;
int NETWORK_ERROR = 12;

The thing is that I’m using queryProductDetailsAsync after a success calling to startConnection – I don’t understand how come it can be a network/connection error.

According to my tests, It always succeeds.
I also did a test on my friends phone and it succeeds either.
Furthermore, I do see some success purchases of some users.
So I’m guessing it is not a configuration problem.

All of the failures are from logs coming from users devices

Here’s the code my BillingHelper class:

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import com.android.billingclient.api.*
import com.android.billingclient.api.BillingFlowParams.ProductDetailsParams
import java.lang.ref.WeakReference

class BillingHelper
{
    // region Enum

    enum class PurchaseStatus
    {
        PURCHASED,
        PENDING
    }

    // endregion

    // region Companion

    companion object
    {
        private const val TAG = "BillingHelper"
    }

    // endregion

    // region Listener

    interface BillingHelperListener
    {
        fun purchaseStatusUpdated(itemId: String, status: PurchaseStatus)
    }

    // endregion

    // region Properties

    private var billingClient: BillingClient? = null
    private var context: WeakReference<Context>? = null
    private var listener: BillingHelperListener? = null
    private val handler = Handler(Looper.getMainLooper())

    // endregion

    // region Init

    fun init(context: Context)
    {
        this.context = WeakReference(context)
    }

    fun setListener(listener: BillingHelperListener)
    {
        this.listener = listener
    }

    // endregion

    // region Purchase flow

    fun launchPurchase(activity: Activity, itemId: String, block: (purchaseStarted: Boolean) -> Unit)
    {
        KLog.i(TAG, "launchPurchase - $itemId")

        connectToBillingClient { connected ->

            KLog.i(TAG, "launchPurchase - $itemId. connected? - $connected")

            if (connected)
            {
                prepareSkuForPurchase(activity, itemId, block)
            } else
            {
                handler.post {

                    KLog.i(TAG, "launchPurchase - $itemId. invoking false")
                    block.invoke(false)
                }
            }
        }
    }

    private fun connectToBillingClient(block: (connected: Boolean) -> Unit)
    {
        KLog.i(TAG, "connectToBillingClient")

        getBillingClient()?.let {

            if (it.isReady)
            {
                KLog.i(TAG, "connectToBillingClient - already connected")
                block.invoke(true)
                return@let
            }

            it.startConnection(object : BillingClientStateListener
            {
                override fun onBillingSetupFinished(billingResult: BillingResult)
                {
                    KLog.i(TAG, "connectToBillingClient::onBillingSetupFinished")

                    if (billingResult.responseCode == BillingClient.BillingResponseCode.OK)
                    {
                        KLog.i(TAG, "connectToBillingClient::onBillingSetupFinished - connected")
                        block.invoke(true)
                        return
                    }

                    KLog.i(TAG, "connectToBillingClient::onBillingSetupFinished - invoking false")
                    block.invoke(false)
                }

                override fun onBillingServiceDisconnected()
                {
                    KLog.i(TAG, "connectToBillingClient::onBillingServiceDisconnected - invoking false")
                    block.invoke(false)
                }
            })
        }
    }

    private fun prepareSkuForPurchase(activity: Activity, itemID: String, block: (purchaseStarted: Boolean) -> Unit)
    {
        KLog.i(TAG, "prepareSkuForPurchase - $itemID")

        val skuList = ArrayList<String>()
        skuList.add(itemID)

        val productList =
            listOf(
                QueryProductDetailsParams.Product.newBuilder()
                    .setProductId(itemID)
                    .setProductType(BillingClient.ProductType.INAPP)
                    .build()
            )

        val params = QueryProductDetailsParams.newBuilder()
        params.setProductList(productList)

        getBillingClient()?.queryProductDetailsAsync(params.build()) { billingResult, skuDetailsList ->

            KLog.i(TAG, "prepareSkuForPurchase::queryProductDetailsAsync - billing result - $billingResult")

            /**
             * PROBLEM IS HERE - ACCORDING TO THE LOG - IT SAYS:
             *   1 - billing result - Response Code: ERROR, Debug Message: An internal error occurred.
             *   2 - billing result - Response Code: NETWORK_ERROR, Debug Message: An internal error occurred.
             *   3 - billing result - Response Code: SERVICE_UNAVAILABLE, Debug Message: Timeout communicating with service.
             */

            var purchaseStarted = false

            if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && skuDetailsList.isNotEmpty())
            {
                launchSkuPurchase(activity, skuDetailsList[0])
                purchaseStarted = true
            }

            handler.post {

                KLog.i(TAG, "prepareSkuForPurchase::queryProductDetailsAsync - invoking purchase started? - $purchaseStarted")
                block.invoke(purchaseStarted)
            }
        }
    }

    private fun launchSkuPurchase(activity: Activity, productDetails: ProductDetails)
    {
        KLog.i(TAG, "launchSkuPurchase - $productDetails")
        val params = ProductDetailsParams.newBuilder()
        params.setProductDetails(productDetails)
        val billingFlowParams = BillingFlowParams.newBuilder().setProductDetailsParamsList(listOf(params.build())).build()
        getBillingClient()?.launchBillingFlow(activity, billingFlowParams)
    }

    private fun handleSuccessPurchase(purchase: Purchase)
    {
        KLog.i(TAG, "handleSuccessPurchase - $purchase")
        KLog.i(TAG, "handleSuccessPurchase. state = - ${purchase.purchaseState}")

        if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED)
        {
            if (!purchase.isAcknowledged)
            {
                acknowledgePurchase(purchase)
            } else
            {
                handler.post {

                    listener?.purchaseStatusUpdated(purchase.products.firstOrNull() ?: "", PurchaseStatus.PURCHASED)
                }
            }
        } else if (purchase.purchaseState == Purchase.PurchaseState.PENDING)
        {
            handler.post {

                listener?.purchaseStatusUpdated(purchase.products.firstOrNull() ?: "", PurchaseStatus.PENDING)
            }
        }
    }

    private fun acknowledgePurchase(purchase: Purchase)
    {
        KLog.i(TAG, "acknowledgePurchase - $purchase")

        val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder().setPurchaseToken(purchase.purchaseToken).build()

        getBillingClient()?.acknowledgePurchase(acknowledgePurchaseParams) { result ->

            KLog.i(TAG, ":acknowledgePurchase::status - ${result.responseCode}")

            if (result.responseCode == BillingClient.BillingResponseCode.OK)
            {
                handler.post {

                    listener?.purchaseStatusUpdated(purchase.products.firstOrNull() ?: "", PurchaseStatus.PURCHASED)
                }
            }
        }
    }

    private val purchaseUpdateListener = PurchasesUpdatedListener { billingResult, purchases ->

        KLog.i(TAG, "purchaseUpdateListener::onPurchasesUpdated : $billingResult")

        if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && !purchases.isNullOrEmpty())
        {
            val purchase = purchases.first()
            handleSuccessPurchase(purchase)
        }
    }

    // endregion

    // region Billing client

    private fun getBillingClient(): BillingClient?
    {
        val context = this.context?.get() ?: return let {

            KLog.i(TAG, "getBillingClient - context is null")
            null
        }

        var billingClient = this.billingClient

        if (billingClient == null)
        {
            KLog.i(TAG, "getBillingClient - creating new billing client")
            billingClient = BillingClient.newBuilder(context)
                .setListener(purchaseUpdateListener)
                .enablePendingPurchases()
                .build()

            this.billingClient = billingClient
        } else
        {
            KLog.i(TAG, "getBillingClient - using existing billing client")
        }

        return billingClient
    }

    // endregion
}

As you can see – the problem is in queryProductDetailsAsync method.

What am I missing?

I’m using:
implementation ‘com.android.billingclient:billing:7.0.0’

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật