Search code examples
androidin-app-purchasein-app-billing

Verifying android in app purchase using developer payload


billing lib.: 'com.android.billingclient:billing:2.0.3'

starting a flow after a successful startConnection ,

val skuList = ArrayList<String>()
skuList.add("buy4")
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP)

     //billingClient is declared and initialized earlier 
     billingClient.querySkuDetailsAsync(params.build()) 
          { billingResult, skuDetailsList ->
                val flowParams = BillingFlowParams.newBuilder()
                    .setSkuDetails(skuDetailsList.first())
                    .build()

                val responseCode = billingClient.launchBillingFlow(this, flowParams)
                println(responseCode.responseCode) //prints 0 ... OK
            }

the MainActivity implements PurchasesUpdatedListener

override fun onPurchasesUpdated(billingResult: BillingResult?, purchases: MutableList<Purchase>?) {

    if (billingResult?.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
      for (purchase in purchases) {
          acknowledgePurchase(purchase)
        }
  }
}
private fun acknowledgePurchase(purchase: Purchase) {
   if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED) {
        // Grant entitlement to the user.
        // Acknowledge the purchase
        val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
                .setPurchaseToken(purchase.purchaseToken)
                .setDeveloperPayload("PayloadString")
                .build()


        billingClient.acknowledgePurchase(
          acknowledgePurchaseParams,
          object : AcknowledgePurchaseResponseListener {
            override fun onAcknowledgePurchaseResponse(billingResult: BillingResult?) {
               println("payload =${purchase.developerPayload}")  // prints "payload="
                    }
                })
    }
}

the developer payload is empty, despite being set at the AcknowledgePurchaseParams , I also saved the purchase after acknowledging it, and tried calling purchase.developerPayload after a while, and still it's blank , what are the best practices for using developer payload to verify in app purchases ?

N.B I'm using an internal testing track on play console


Solution

  • In onAcknowledgePurchaseResponse you will need to refresh your purchase object from the cache. The cache is updated by the time onAcknowledgePurchaseResponse is called so you do this by calling https://developer.android.com/reference/com/android/billingclient/api/BillingClient.html#querypurchases. We will consider adding the update purchase to the listener for a future library release to make this more convenient.