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

Is there a way to add extra data when purchasing using Inapp purchases


Here is a scenerio , We have multiple teachers on our app . User can purchase 3 different items from teacher which costs $20, $30, $40 . So I created 3 products in google play console . When user purchases some item how can I know from which teacher he purchased the item from ? I don't see any way to set extra data when purchasing the item . How people generally handles these cases ?

This is the method I use to launch payment screen

 fun buyAnItem(activity:Activity,skuDetails: SkuDetails) {
    val flowParams = BillingFlowParams.newBuilder()
        .setSkuDetails(skuDetails)
        .build()
    val responseCode =
        billingClient.launchBillingFlow(activity, flowParams)
    log(responseCode.toString())
}

I don't see any way to set extra data in SkuDetails or BillingFlowParams.newBuilder()

How ever I saw we can set these 2 parameters we can set for BillingFlowParams.newBuilder() .setObfuscatedAccountId() and .setObfuscatedProfileId() , should I be using these ? It looks like a hack to me .

I want to get back the extra params in Purchase object

 override fun onPurchasesUpdated(
    billingResult: BillingResult?,
    purchases: MutableList<Purchase>?
) {
        for (purchase in purchases) {
           consumePurchase(purchase)
       }
    }
}

Solution

  • Seems like using setObfuscatedProfileId and setObfuscatedAccountId is the right way. Set some unique values for different users . maximum of 64 charecters is allowed per each property .

    val flowParams = BillingFlowParams.newBuilder()
            .setSkuDetails(skuDetails)
            .setObfuscatedProfileId(profileId)  //Some data you want to send
            .setObfuscatedAccountId(id)  //Some data you want to send
            .build()
        val responseCode =
            billingClient?.launchBillingFlow(activity, flowParams)
    

    Retrieving :- you can retrieve the data by using purchase.accountIdentifiers?.obfuscatedAccountId and purchase.accountIdentifiers?.obfuscatedProfileId

    override fun onPurchasesUpdated(
        billingResult: BillingResult?,
        purchases: MutableList<Purchase>?
    ) {
    
        if (billingResult?.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
            for (purchase in purchases) {
                CoroutineScope(Dispatchers.Main).launch {
                    log(purchase.accountIdentifiers?.obfuscatedAccountId)
                    log(purchase.accountIdentifiers?.obfuscatedProfileId)
                    consumePurchase(purchase)
                }
            }
        }
    }
    

    Official documentation :- https://developer.android.com/google/play/billing/developer-payload#attribute