NAV Navbar

YandexCheckout.js

YandexCheckout.js is a JavaScript library used by Merchants for creating customized payment acceptance forms on their side. It acts as an extension of the Yandex.Checkout API.

Right now, the library contains only the forms for accepting bank card payments, but we do plan to add other payment methods available in Yandex.Checkout (for example, payments via Sberbank Online or Apple Pay) in the future.

Using this library, you can:

Initialization

Link to the library

<script src="https://static.yandex.net/checkout/js/v1/"></script>

You can only connect to YandexCheckout.js from the https://static.yandex.net servers, so that your clients' sensitive data is always safe.

Load the main library to start working with the API.

Authentication

Example of a created YandexCheckout

const checkout = YandexCheckout(<Shop ID>);

Create a YandexCheckout object using the following structure: YandexCheckout(<Shop ID>)

<Shop ID> is shopId of your shop in Yandex.Checkout (it's issued upon onboarding and can be found in your Yandex.Checkout Merchant Profile).

After that you can create a YandexCheckout instance and use it to generate a bank card information token.

Configuration

Example of initialization with selected language

const checkout = YandexCheckout(<Shop ID>, {
    language: 'en'
});

You can show the error messages to your users in Russian and English languages. The default language for error messages is Russian.

Parameter Description Type Validation
language Language for user error messages. Possible values: en and ru string 2 symbols

Tokenization

Example of generated token

checkout.tokenize({
    number: document.querySelector('.number').value,
    cvc: document.querySelector('.cvc').value,
    month: document.querySelector('.expiry_month').value,
    year: document.querySelector('.expiry_year').value
}).then(res => {
    if (res.status === 'success') {
        const { paymentToken } = res.data.response;

        return paymentToken;
    }
});

Generate a payment token containing bank card data. The token can be used for carrying out transactions using the Yandex.Checkout API.

Method parameters

Example of valid data

checkout.tokenize({
    number: document.querySelector('.number').value,
    cvc: document.querySelector('.cvc').value,
    month: document.querySelector('.expiry_month').value,
    year: document.querySelector('.expiry_year').value
}).then(response => {
    if (response.status === 'success') {
        const { paymentToken } = response.data.response;

        // eyJlbmNyeXB0ZWRNZXNzYWdlIjoiWlc...
        return paymentToken;
    }
});

Example of invalid data

checkout.tokenize({
    number: document.querySelector('.number').value,
    cvc: document.querySelector('.cvc').value,
    month: document.querySelector('.expiry_month').value,
    year: document.querySelector('.expiry_year').value
}).then(response => {
    if (response.status === 'error') {
        // validation_error
        const { type } = response.error;

        /*
            [
                {
                    code: 'invalid_expiry_month',
                    message: 'Invalid month value'
                },
                {
                    code: 'invalid_cvc',
                    message: 'Invalid CVC value'
                }
            ]
        */
        const { params } = response.error;

        return response;
    }
});
Parameter Description Type Validation
number * Bank card number string 16 symbols, numeric only
cvc * CVC2 or CVV2 code, 3 or 4 symbols, printed on the back of the card string 3, 4 symbols, numeric only
month * Month of the card expiration date string 2 symbols, numeric only
year * Year of the card expiration date string 2 symbols, numeric only

Errors

The library returns two types of errors: errors related to data validation in the form and errors related to YandexCheckout.js performance.

Validation errors occur when the user enters invalid bank card data: they should be shown to the user.

Other errors occur as a result of the problems with the library initialization, or the problems with the interaction between the library and Yandex.Checkout. You don't have to show these error messages to the user.

try {
    const checkout = YandexCheckout(); // Missing shopId
} catch(error) {
    // See response format in the Errors section
}

Error message format

{
    status: 'error',
    error: {
        type: string,
        message: ?string,
        status_code: number,
        code: ?string,
        params: Array<{
            code: string,
            message: string
        }>
    }
}

Example 1. Failure to connect to the server

{
    status: 'error',
    error: {
        type: 'api_connection_error',
        message: 'Failure to connect to the server',
        status_code: 402,
        code: 'processing_error',
        params: []
    }
}

Example 2. Validation error

{
    status: 'error',
    error: {
        type: 'validation_error',
        message: undefined,
        status_code: 400,
        code: undefined,
        params: [
            {
                code: 'invalid_number',
                message: 'Invalid card number'
            },
            {
                code: 'invalid_expiry_month',
                message: 'Invalid month value'
            }
        ]
    }
}

Response codes

Response code Value
400 Validation error
401 Authentication error
402 Failure to connect to the Yandex.Checkout API
404 Requested resource not found
500 Internal server error

YandexCheckout.js supports standard response codes:

Error types

Error type Meaning
authentication_error Authentication error
api_connection_error Couldn't connect to Yandex.Checkout
api_error Error on Yandex.Checkout's side
card_error Something is wrong with the bank card
invalid_request_error Invalid request data
validation_error Validation error: invalid value in one of the data input fields

Error codes

Error code Meaning
invalid_number Invalid card number
invalid_expiry_month Invalid month of the card expiration date
invalid_expiry_year Invalid year of the card expiration date
invalid_cvc Invalid CVC code
expired_card The card has expired
card_declined The card is declined
processing_error Failure to process the card
missing Internal server error

YandexCheckout UI

UI library that works with YandexCheckout.js and allows showing users a ready-made bank card payment form.

It can:

Initialization

Add the script to the page

<script src="https://static.yandex.net/checkout/ui/v1/"></script>

Create YandexCheckoutUI instance

const $checkout = YandexCheckoutUI(123456);

Where 123456 is your shopId

You can connect to the library only via CDN.

Add the script from CDN. The library will be available in the global scope under the YandexCheckoutUI name.

After that you can create a YandexCheckoutUI instance and use $checkout to generate bank card data tokens.

Configuration

Example with YandexCheckoutUI configuration

const $checkout = YandexCheckoutUI(123456, {
    language: 'en',
    domSelector: '.my-selector',
    amount: 99.99
});

You can configure the form:

Parameter Description Type Default
language Interface language (display text, responses, errors). Possible values: en or ru string ru
amount The payment amount shown in the form number 0
isRecurrent The form will show the message informing of further direct debits (recurrent payments) boolean false

Possible values

{
    // response messages language
    language: string ('en' | 'ru') ['ru'],

    // amount shown in the form
    amount: number ['0'],

    // Recurrent payments enabled
    isRecurrent: true [false]
}

Methods

Method Description Recieves Returns
.open Shows the form {void}
.close Hides the form {void}
.on Enables notifications yc_error, yc_success {void}
.showLantern Shows message to the user text string {void}
.hideLantern Hides message from the user {void}
.showLantern Changes the status of message for the user text string {void}
.chargeSuccessful Informs the form of a successful response from the Yandex.Checkout API text string {void}
.chargeFailful Informs the form of an error from the Yandex.Checkout API text string {void}

.open

Shows the payment form.

const $checkout = YandexCheckoutUI(123456);
$checkout.open();

.close

Hides the payment form.

const $checkout = YandexCheckoutUI(123456);
$checkout.close();

.on

Allows subscribing to notifications informing of everything going on with the library.

Available notifications:

Notification Description Returns
yc_error An error of some kind has occurred Object is identical to the error in Yandex.CheckoutJS
yc_success A token has been successfully created Object is identical to the successful response in Yandex.CheckoutJS

Example of error

$checkout.on('yc_error', response => {
    /*
    {
        status: 'error',
        error: {
            type: 'validation_error',
            message: undefined,
            status_code: 400,
            code: undefined,
            params: [
                {
                    code: 'invalid_number',
                    message: 'Invalid card number'
                },
                {
                    code: 'invalid_expiry_month',
                    message: 'Invalid month value'
                }
            ]
        }
    }
    */
});

Example of successful token creation

$checkout.on('yc_success', response => {
    /*
    {
        status: 'success',
        data: {
            message: 'Payment token created',
            status_code: 200,
            type: 'payment_token_created',
            response: {
                paymentToken: 'eyJlbmNyeXB0ZWRNZXNzYWdlIjoiWlc1amNubHdkR1ZrVFdWemMyRm5aUT09IiwiZXBoZW1lcmFsUHVibGljS2V5IjoiWlhCb1pXMWxjbUZzVUhWaWJHbGpTMlY1IiwidGFnIjoiYzJsbmJtRjBkWEpsIn0K'
            }
        }
    }
    */
    console.log(response);
});

.showLantern

Shows a message above the form to the user (in case there's a request error in the Yandex.Checkout API).

Parameter Type Description
text string Error description
const $checkout = YandexCheckoutUI(123456);
$checkout.showLantern('Error description');

.hideLantern

Allows hiding the error message.

const $checkout = YandexCheckout(123456);
$checkout.hideLantern();

.toggleLantern

Opens or closes the error message.

Parameter Type Description
text string Error description
const $checkout = YandexCheckoutUI(123456);
$checkout.toggleLantern('Error description');

.chargeSuccessful

Informs the form of a successful response from the Yandex.Checkout API.

After this method is called:

const $checkout = YandexCheckoutUI(123456);

// Open the form
$checkout.open();

// Token successfully created
$checkout.on('yc_success', () => {
    // Request to Yandex.Checkout API
    // ...

    // If the payment is successful, call the method
    $checkout.chargeSuccessful();
});

.chargeFailful

Informs the form of an error from the Yandex.Checkout API.

After this method is called, the error message will be shown to the user.

Parameter Type Description
text string Error description
const $checkout = YandexCheckoutUI(123456);

// Open the form
$checkout.open();

// Token successfully created
$checkout.on('yc_success', () => {
    // Request to Yandex.Checkout API
    // ...

    // Failure to conduct transaction
    $checkout.chargeFailful();
});

Mobile SDK

These libraries allow you to integrate payment acceptance in iOS and Android mobile apps, providing ready-made payment interfaces, such as the payment form and everything related to it. SDK operates on the basis of the Yandex.Checkout API.

Demo app

You can install our special demo app to preview payment interfaces and the payment process. Using the demo app, you can recreate the entire process the same way your customers will see it: click the Buy button, enter your bank card details or Yandex.Money wallet details, and select one of the several payment scenarios.

Download the demo app (installed from smartphone):

By clcking these links, you accept the license agreement

Operating SDK

First of all, you need to integrate payment acceptance via the Yandex.Checkout API and tell the manager that you want to process payments using mobile SDK. After that:

  1. Issue a client apps key in your Merchant Profile (this option is enabled by request to the manager).

  2. Add SDK to the app and set it up to generate one-time payment tokens.

  3. Set up the process of sending one-time tokens from the mobile app to your system (for example, to the back-end of your website interacting with Yandex.Checkout).

  4. Make payments using payment tokens via the Yandex.Checkout API.

SDK for iOS

Requirements

iOS 8.0, 9, 10 and 11

Integration

Integrate the libraries via CocoaPods. Add these lines to your Podfile:

pod 'Gloss', '~> 1.2.2'
pod 'When', '~> 3.0.0'
pod 'FunctionalSwift', '~> 1.0.2'
pod 'Alamofire', '~> 4.7.0'
pod 'GMEllipticCurveCrypto', '~> 1.3.0'
pod 'KeychainAccess', '~> 3.1.0'
  1. Request the Yandex.Checkout libraries for installing SDK from the manager.
  2. Install Сarthage.
  3. Integrate additional libraries: Alamofire, FunctionalSwift, GMEllipticCurveCrypto, Gloss, KeychainAccess и When (see example for versions).
  4. Add the Yandex.Checkout libraries to the Embedded Binaries section.
  5. Add a new script with /usr/local/bin/carthage copy-frameworks command to Build Phases. Set the Yandex.Chekout libraries in the Input Files field of the script.

Yandex.Money Authorization in Yandex (for payments from the wallet)

Add these lines to info.plist

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>yandexauth</string>
  <string>yandexauth2</string>
</array>

Add these lines to AppDelegate

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    do {
        try YandexLoginService.activate(withAppId: <ID from Yandex.OAuth>)
    } catch {
        // process error
    }
}

func application(_ application: UIApplication,
                 continue userActivity: NSUserActivity,
                 restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    YandexLoginService.processUserActivity(userActivity)
    return true
}

func application(_ app: UIApplication,
                 open url: URL,
                 options: [UIApplicationOpenURLOptionsKey: Any]) -> Bool {
    return YandexLoginService.handleOpen(url, sourceApplication: options[.sourceApplication] as? String)
}

To accept payments from Yandex.Money wallets, you will need to be authorized in Yandex. Authorization is not required for bank card payments.

1. Register your app in Yandex.OAuth and save ID.

2. Add two URL schemes to info.plist.

3. In the Capabilities section of your project enable Associated Domains and add the domain from the template:

applinks:yx<ID from yandex.OAuth>.oauth.yandex.ru

For example, if your ID from Yandex.OAuth is 333, the domain will look like this: applinks:yx333.oauth.yandex.ru.

4. Add the code from the example to AppDelegate.

Prepare to accept payments

Creating TokenizationModuleInputData

import YandexMoneyPayments


let clientApplicationKey = "<Client apps key>"
let amount = Amount(value: <Amount>, currency: <Currency>),

let inputData = TokenizationModuleInputData(clientApplicationKey: clientApplicationKey,
                                            shopName: "<Store name>",
                                            purchaseDescription: """
                                                    <Product description>
                                                    """,
                                            amount: amount)

Create TokenizationModuleInputData. You will need the client apps key from your Yandex.Checkout Merchant Profile.

Get a token

Getting a token

let viewController = TokenizationAssembly.makeModule(inputData: inputData,
                                                     moduleOutput: self)
present(viewController, animated: true, completion: nil)

Create ViewController from TokenizationAssembly put it on the screen.

Make a payment with the token

Seniding the token to your system

func tokenizationModule(_ module: TokenizationModuleInput,
                        didTokenize token: Tokens,
                        paymentMethodType: PaymentMethodType) {
    DispatchQueue.main.async { [weak self] in
        guard let strongSelf = self else { return }
        strongSelf.dismiss(animated: true)
    }
    // Send the token to your system
}

func didFinish(on module: TokenizationModuleInput) {
    DispatchQueue.main.async { [weak self] in
        guard let strongSelf = self else { return }
        strongSelf.dismiss(animated: true)
    }
}

Close ViewController and send the token to your system. Then create a Yandex.Checkout API payment and specify the token received from SDK in the payment_token parameter.

SDK for Android

Requirements

Android 4.0 (API 14) or higher

Library integration

Add repository and set up dependecies in the build.gradle file of your project.

Add repositories and dependecies

repositories {

    // mavenCentral() or jcenter()

}

dependecies {

    implementation 'ru.yandex.money:msdk-android:1.0.0'

}

The library operates by referencing the ru.yandex.money.android.sdk.Checkout class.

Authorization in Yandex (for payments from the wallet)

Add ID from Yandex.OAuth to the app

android {
    defaultConfig {
        manifestPlaceholders = [YANDEX_CLIENT_ID:"<ID from Yandex.OAuth>"]
    }
}

To issue payment tokens for Yandex.Money wallets, you need to register the app in Yandex:

1. Register your app in Yandex.OAuth and save ID.

Select Android app in the Platforms block.

Check Access to login, given name, surname and gender in the Yandex.Passport API block (these are required for proper display of user's name).

2. Specify the ID you received during registration in Yandex.OAuth to your app.

If you want to accept payments only from bank cards, specify PaymentMethodType.BANK_CARD when you issue a token (Checkout.tokenize()).

Connecting library to fragment or activity

Example

public final class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        Checkout.attach(getSupportFragmentManager());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Checkout.detach();
    }
}

To integrate interface, you will need to call the Checkout.attach() method before starting tokenization (it's preferable to call it right after creating fragment or activity that you will start tokenization from).

Call the Checkout.detach() method when destroying fragment or activity.

Checkout.attach()

Method's input parameters:

Parameter Description
supportFragmentManager (FragmentManager) Fragment manager.

Starting tokenization

Starting tokenization

class MyActivity extends AppCompatActivity {
    // Your code

    void timeToStartCheckout() {
        Checkout.tokenize(
             this,
             new Amount(new BigDecimal("10.0"), Currency.getInstance("RUB")),
             new ShopParameters(
                   "<Store name>",
                   "<Store description>",
                   "<Client apps key>"));
    }
}

To start the tokenization process you will need to call the Checkout.tokenize() method. SDK will manage the process after that.

Checkout.tokenize()

Method's input parameters

Parameter Type Description
context Context App context.
amount Amount Payment amount.
shopParameters ShopParameters Store parameters (same for payments).

ShopParameters class fields

Parameter Type Description
title string Store name.
subtitle string Store description.
clientApplicationKey string Client apps key from Yandex.Checkout's Merchant Profile.
paymentMethodType PaymentMethodType List of payment methods. If you leave this field blank and send it as null, the user will see all the available payment methods. Possible values: YANDEX_MONEY — Yandex.Money wallet, BANK_CARD — bank card.

Amount class fields

Parameter Type Description
value BigDecimal Amount.
currency Currency Currency.

Tokenization results

Getting tokenization results

class MyActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Checkout.setResultCallback(new Checkout.ResultCallback() {
            @Override
            public void onResult(@NotNull String paymentToken, @NotNull PaymentMethodType type) {
                //result handling
            }
        });
    }
}

To get the tokenization results, use the Checkout.setResultCallback() method.

If the tokenization is successful, SDK will return the token and the payment method it was issued for.

Checkout.setResultCallback()

Method's input parameters:

Checkout.ResultCallback returns: