2.2.1
RuStore allows you to integrate payments into your mobile app.
Implementation example
Please have a thorough look at the application example to learn how to integrate payments correctly.
Prerequisites
- The current version of RuStore is installed on the user's device.
- The user is authorized in RuStore.
- The user and the app should not be blocked in RuStore.
- In-app purchases should be enabled for the app in RuStore Console.
The service has some restrictions to work outside of Russia.
Getting started
To get started, you need to download RuStore Billing SDK and import it into your project (Assets > Import Package > Custom Package). Dependencies are included automatically using External Dependency Manager (included in the SDK).
If you are using macOS, change the settings of the archive utility. In the Archive Utility settings, uncheck Keep expanding if possible. Otherwise the project archive will not be downloaded correctly.
Apart from that, you can clone the code using Git.
To correctly handle SDK dependencies, you must set the following settings:
- Edit > Project Settings > Player Settings > Publishing Settings, enable Custom Main Gradle Template and Custom Gradle Properties Template.
- Assets > External Dependencies Manager > Android Resolver > Settings, enable Use Jetifier, Patch
mainTemplate.gradle
, PatchgradleTemplate.properties
.
After setting up, be sure complete Assets > External Dependencies Manager > Android Resolver > Force Resolve.
Minimum API level must be set to at least 24. Application minification (ProGuard/R8) is not currently supported; it must be disabled in the project settings (File > Build Settings > Player Settings > Publishing Settings > Minify).
Deeplink processing
To redirect a user to your app after payment via third-party apps (the Faster Payments System (SBP), SberPay and others), you need to properly implement deep linking in your app. Specify the intent-filter
in AndroidManifest.xml
with scheme
of your project (see below).
<activity
android:name="ru.rustore.unitysdk.RuStoreUnityActivity" android:theme ="@style/UnityThemeSelector" android:exported ="true">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="yourappscheme"/>
</intent-filter></activity>
where yourappscheme
— your deeplink scheme, it can be changed to another one.
Next, extend the UnityPlayerActivity
class and add incoming intent
processing to onNewIntent
.
package ru.rustore.unitysdk;import android.os.Bundle;import android.content.Intent;import ru.rustore.unitysdk.billingclient.RuStoreUnityBillingClient;import com.unity3d.player.UnityPlayerActivity;public class RuStoreUnityActivity extends UnityPlayerActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
if (savedInstanceState == null ) {
RuStoreUnityBillingClient.onNewIntent(getIntent());
}
}
@Override protected void onNewIntent(Intent intent) {
super .onNewIntent(intent);
RuStoreUnityBillingClient.onNewIntent(intent);
}}
The Java file with UnityPlayerActivity
extension code must be placed in the Assets
folder of the project. If you already have your own UnityPlayerActivity
extension, you need to transfer the code of the onCreate
and onNewIntent
functions to it.
Initialization
Initialize the library before calling its methods.
In the editor menu select Window > RuStoreSDK > Settings > Billing Client..
RuStoreBillingClient.Instance.Init();
Once you’re required other settings, you can pass them directly from the code:
var config = new RuStoreBillingClientConfig() {
consoleApplicationId = "11111" ,
deeplinkPrefix = "yourappscheme" ,
allowNativeErrorHandling = true,
enableLogs = true
};
RuStoreBillingClient.Instance.Init(config);
-
consoleApplicationId
— application code from RuStore Console (example:https://console.rustore.ru/apps/123456
). -
deeplinkPrefix
— an url used for deeplink. Make sure your use a unique name, for exampl: yourappscheme). -
allowNativeErrorHandling
— allow error handling (see in Error handling). -
enableLogs
— enable event logging.
deeplinkPrefix
must match the one specified in AndroidManifest.xml
(see Deeplinks handling).If you need to check that the library is initialized, use RuStoreBillingClient.Instance.isInitialized
which returns true
, if the library is initialized and false
if the Init
function has not been called yet.
var isInitialized = RuStoreBillingClient.Instance.IsIninialized;
How payments work
Checking purchases availability
To check whether your app supports payment functions, call theCheckPurchasesAvailability
method.
If all conditions are met, the method returns FeatureAvailabilityResult.isAvailable == true
.
Otherwise, it returns FeatureAvailabilityResult.isAvailable == false
, where FeatureAvailabilityResult.cause
indicates an unfulfilled condition.
All possible RuStoreException
errors are described in Error handling. Other errors are processed in onFailure
.
RuStoreBillingClient.Instance.CheckPurchasesAvailability(
onFailure: (error) => {
// Process error
},
onSuccess: (response) => {
if (response.isAvailable) {
// Process purchases available
} else {
// Process purchases unavailable
}
});
Working with SDK
Getting products list
Use the GetProducts
method to get a list of products.
RuStoreBillingClient.Instance.GetProducts(productIds,
onFailure: (error) => {
// Process error
},
onSuccess: (response) => {
// Process response
});
string[] productIds
— list of products IDs.
This method returns List<Product>
.
Product structure
public class Product {
public enum ProductStatus {
ACTIVE,
INACTIVE
}
public enum ProductType {
NON_CONSUMABLE,
CONSUMABLE,
SUBSCRIPTION
}
public string productId;
public ProductType productType;
public ProductStatus productStatus;
public string priceLabel;
public int price;
public string currency;
public string language;
public string title;
public string description;
public string imageUrl;
public string promoImageUrl;
public ProductSubscription subscription;
}
productId
— product ID..productType
— product type..productStatus
— product status..priceLable
— formatted purchase price, including the currency symbol inlanguage
.price
— price in minor units (in kopecks)..currency
— ISO 4217 currency code.language
— language specified with the BCP 47 encoding..title
— product name inlanguage
.description
— product description inlanguage
.imageUrl
— link to an image..promoImageUrl
— promotional picture link..subscription
— subscription description, returned only for products withsubscription
.
Subscription structure
public class ProductSubscription {
public SubscriptionPeriod subscriptionPeriod;
public SubscriptionPeriod freeTrialPeriod;
public SubscriptionPeriod gracePeriod;
public string introductoryPrice;
public string introductoryPriceAmount;
public SubscriptionPeriod introductoryPricePeriod;
}
subscriptionPeriod
— subscription period..freeTrialPeriod
— trial subscription period..gracePeriod
— grace period..introductoryPrice
— formatted introductory subscription price, including the currency symbol, inproduct:language
.introductoryPriceAmount
— introductory price in minor units of currency (in kopecks).introductoryPricePeriod
— calculated period of the introductory price..
Structure of the subscription period
public class SubscriptionPeriod {
public int years;
public int months;
public int days;
}
years
— number of years..months
— number of days..days
— number of days..
Getting purchases list
The method only returns purchases with statuses from the table below.
Type/Status | INVOICE_CREATED | CONFIRMED | PAID |
---|---|---|---|
CONSUMABLE | + | + | |
NON-CONSUMABLE | + | + | |
SUBSCRIPTION | + | + |
The method returns incomplete purchase and purchase consumable states that require processing. Apart from that, it shows confirmed purchases for subscriptions and non-consumable items - those that cannot be purchased again.
Use theGetPurchases
method to get the user's list of purchases.
RuStoreBillingClient.Instance.GetPurchases(
onFailure: (error) => {
// Process error
},
onSuccess: (response) => {
// Process response
});
This method returns List<Purchase>response
— list of products.
Purchase Structure
public class Purchase {
public enum PurchaseState
{
CREATED,
INVOICE_CREATED,
CONFIRMED,
PAID,
CANCELLED,
CONSUMED,
CLOSED
}
public string purchaseId;
public string productId;
public string description;
public string invoiceId;
public string language;
public DateTime purchaseTime;
public string orderId;
public string amountLabel;
public int amount;
public string currency;
public int quantity;
public PurchaseState purchaseState;
public string developerPayload;
public string subscriptionToken;
}
purchaseId
— purchase ID..productId
— product ID..description
— product description inlanguage
.invoiceId
— invoice ID..language
— language specified with the BCP 47 encoding..
.purchaseTime
— time of purchase.orderId
— unique payment identifier generated by the application (uuid);.amountLable
— formatted purchase price, including the currency symbol inlanguage
.amount
— price in minor units of currency..currency
— ISO 4217 currency code.quantity
— product quantity..purchaseState
— purchase state.:developerPayload
— уline specified by the developer that contains additional information about the order..subscriptionToken
— token for server validation..
Confirming purchase
Products that require confirmation
The RuStore application consists of the following types of products:
SUBSCRIPTION
— subscription (can be purchased for a period of time, such as a streaming service subscription)..NON_CONSUMABLE
— non-consumables (one-time purchases, such as disabling ads in an app).
.CONSUMABLE
— consumables (multiple-time purchases, such as crystals in the app);
Only CONSUMABLE
type products require confirmation if they are in PurchaseState.PAID
state.
Calling confirmation method
Use theconfirmPurchase
method to call a product purchase. The release of the goods must be accompanied by a purchase confirmation request. Once the confirmation is called, the purchase will have a CONSUMED
status.
RuStoreBillingClient.Instance.ConfirmPurchase(
purchaseId: "purchaseId" ,
onFailure: (error) => {
// Process error
},
onSuccess: () => {
// Process success
}
);
purchaseId
— purchase ID..
Canceling purchase
Use theDeletePurchase
method to cancel a purchase.
RuStoreBillingClient.Instance.DeletePurchase(
purchaseId: "purchaseId" ,
onFailure: (error) => {
// Process error
},
onSuccess: () => {
// Process success
}
);
purchaseId
— purchase ID..
Note. Use this method if your app logic is related to purchase cancellation. The purchase is canceled automatically after a 20-min timeout, or upon a second purchase from the same customer.
Errors processing
Possible errors
RuStoreNotInstalledException
— RuStore not installed on user's device;RuStoreOutdatedException
— RuStore, installed on the user's device, does not support payment processing functions.;RuStoreUserUnauthorizedException
— user not authorized on RuStore;RuStoreRequestLimitReached
— not enough time has passed since the process was last shown.;RuStoreReviewExists
— this user has already rated your app.;RuStoreInvalidReviewInfo
— problems withReviewInfo
;RuStoreException
— basic RuStore error, from which all other errors are inherited..
All the errors that may occur are processed by onFailure
.
Error structure
public class RuStoreError {
public string name;
public string description;
}
name
– error name..description
– error description..
Auto error handling
When thePurchaseProduct
method is called, errors are handled automatically.
If the allowNativeErrorHandling == true
parameter was passed during SDK initialisation, an error dialog will be displayed to the user when an error occurs, apart from calling the appropriate Failure
handler.
public fun RuStoreException.resolveForBilling(context: Context)
You can change this behavior after the initialization by setting AllowNativeErrorHandling
property:
RuStoreBillingClient.Instance.AllowNativeErrorHandling = false ;
Confirm and delete purchase scenario
Due to the change of the product purchase model result, the business logic of the purchase confirmation and cancellation was also changed.
The purchase cancellation method (deletePurchase
) should be used if:
-
The method of getting the list of products (
getPurchases
) returned the purchase status as follows:PurchaseState.CREATED
;PurchaseState.INVOICE_CREATED
;
-
The purchase method (
purchaseProduct
) returned:PaymentResult.Cancelled
;PaymentResult.Failure
.
Use product consumption method (confirmPurchase
) if the method the purchase obtaining method (getPurchases
) returns a CONSUMABLE
product and with the status PurchaseState.PAID
.