Usage
Billing Services allows to monetize your app on iOS and Android platforms
Once after you setup and add billing products, you can purchase a product by referring them in code.
Before using any of the billing services features, first make sure if it's available on the running platform with IsAvailable method. This returns true if you are allowed to make purchases on the current platform.
1
BillingServices.IsAvailable()
Copied!

Events

Once you see that billing services are available, you should register for the billing services events.
1
private void OnEnable()
2
{
3
// register for events
4
BillingServices.OnInitializeStoreComplete += OnInitializeStoreComplete;
5
BillingServices.OnTransactionStateChange += OnTransactionStateChange;
6
BillingServices.OnRestorePurchasesComplete += OnRestorePurchasesComplete;
7
}
8
9
private void OnDisable()
10
{
11
// unregister from events
12
BillingServices.OnInitializeStoreComplete -= OnInitializeStoreComplete;
13
BillingServices.OnTransactionStateChange -= OnTransactionStateChange;
14
BillingServices.OnRestorePurchasesComplete -= OnRestorePurchasesComplete;
15
}
Copied!
Event Name
Description
OnInitializeStoreComplete
Event triggered when products are fetched from the store
OnTransactionStateChange
Event triggered when there is a change in state for an ongoing transaction
OnRestorePurchasesComplete
Event triggered once restored products are available
Events are triggered based on an action initiated by the plugin's api calls, asynchronously. For ex: Calling InitializeStore triggers OnInitializeStoreComplete with the product details if it's successful.

Get Billing Product Details

After event registration, you need to call InitializeStore to fetch the complete details of the in-app purchase billing products.
This call fetches the details(you set in iTunes connect and google play) and triggers BillingServices.OnInitializeStoreComplete callback with the details.
Optionally, you can pass your own BillingProducts created at runtime to InitializeStore call. This will be handy if you have an API to fetch platform id's runtime.
1
BillingServices.InitializeStore();
Copied!
1
// Register for the BillingServices.OnInitializeStoreComplete event
2
// ...
3
4
private void OnInitializeStoreComplete(BillingServicesInitializeStoreResult result, Error error)
5
{
6
if (error == null)
7
{
8
// update UI
9
// show console messages
10
var products = result.Products;
11
Debug.Log("Store initialized successfully.");
12
Debug.Log("Total products fetched: " + products.Length);
13
Debug.Log("Below are the available products:");
14
for (int iter = 0; iter < products.Length; iter++)
15
{
16
var product = products[iter];
17
Debug.Log(string.Format("[{0}]: {1}", iter, product));
18
}
19
}
20
else
21
{
22
Debug.Log("Store initialization failed with error. Error: " + error);
23
}
24
25
var invalidIds = result.InvalidProductIds;
26
Debug.Log("Total invalid products: " + invalidIds.Length);
27
if (invalidIds.Length > 0)
28
{
29
Debug.Log("Here are the invalid product ids:");
30
for (int iter = 0; iter < invalidIds.Length; iter++)
31
{
32
Debug.Log(string.Format("[{0}]: {1}", iter, invalidIds[iter]));
33
}
34
}
35
}
Copied!
The platform product id's you set in Essential Kit Settings will be used internally by the plugin to fetch the complete details of the product on current platform.

Making a purchase

Once you have the details about pricing and description of a product, you can check if your device is ready to make payments. CanMakePayments returns true when its fine to make purchases. If purchases are not currently allowed, it returns false.
1
BillingServices.CanMakePayments()
Copied!
Consumable products can be purchased multiple time where as Non-Consumable products can be bought only once. To unlock the content purchased with non-consumable product you can check if its already bought or not with IsProductPurchased
1
//product => "Product you got from OnInitializeStoreComplete event (result.Products)"
2
BillingServices.IsProductPurchased(product);
Copied!
If the product is not purchased or if its a consumable product you can proceed with the purchase by calling BuyProduct. BuyProduct takes the BillingProduct instance you got from OnInitializeStoreComplete event.
1
//product => "Product you got from OnInitializeStoreComplete event (result.Products)"
2
BillingServices.BuyProduct(product);
Copied!
BuyProduct shows native purchase dialogs to proceed with the purchase and fires BillingServices.OnTransactionStateChange event callback during the purchase process.
1
private void OnTransactionStateChange(BillingServicesTransactionStateChangeResult result)
2
{
3
var transactions = result.Transactions;
4
for (int iter = 0; iter < transactions.Length; iter++)
5
{
6
var transaction = transactions[iter];
7
switch (transaction.TransactionState)
8
{
9
case BillingTransactionState.Purchased:
10
Debug.Log(string.Format("Buy product with id:{0} finished successfully.", transaction.Payment.ProductId));
11
break;
12
13
case BillingTransactionState.Failed:
14
Debug.Log(string.Format("Buy product with id:{0} failed with error. Error: {1}", transaction.Payment.ProductId, transaction.Error));
15
break;
16
}
17
}
18
}
Copied!
Once you BillingServices.OnTransactionStateChange event fired, you will get a list of transactions that are currently getting processed. You can check if the transaction state is BillingTransactionState.Purchased or BillingTransactionState.Failed.
If its Purchased state, you can proceed with unlocking the content to the user. If Failed, It could be because the user cancelled the payment or due a failed transaction. You can get more details from Error property of a transaction.

Get previous purchases (Restore Purchases)

There are scenarios where
    The user uninstalls your game and re-installs later
    The user installs the game on multiple devices
As Non-Consumable product purchases need to be maintained across devices and installs, you need a way to fetch the old purchases of the user so that you can unlock the content for the user.
This can be achieved through RestorePurchases call.
1
BillingServices.RestorePurchases();
Copied!
Calling RestorePurchases fetches the old purchase transactions linked to the user account and fires BillingServices.OnRestorePurchasesComplete event with all purchase details.
1
private void OnRestorePurchasesComplete(BillingServicesRestorePurchasesResult result, Error error)
2
{
3
if (error == null)
4
{
5
var transactions = result.Transactions;
6
Debug.Log("Request to restore purchases finished successfully.");
7
Debug.Log("Total restored products: " + transactions.Length);
8
for (int iter = 0; iter < transactions.Length; iter++)
9
{
10
var transaction = transactions[iter];
11
Log(string.Format("[{0}]: {1}", iter, transaction.Payment.ProductId));
12
}
13
}
14
else
15
{
16
Debug.Log("Request to restore purchases failed with error. Error: " + error);
17
}
18
}
Copied!
Once you get the old purchase transactions, you can unlock the content for the user.
On iOS, it's required to have an explicit button to restore purchases as per Apple guidelines.
It's always good to call Restore Purchases once you are done with InitializeStore call as the user will be available with unlocked content if he/she has purchased any earlier.

Manually handling transactions (Auto Finish Transactions disabled)

There are scenarios where you want to validate a purchase receipt on your server and unlock the content to the user. If you have such requirement, you need to disable "Auto Finish Transactions" in Billing Services settings and close the transactions manually.
GetTransactions gives the list of all pending transactions and you need to
    1.
    Process each transaction returned from GetTransactions
    2.
    Pass the transaction receipt details to your backend server
    3.
    Set ReceiptVerificationState of the transaction to BillingReceiptVerificationState.Success or BillingReceiptVerificationState.Failed
    4.
    Call FinishTransactions with the updated transaction verification details
If you have "Auto Finish Transactions" enabled in Essential Kit Settings -> Billing Services, you don't need to call GetTransactions as we handle this automatically.
1
// Fetch all pending transactions
2
var transactions = BillingServices.GetTransactions();
3
// Process each transaction
4
foreach (var each in transactions)
5
{
6
// Verify the receipt with your server - This is an async call usually
7
// Set the ReceiptVerificationState to Success or Failed
8
}
9
10
// Call Finish Transactions to clear the pending transaction queue
11
BillingServices.FinishTransactions(transactions);
Copied!

Platform Specific (Advanced)

Android

Have a look at the below table for the BillingTransaction to Google Play purchase response mapping.
Property Name of BillingTransaction
Mapped Property on Native Platform
Id
INAPP_PURCHASE_DATA.orderId
Receipt
INAPP_PURCHASE_DATA.purchaseToken
Payment.ProductId
INAPP_PURCHASE_DATA.productId
AndroidProperties.PurchaseData
INAPP_PURCHASE_DATA
AndroidProperties.Signature
INAPP_DATA_SIGNATURE
Last modified 9mo ago