I am implementing In-App purchase demo in my android application to learn all the things carefully and deeply.
Now, For that, I have below three product ids that I have added in my google play console accounts:
consumable_product_coins
nonconsumable_product_basic_videos
nonconsumable_product_prime_videos
Now, my xml contains three buttons each for buying above three products, I am launching purchase flow on click of particular button.
In my Java file, I have done as below :
class MainActivity : AppCompatActivity(), CoroutineScope, PurchasesUpdatedListener {
private lateinit var billingClient: BillingClient
private val prod_coin = "consumable_product_coin"
private val prod_basic_videos = "nonconsumable_product_basic_videos"
private val prod_prime_videos = "nonconsumable_product_prime_videos"
private var recent_purchase = ""
private var job: Job = Job()
private lateinit var mBtnBuyCoins: Button
private lateinit var mBtnBuyBasicVideos: Button
private lateinit var mBtnBuyPremiumVideos: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViews()
initializePurchaseUpdateListener()
Toast.makeText(this@MainActivity, "No SKU Details found", Toast.LENGTH_SHORT).show()
}
private fun findViews() {
mTvDescription = findViewById(R.id.tvDescription)
mBtnBuyCoins = findViewById(R.id.btnBuyCoins)
mBtnBuyBasicVideos = findViewById(R.id.btnBuyBasic)
mBtnBuyPremiumVideos = findViewById(R.id.btnBuyPremium)
mBtnBuyCoins.setOnClickListener {
recent_purchase=prod_coin
querySkuDetails(prod_coin)
}
mBtnBuyBasicVideos.setOnClickListener {
recent_purchase=prod_basic_videos
querySkuDetails(prod_basic_videos)
}
mBtnBuyPremiumVideos.setOnClickListener {
recent_purchase=prod_prime_videos
querySkuDetails(prod_prime_videos)
}
}
private fun initializePurchaseUpdateListener() {
val purchasesUpdateListener =
PurchasesUpdatedListener { billingResult, purchases ->
// To be implemented in a later section.
}
initializeBillingClient(purchasesUpdateListener)
}
private fun initializeBillingClient(purchasesUpdateListener: PurchasesUpdatedListener) {
billingClient = BillingClient.newBuilder(this@MainActivity)
.setListener(purchasesUpdateListener)
.enablePendingPurchases()
.build()
establishConnectionForBillingClient()
}
private fun establishConnectionForBillingClient() {
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
}
}
override fun onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
})
}
fun querySkuDetails(sku: String) {
val skuList = ArrayList<String>()
skuList.add(prod_coin)
skuList.add(prod_basic_videos)
skuList.add(prod_prime_videos)
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP)
launch {
withContext(Dispatchers.IO) {
billingClient.querySkuDetailsAsync(params.build()) { billingResult, skuDetailsList ->
// Process the result.
if (skuDetailsList?.size ?: 0 > 0) {
Toast.makeText(
this@MainActivity,
"TOTAL SKUS >> "+skuDetailsList?.size,
Toast.LENGTH_SHORT
).show()
for (i in 0 until (skuDetailsList?.size ?: 0)) {
Log.e("INSIDE QUERY ", "" + skuDetailsList!![i])
if (skuDetailsList!![i].sku.equals(sku)) {
val billingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList!![i])
.build()
val responseCode = billingClient.launchBillingFlow(
this@MainActivity,
billingFlowParams
).responseCode
}
}
} else {
Toast.makeText(
this@MainActivity,
"No SKU Details found",
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
override fun onPurchasesUpdated(
billingResult: BillingResult,
purchases: MutableList<Purchase>?
) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
Log.e("On Purcahse Updated >> ", "> " + purchases!!.size)
mTvDescription.text = "Size : " + purchases.size
for (purchase in purchases) {
handlePurchase(purchase)
}
} else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
Log.e(">>>Purchase CANCELED", " >> P CAN")
} else {
// Handle any other error codes.
Log.e(">>>ERROR > ", " Other Error Occured")
}
}
fun handlePurchase(purchase: Purchase) {
if(recent_purchase.equals(prod_coin))
{
//for consumable products
Toast.makeText(this@MainActivity, "Inside handle purcahse", Toast.LENGTH_SHORT).show()
val consumeParams =
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build()
Toast.makeText(this@MainActivity,"Purchase Token : >>"+"\n"+purchase.purchaseToken.toString(),Toast.LENGTH_LONG).show()
billingClient.consumeAsync(consumeParams, { billingResult, outToken ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
// Handle the success of the consume operation.
Toast.makeText(this@MainActivity,"Acknowledgement Successfull",Toast.LENGTH_LONG).show()
}else{
Toast.makeText(this@MainActivity,"Acknowledgement FAILS",Toast.LENGTH_LONG).show()
}
})
}else{
//for nonconsumable products
if (purchase.purchaseState === Purchase.PurchaseState.PURCHASED) {
if (!purchase.isAcknowledged) {
val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
launch{
val ackPurchaseResult = withContext(Dispatchers.IO) {
billingClient.acknowledgePurchase(acknowledgePurchaseParams.build())
}
}
}else{
Toast.makeText(this@MainActivity,"You have already puchased this product",Toast.LENGTH_LONG).show()
}
}
}
}
}
Now, you can see from the code that product1 (coins) is consumable, so I have implemented consumeAsync
method. For rest, implemented acknowledgePurchase
.
But, the issue is first time I can buy the coin product normally. From the second time Its showing me that : "You already own this item" Same thing is happening for rest of the two products.
What might be the issue ?
Note : After 5 mins I can buy it again! I am not implementing Subscriptions.
Got the Solutions:
The Issue was there in passing purchaseUpdateListener to billingClient.
Removed Below code :
private fun initializePurchaseUpdateListener() {
val purchasesUpdateListener =
PurchasesUpdatedListener { billingResult, purchases ->
// To be implemented in a later section.
}
initializeBillingClient(purchasesUpdateListener)
}
private fun initializeBillingClient(purchasesUpdateListener: PurchasesUpdatedListener) {
billingClient = BillingClient.newBuilder(this@MainActivity)
.setListener(purchasesUpdateListener)
.enablePendingPurchases()
.build()
establishConnectionForBillingClient()
}
Since I am implementing PurchasesUpdatedListener
I have to change below lines :
billingClient = BillingClient.newBuilder(this@MainActivity)
.setListener(purchasesUpdateListener)
.enablePendingPurchases()
.build()
To
billingClient = BillingClient.newBuilder(this@MainActivity)
.setListener(this)
.enablePendingPurchases()
.build()
In short the my onPurchaseUpdate()
method was not called.