Skip to main content

6.0.0

With RuStore you can integrate payments in your mobile app.

tip

If you are in doubt read the instruction in the usage scenarios.

Implementation example

Look at the example app to learn how to integrate our SDK.

Prerequisites

  • App uploaded to RuStore Console.
  • App passed moderation (you don't have to publish the app).
Important
  • Test build signature (for example: debug) of the app must match the signature of the app build that was uploaded to the console and passed moderation (for example, release).
  • The user and the app are not banned in RuStore.
  • In-app purchases for the app are enabled in RuStore Console.
caution

The service has some restrictions to work outside of Russia.

Getting started

Run the following command to connect the package to your project.

// HTTPS
npm install git+https://git@gitflic.ru/project/rustore/react-native-rustore-billing-sdk.git

// SSH
npm install git+ssh://git@gitflic.ru/project/rustore/react-native-rustore-billing-sdk.git

RuStore SDK uses deeplink to handle third-party payment applications. This makes it easier to pay with third-party apps and return to your app.

To configure deeplinks functionality in your app and RuStore SDK, define deeplinkScheme in your AndroidManifest file and redefine the onNewIntent method of your activity.

AndroidManifest.xml
<activity
android:name=".sample.MainActivity">
<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>

Replace yourappscheme in the example above with the name of your scheme. For example, ru.package.name.rustore.scheme.

info

The scheme defined in the Androidmanifest file must match the scheme you specify in the create method of the RuStore SDK billing.

Initialization

Initialize the library before calling its methods.

For initialization, call the RustoreBillingClient.init() method.
try {  
RustoreBillingClient.init({
consoleApplicationId: 'appId' ,
deeplinkScheme: 'scheme' ,
});
console.log(initialize success: ${result});
} catch (err) {
console.log(initialize err: ${err});
}
  • consoleApplicationId — идентификатор приложения из консоли RuStore.

  • deeplinkScheme — deeplink scheme that i sused to return to your app after paying with a third party payment app (for example, SberPay or SBP). SDK generates its own host to this scheme.
note
Tye deeplink scheme that is passed in deeplinkScheme must match the scheme specified in AndroidManifest.xml (see Deeplink processing).

Before you start

Payment appRuStore Server RuStore_Billing_ClientYour serverYour appUserPayment appRuStore Server RuStore_Billing_ClientYour serverYour appUserPayments availability check[Optional]Server validation[Mandatory]Purchasing consumable product[Mandatory]Deeplink processing for paying with SBP, SberPay, etc.Product purchaseStarts your app checkPurchasesAvailabilityResult getProductsProducts list of your appDisplaying list of available purchasesPurchasing product purchaseProductRequest payment methodMaking paymentPayment methodPayment resultPayment infoServer validation (public API)Reliable purchase informationDeliver product to the userValidation result confirmPurchaseConsumption result purchaseProductRequest payment methodSpecified SBP/SberPay/T-PayStart payment processPayment scenarioPurchase paymentReturn to app OnNewIntentPayment resultDisplaying payment screen with the result

Payments availability check

During the purchases availability check, the following conditions are verified.

  • The current version of RuStore is installed on the user's device.
  • RuStore app supports payments.
  • User is authorized in RuStore.
  • The user and the app are not banned in RuStore.
  • In-app purchases for the app are enabled in RuStore Console.

To check payments availability, use the RustoreBillingClient.checkPurchasesAvailability() method.If all above conditions are met, true is returned.

try {
const isAvailable = await RustoreBillingClient.checkPurchasesAvailability();
console.log(available success ${isAvailable});
} catch (err) {
console.log(available error ${err});
}

Working with SDK

Retrieving products list

You verified that payments are available and the users are able to make purchases. Now you can request products list. Use the RustoreBillingClient.getProducts(productIds) method to request the information about products added to your app in RuStore Console.

try {
const products = await RustoreBillingClient.getProducts(productIds);
for (const product of products) {
console.log(product?.productId);
}
} catch (err) {
console.log(products err: ${err});
}

productIds — the list of product IDs. Must not exceed 100 entries.

To specify id of the products needed for the method, do the following.

  1. Open RuStore Console.
  2. Navigate to the Applications tab.
  3. Select the necessary app.
  4. In the left side menu select Monetization.
  5. Select product type: Subscriptions or In-App purchases.
  6. Copy the IDs of the required products. These are product ids.

The method returns products list Product[]. Below is the product pattern.

interface Product {
productId: string;
productType?: ProductType;
productStatus: ProductStatus;
priceLabel?: string;
price?: number;
currency?: string;
language?: string;
title?: string;
description?: string;
imageUrl?: string;
promoImageUrl?: string;
subscription?: ProductSubscription;
}
  • productId — product ID assigned to product in RuStore Console (mandatory).
  • productType — product type: CONSUMABLE/NON-CONSUMABE/SUBSCRIPTION.
  • productStatus — product status.
  • priceLabel — formatted product price, including currency symbol in language.
  • price — price in minimum currency units.
  • currency — ISO 4217 currency code.
  • language — language specified with BCP 47 code.
  • title — product name in language.
  • description — descriptions in language.
  • imageUrl — image URL.
  • promoImageUrl — promo image URL.
  • subscription — subscription description, returns only for subscription products.

Subscription structure

interface ProductSubscription {
subscriptionPeriod?: SubscriptionPeriod;
freeTrialPeriod?: SubscriptionPeriod;
gracePeriod?: SubscriptionPeriod;
introductoryPrice?: string;
introductoryPriceAmount?: string;
introductoryPricePeriod?: SubscriptionPeriod;
}
  • subscriptionPeriod — subscription period.
  • freeTrialPeriod — subscription trial period.
  • gracePeriod — subscription grace period.
  • introductoryPrice — formated introductory price with the currency symbol in the product:language language.
  • introductoryPriceAmount — introductory price in minimum currency units.
  • introductoryPricePeriod — introductory price invoice period.

SubscriptionPeriod structure

interface SubscriptionPeriod {
years: number;
months: number;
days: number;
}
  • years — amount of years.
  • months — amount of months.
  • days — amount of days.

Purchasing product

To purchase product, use the RustoreBillingClient.purchaseProduct({...}) method.

try {
const response = await RustoreBillingClient.purchaseProduct({
productId: 'productId',
orderId: 'orderId',
quantity: 0,
developerPayload: 'developerPayload'
});
console.log(purchase success: ${response});
} catch (err) {
console.log(purchase err: ${err});
}
  • productId — product ID assigned to product in RuStore Console (mandatory).
  • orderId — payment ID generated by the app (optional). If you specify this parameter in your system, you will receive it via our API. Если не укажете, он будет сгенерирован автоматически (uuid). Максимальная длина 150 символов.
  • quantity — количество продукта (необязательный параметр — если не указывать, будет подставлено значение 1).
  • developerPayload — string with additional order information, that you can specify on purchase initialization.

A purchase may result in one of the following interfaces: SuccessPayment, CancelledPayment, or FailurePayment.

enum PaymentResult {
SUCCESS = 'SUCCESS',
CANCELLED = 'CANCELLED',
FAILURE = 'FAILURE',
}
interface SuccessPaymentResult {
orderId?: string;
purchaseId: string;
productId: string;
invoiceId: string;
sandbox: boolean;
subscriptionToken?: string;
}
interface SuccessPayment {
type: PaymentResult.SUCCESS;
result: SuccessPaymentResult;
}
interface CancelledPaymentResult {
purchaseId: string;
sandbox: boolean;
}
interface CancelledPayment {
type: PaymentResult.CANCELLED;
result: CancelledPaymentResult;
}
interface FailurePaymentResult {
purchaseId?: string;
invoiceId?: string;
orderId?: string;
quantity?: number;
productId?: string;
errorCode?: number;
sandbox: boolean;
}
interface FailurePayment {
type: PaymentResult.FAILURE;
result: FailurePaymentResult;
}
  • SuccessPayment - successful purchase result.
  • FailurePayment - there was a problem during sending payment request or receiving payment status, purchase status unknown.
  • CancelledPayment — payment request sent, although, the user closed the payment screen on their app, thus, the payment result is unknown.

Getting products list

This method returns purchases with the following statuses. For more informations on possible purchase states see Getting purchase info.

Type/StatusINVOICE_CREATEDCONFIRMEDPAIDPAUSED
CONSUMABLE++
NON-CONSUMABLE++
SUBSCRIPTION+++
note

This method returns incomplete purchases that require attention. Also, it shows confirmed subscriptions and consumable products that cannot be purchased more than once.

Go get the user's purchases list, use the RustoreBillingClient.getPurchases() method.

try {
const purchases = await RustoreBillingClient.getPurchases();
for (const purchase of purchases) {
console.log(purchase?.purchaseId);
}
} catch (err) {
console.log(purchase err: ${err});
}

The method returns purchases list Purchase[]. Below is the purchase pattern:

interface Purchase {  
purchaseId?: string;
productId: string;
productType?: ProductType;
invoiceId?: string;
language?: string;
purchaseTime?: string;
orderId?: string;
amountLabel?: string;
amount?: number;
currency?: string;
quantity?: number;
purchaseState?: PurchaseState;
developerPayload?: string;
subscriptionToken?: string;
}
  • purchaseId — product ID.

  • productId — product ID assigned to product in RuStore Console (mandatory).

  • productType — product type: CONSUMABLE/NON-CONSUMABE/SUBSCRIPTION.

  • invoiceId — invoice ID.

  • language — language specified with BCP 47 code.

  • purchaseTime — purchase time.

  • orderId — payment ID generated by the app (optional). If you specify this parameter in your system, you will receive it via our API. Если не укажете, он будет сгенерирован автоматически (uuid). Максимальная длина 150 символов.

  • amountLable — formatted purchase price, including currency symbol.

  • amount — price in minimum currency units.

  • currency — ISO 4217 currency code.

  • quantity — количество продукта (необязательный параметр — если не указывать, будет подставлено значение 1).

  • purchaseState — purchase state:

    • CREATED — purchase created;
    • INVOICE_CREATED — purchase invoiced is created and awaiting payment;
    • PAID — only for consumable products — intermediate status, the funds on the user's account are put on hold. The purchase is awaiting confirmation from the developer;
    • CONFIRMED — payment for non-consumable product successful;
    • CONSUMED — payment for consumable product successful;
    • CANCELLED — purchase canceled — there was no payment or the payment was refunded (if a purchase is a subscription it doesn't change its state to CANCELLED);
    • PAUSED — for subscriptions — the purchase is in HOLD period;
    • TERMINATED — subscription terminated.
  • developerPayload — string with additional order information, that you can specify on purchase initialization.

  • subscriptionToken — purchase token for server validation .

Getting purchase information

Go get purchase information, use the getPurchaseInfo method.
try {
const purchaseInfo = await RustoreBillingClient.getPurchaseInfo(purchaseId);
console.log(purchase info ${purchaseInfo});
} catch (err) {
console.log(purchase error ${err});
}

purchaseId — product ID.

This method returns Purchase, which is described above.

State model (purchaseState)

CONSUMABLES - purchase state model

Purchase created, however, the invoice was not createdNo payment was made. This purchase can be ignored.The user has an unfinished purchase. Invoice was created but not paid. You need to inform the user.Purchase canceledFor consumable products. Purchase paid, but not consumed. Any App need to send an immediate request for purchase confirmation.For consumable products. Purchase consumption confirmed.CREATEDINVOICE_CREATEDCANCELLEDInvoice createdInvoice paidConsumptionPAIDCONSUMEDInvoice canceledPayment returnInvoice was paid and received an errorPurchase canceled

NON-CONSUMABLES - purchase state model

Purchase created, however, the invoice was not created. There was no payment. This purchase can be ignored.The user has an unfinished purchase. Invoice was created but not paid. You need to inform the user.Purchase canceledPayment confirmation status for non-consumable or subscription products. This status means that the product is purchased, further purchase attempts will lead errors.CREATEDINVOICE_CREATEDCANCELLEDInvoice creationPurchase confirmedCONFIRMEDInvoice canceledPayment returnPurchase cancellation

(SUBSCRIPTIONS) - purchase state model

img

Server validation

If you need to validate a successful app using API RuStore methods, you can use subscriptionToken in PurchaseResult returned by purchaseProduct on successful purchase.

SubscriptionToken consists of invoiceId and userId of the purchase separated by period: $invoiceId.$userId.

try {
const paymentResult = await RustoreBillingClient.purchaseProduct({productId});

if (paymentResult.type == PaymentResult.SUCCESS) {
const subscriptionToken = paymentResult.response.subscriptionToken
yourApi.validate(subscriptionToken)
}
setPayment(paymentResult);
} catch (err: any) {
setError(JSON.stringify(err));
}

You can also get a subscriptionToken from the Purchase entity. The Purchase entity can be retrieved using the getPurchases method.

const purchases = await RustoreBillingClient.getPurchases();
for (const purchase of purchases) {
yourApi.validate(purchase.subscriptionToken)
}

Consume (confirm) purchase

Us the RustoreBillingClient.confirmPurchase({...}) method to confirm a purchase. Purchase confirmation request must be accompanied by the delivery of the product. After calling the confirmation method the purchase changes its state to CONSUMED.

try {
const isConfirmed = await RustoreBillingClient.confirmPurchase({
purchaseId: 'purchaseId' ,
developerPayload: 'developerPayload'
})
console.log(confirm success: ${isConfirmed});
} catch (err) {
console.log(confirm err: ${err});
}
  • purchaseId — product ID.
  • developerPayload — string with additional order information, that you can specify on purchase initialization.

Provided that all conditions are met, the RustoreBillingClient.confirmPurchase() method returns true.

Products that require confirmation

Please, keep in mind the purchase type. Confirmation is only needed if your product is CONSUMABLE and can be purchased more than once.

To correctly deliver such products, confirm purchases with the confirmPurchase method. On delivering a product, use server validation. Deliver your product only after the payment (invoice) is in the CONFIRMED status. Use the addOnSuccessListener callback of the confirmPurchase method to deliver products.

Attention!

The PAID status is intermediate and meas that the user's money is put on hold on their card, so you need to confirm the purchase.

The exceptions are SBP or mobile payment — see the explanation below.

When paying for CONSUMABLE products with SBP or mobile payment, one-stage payment is used, although the payment model is as in two-stage payments. It means that what a payment is in the PAID status, when paying with SBP or mobile payment, the money is withdrawn from the buyer's account, as well as the developer's fee is withdrawn from their's. In this case, if a purchase is canceled from the PAID status the refund is made, not reverse. The developer's fee will not be returned. At the same time, to complete the purchase you still have to confirm purhchase — see the table below.

Payment methodPayment typePayment in the PAID status
  • bank cards;
  • Sber ID;
  • SberPay;
  • T-Pay;
  • VK Pay.
Two-stage
  • Money is on hold on the buyer's account.
  • Developer's fee is not applied.
  • Payment cancellation (reverse) is available.
  • SBP;
  • mobile payment.
One-stage
  • Money is withdrawn from the buyer's account.
  • The developer's fee is applied.
  • If a purchase is canceled form the PAID status the transaction is refunded, not reverse reversed. The developer's fee will not be returned.

ConfirmPurchase request

Purchase cancellation

To cancel a purchase, use the RustoreBillingClient.deletePurchase(purchaseId) method.

try {
const isDeleted = await RustoreBillingClient.deletePurchase(purchaseId)
console.log(delete success: ${isDeleted});
} catch (err) {
console.log(delete err: ${err});
}
  • purchaseId — product ID.

Provided that all conditions are met, the RustoreBillingClient.deletePurchase() method returns true.

info

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.

Handling pending payments

Handling of unfinished payments is done by the developer.

To confirm a purchase of CONSUMABLE product in the PAID state, call the [purchase confirmation method].(#confirm) (see Retrieve purchase details).

When dealing with purchase cancellation using payment processing methods take into account your business logic. Some developers implement additional checks before purchase confirmation or cancellation. In that case, make a separate purchase state request.

tip

For example, if the user paid for the product that you cannot deliver for some reason, call the payment cancellation method for the purchase in the PAID status to cancel the purchase.

If the get purchases list method returns a purchase in the INVOICE_CREATED state, you can us the purchase cancellation method. For instance, if you don't want to see a purchase in that state in the purchase list. This is optional as RuStore handles cancellation of such purchases on its side.

info

Sometimes, after paying with a bank app (SBP, SberPay, T-Pay etc.) and returning to the app, the status is still INVOICE_CREATED, and the payment status is unsuccessful. This is caused by the purchase processing time by the bank. In this case, you need to adapt your screen lifecycle to the product list retrieval logic.

Alternatively, you can implement cancellation of purchases in the INVOICE_CREATED state only through user action in your app. For example, create a dedicated button for this purpose.

Error handling

Possible errors

  • RuStoreNotInstalledException — RuStore is not installed on the user's device;
  • RuStoreOutdatedException — RuStore version installed on the user's device does not support this SDK;
  • RuStoreUserUnauthorizedException — user is not authorized in RuStore;
  • RuStoreRequestLimitReached — not enough time has passed since the process was last shown;
  • RuStoreReviewExists — this user has already rated your app;
  • RuStoreInvalidReviewInfo — problems with ReviewInfo;
  • RuStoreException — basic RuStore error from which other errors are inherited.