Skip to content

3. Purchasing a Product

Saeed Moradi edited this page Feb 23, 2022 · 6 revisions

To purchase a product, you need to construct a PurchaseRequest class:

val purchaseRequest = PurchaseRequest(
    productId = "coinBoxProduct",
    requestCode = 123,
    payload = "",
    dynamicPriceToken = null
)

productId -> This is the product id that you have defined inside of the developer's panel.
requestCode -> This is just a random integer but, it's a good practice to make this a constant property.
payload -> This can be an empty string or anything else that you wish, but it's a good practice to actually pass in some data to help you to verify the purchase.
dynamicPriceToken -> This is a token that the developer can apply to any user to change the price of the product, for more info about this please read the site documentation

Okay, so now that you have constructed a PurchaseRequest, you can easily call purchaseProduct function in Payment class:
purchaseProduct supports fragments as well.

payment.purchaseProduct(
  registry = activityResultRegistry,
  request = purchaseRequest
) {
  purchaseFlowBegan {
        // Bazaar's billing screen has opened successfully
        ...    
  }
  failedToBeginFlow { throwable ->
        // Failed to open Bazaar's billing screen
        ...    
  }
  purchaseSucceed { purchaseEntity ->
        ...
  }
  purchaseCanceled {
        ...       
  }
  purchaseFailed { throwable ->
        ...        
  }
}

As you can see, inside of the purchaseProduct function, you have access to callbacks which you can use to get notified about the purchase flow.

Reactive way of this

payment.purchaseProduct(
 registry: ActivityResultRegistry,
 request: PurchaseRequest
).subscribe({
        // Purchase Succeed
        ...
    }, { throwable ->
        // Purchase Failed
        ...
    })