---
metadata:
  - name: generator
    content: Diplodoc Platform v5.55.3
alternate:
  - https://pay.yandex.ru/docs/en/custom/android-sdk/url-flow.md
  - href: en/custom/android-sdk/url-flow.md
    type: text/markdown
    title: Markdown version
  - href: ../../llms.txt
    type: text/markdown
    title: llms.txt
---
> **Documentation Index:** Fetch the complete configuration index at https://pay.yandex.ru/docs/en/llms.txt

# Enabling payments via a payment link

## General information {#url-flow-general-info}

{% note info %}

Starting with version 2.3.0-alpha01, the SDK uses a new workflow. For details, see this [article](https://pay.yandex.ru/docs/en/custom/mobile/redirect-scheme.md).

{% endnote %}

### How it works {#url-flow-work-scheme}

1. The user taps the pay button in the app.
1. <!-- source: en/_includes/pay-form.md -->
   The user goes to the Yandex Pay payment form screen, with the following information displayed:

   - A list of the user’s bank cards.
   - Payment options via the Faster Payment System (SBP).
   <!-- endsource: en/_includes/pay-form.md -->
1. <!-- source: en/_includes/card-selection.md -->
   The user selects a payment method and clicks on the order confirmation button.
   <!-- endsource: en/_includes/card-selection.md -->
1. Yandex Pay service completes a payment and returns the operation result.

#### Full payment

![flow](../_assets/android-sdk-bolt-payment-flow.png)

#### Split payment

![flow](../_assets/android-sdk-bolt-split-flow.png)

### Requirements for connecting {#url-flow-requirements}

Supported version: Android 7.0 and higher.

{% note info %}

If your project's minSdkVersion is 23 or lower, see info about [support for lower device versions](#min-sdk-support).

{% endnote %}

Before you start the integration, obtain the following IDs and add them to your project:

- [Merchant ID](https://pay.yandex.ru/docs/en/console/index.md)
- SHA256 Fingerprints
- Client ID (`YANDEX_CLIENT_ID`)
- Android package name (`applicationId`)

## Step 1. Obtain the required IDs {#create-oauth-app}

1. Get the SHA256 Fingerprints hash value using the `keytool` utility:

   ```Bash
   keytool -list -v -alias <your-key-name> -keystore <path-to-production-keystore>
   ```

   Once you enter the command, the hash value will be shown under `Certificate fingerprints: SHA256`.

1. <!-- source: en/custom/_includes/yandex-oauth.md -->
   To [register](../_includes/(https:/yandex.ru/dev/id/doc/en/register-client)) the app, go to [Yandex OAuth](https://oauth.yandex.com/) and click **Create app**.
   <!-- endsource: en/custom/_includes/yandex-oauth.md -->
1. <!-- source: en/custom/_includes/yandex-oauth.md -->
   In the **Service name** field, enter the name to be displayed to users on the authorization screen, and upload the application icon.
   <!-- endsource: en/custom/_includes/yandex-oauth.md -->
1. <!-- source: en/custom/_includes/yandex-oauth.md -->
   Under **Platforms**, select **Android app** and set its parameters:

   - **Android package name**: Unique app name from the project config file's `applicationId`.
   - **SHA256 Fingerprints**: SHA256 hash value from step 1. **The hash must contain capital letters only**.
   <!-- endsource: en/custom/_includes/yandex-oauth.md -->
1. <!-- source: en/custom/_includes/yandex-oauth.md -->
   Make sure that your app has access to Yandex Pay added in Yandex OAuth. To do this, select **Payment via Yandex Pay** in the **Permission name** field of the **Data access** section.
   <!-- endsource: en/custom/_includes/yandex-oauth.md -->
1. <!-- source: en/custom/_includes/yandex-oauth.md -->
   Click **Create app** and copy the **Client ID** field value.
   <!-- endsource: en/custom/_includes/yandex-oauth.md -->
1. <!-- source: en/custom/_includes/yandex-oauth.md -->
   On the [Settings](https://console.pay.yandex.ru/settings) page of the Yandex Pay dashboard, specify the Client ID, SHA256, and Android package name values in the **Client ID**, **SHA256 Fingerprints**, and **Android package name** fields, respectively.
   <!-- endsource: en/custom/_includes/yandex-oauth.md -->

## Step 2. Enable the Client ID {#include-yandex-client-id}

Specify the resulting Client ID in the `build.gradle` build script as the `YANDEX_CLIENT_ID` value in `manifestPlaceholders`:

```Gradle
   android {
     defaultConfig {
       manifestPlaceholders = [
         // Use your Client ID
         YANDEX_CLIENT_ID: "12345678901234567890",
       ]
     }
   }
```

## Step 3. Initialize FirebaseApp in all the app's workflows {#initialize-firebaseapp}

The Mobile SDK uses AppMetrica services to ensure the stable operation of the SDK. This step helps fix the Firebase and AppMetrica service compatibility issues.

If Firebase is used along with the Yandex Pay SDK, call ```FirebaseApp.initialize(context)``` in all the app's workflows.

If you use AppMetrica in your app, be sure to activate YandexMetrica after Firebase is initialized.

{% cut "Example" %}

  ```Kotlin

  // Don`t forget declare MyApplication in AndroidManifest.xml in <application/> block using android:name
  class MyApplication: Application() {

      override fun onCreate() {
          // Inited at every app processes
          FirebaseApp.initializeApp(this)
      }
  }
  ```

{% endcut %}


## Step 4. Enable the Yandex Pay SDK {#url-flow-include-sdk}

Add the following dependency to your `build.gradle` build scripts:

```Gradle
dependencies {
    implementation 'com.yandex.pay:pay:2.6.0'
}
```

## Step 5. Get an object of the payment session {#url-flow-get-payment-session}

Get an object of the payment session using the  `getYandexPaymentSession` function:

{% list tabs %}

- Kotlin

  ```Kotlin
    private val yaPayConfig = YPayConfig(
      merchantData = MerchantData(
          id = MerchantId("merchantId"),
          name = MerchantName("merchantName"),
          url = MerchantUrl("https://merchant.com/"),
      ),
      environment = YPayApiEnvironment.PROD,
    )

    private val paymentSessionKey = PaymentSessionKey(
      generateSessionKey()
    )

    private val paymentSession: PaymentSession = YPay.getYandexPaymentSession(
      context = this,
      config = yaPayConfig,
      sessionKey = paymentSessionKey  // Optional if you're using Kotlin for implementation
    )
  ```

- Java

  ```Java
    private YPayConfig getPayConfig() {
      return new YPayConfig(
          new MerchantData(
              new MerchantId("merchantId"),
              new MerchantName("MERCHANT_NAME"),
              new MerchantUrl("https://merchant.com/")
          ),
          YPayApiEnvironment.PROD
      );
    }

    private PaymentSessionKey getPaymentSessionKey() {
      return new PaymentSessionKey(
          generateSessionKey()
      );
    }

    private PaymentSession getPaymentSession() {
      return YPay.INSTANCE.getYandexPaymentSession(
          this,
          getPaymentSessionKey(),
          getPayConfig()
      );
    }
  ```

{% endlist %}

When getting a `PaymentSession`, be sure to pass:

- `Context`: The context of the application or Activity.
- `PaymentSessionKey`: Key of the payment session.
- `YPayConfig`: Data about the Yandex Pay SDK configuration.

When creating `YPayConfig`, be sure to pass:

- `merchantData`: Data of the merchant:

  - `id`: Unique merchant ID. You can get it when registering a merchant in Yandex Pay service.
  - `name`: The name of the merchant that the user will see.
  - `url`: The URL of the merchant that the user will see.

- `environment`: The Yandex Pay SDK execution environment:

  - `PROD`: Production environment.
  - `SANDBOX`: A test environment.

## Step 6. (optional) Place the Yandex Pay button on the screen {#url-flow-create-button}

Add the button to your layout:

```XML
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <com.yandex.pay.YPayButton
        android:id="@+id/y_pay_button"
        android:layout_width="300dp"
        android:layout_height="54dp"
        android:layout_marginTop="4dp"
        app:ypay_color_scheme="by_theme"
        app:ypay_corner_radius="4dp" />
```

When creating a button, you can pass values for the attributes:

- `ypay_color_scheme`: With this option, you can define the color palette of the button. Acceptable values:

  - `by_theme`: The color palette is adapted to match the system theme.
  - `light`: The color palette is always light.
  - `dark`: The color palette is always dark.

- `ypay_corner_radius`: With this option, you can define the corner radius for the button (in `dp`).

When initializing the view components, bind the current session's object to the button using a `PaymentSession` object and its `bindTo` function:

In addition, pass SessionListenerArgs with a list of payment methods allowed for the user.

{% list tabs %}

- Kotlin

  ```Kotlin
  fun initViews() {
      paymentSession.bindTo(yPayButton, SessionListenerArgs(listOf(PaymentMethodType.CARD,PaymentMethodType.SPLIT)))
  }
  ```

- Java

  ```Java
  void initViews() {
      getPaymentSession().bindTo(yPayButton);
  }
  ```

{% endlist %}

## Step 7. Initialize a contract for Yandex Pay launch {#url-flow-register-launcher}

When initializing the contract, add a callback that obtains the `YPayResult`:

{% list tabs %}

- Kotlin

  ```Kotlin
  private val yandexPayLauncher = YPayLauncher(this) { result: YPayResult ->
      when (result) {
          is YPayResult.Success -> showToast("Finished with success")
          is YPayResult.Cancelled -> showToast("Finished with cancelled event")
          is YPayResult.Failure -> showToast("Finished with domain error")
      }
  }
  ```

- Java

  ```Java
  private final YPayLauncher launcher = new YPayLauncher(this, yPayResult -> {
      if (yPayResult instanceof YPayResult.Success) {
          handleResult("Finished with success");
      } else if (yPayResult instanceof YPayResult.Cancelled) {
          handleResult("Finished with cancelled event");
      } else if (yPayResult instanceof YPayResult.Failure) {
          handleResult("Finished with domain error");
      }
  });
  ```

{% endlist %}

In the event of payment failure, the `errorMsg` error code is also returned:

| **Error code** | **Description** |
|----------------|-----------------|
| `incorrect payment url` | Invalid payment link |
| `transaction error` | Error performing transaction |
| `failed to parse order ID` | No `orderId` received with the results returned |
| `invalid intent parsing` | No payment results received |
| `invalid result code` | Invalid payment result code |
| `unresolved payment strategy` | Couldn't handle the payment results because your app shut down in the background |
| `session key not provided` | No session key provided |
| `config data not provided` | The `СonfigData` object not provided |
| `payment data not provided` | The `PaymentData` object not provided |

## Step 8. Generate data for launching Yandex Pay {#url-flow-create-launch-params}

Before launching Yandex Pay, generate payment data using the `PaymentData.PaymentUrlFlowData` class and [payment session data](#url-flow-get-payment-session). Create `YPayContractParams` based on this data.

{% list tabs %}

- Kotlin

  ```Kotlin
  val paymentData = PaymentData.PaymentUrlFlowData(
      // Order payment URL received from the Yandex Pay API
      paymentUrl = "payment-url"
  )

  val params = YPayContractParams(
      paymentSession = paymentSession,
      paymentData = paymentData,
  )
  ```

- Java

  ```Java
  final PaymentData paymentData = new PaymentData.PaymentUrlFlowData(
      // Order payment URL received from the Yandex Pay API
      "payment-url"
  );

  // Parameters for launching Yandex Pay
  final YPayContractParams params = new YPayContractParams(
      getPaymentSession(),
      paymentData
  );
  ```

{% endlist %}

{% note info %}

If you want to enable Split payments, pass the required parameters to `availablePaymentMethods` when generating a link.

For more information about generating a payment link, see the [backend documentation](https://pay.yandex.ru/en/docs/custom/backend/yandex-pay-api/order/merchant_v1_orders-post).

{% endnote %}

## Step 9. Launch Yandex Pay {#url-flow-run-service}

### Launch via the Yandex Pay button {#url-flow-run-service-with-button}

Pass the previously created launcher to the button using the `setOnClickListener` function and define its launch logic in a lambda expression. When running the launcher, pass the `YPayContractParams` [parameters](#url-flow-create-launch-params) to it:

{% list tabs %}

- Kotlin

  ```Kotlin
  yPayButton.setOnClickListener(yandexPayLauncher) { launcher ->
      val params = YPayContractParams(...)
      launcher.launch(params)
  }
  ```

- Java

  ```Java
  yPayButton.setOnClickListener(yandexPayLauncher, launcher -> {
      YPayContractParams params = new YPayContractParams(...);
      launcher.launch(params);
  });
  ```

{% endlist %}

{% note warning %}

The YPayButton has its own `setOnClickListener` function created. The entire logic for click handling should be specified in it. Calling the `View.setOnClickListener` will throw an exception.

{% endnote %}

### Launch without using the button {#url-flow-run-service-without-button}

Run the service using the [launcher](#url-flow-register-launcher), passing the `YPayContractParams` [launch parameters](#url-flow-create-launch-params):

{% list tabs %}

- Kotlin

  ```Kotlin
  val params = YPayContractParams(...)
  yandexPayLauncher.launch(params)
  ```

- Java

  ```Java
  final YPayContractParams params = new YPayContractParams(...);
  yandexPayLauncher.launch(params);
  ```

{% endlist %}

## Step 10. Handle the results {#url-flow-result-processing}

After Yandex Pay is launched, the SDK will select the optimal [strategy](https://pay.yandex.ru/docs/en/custom/mobile/redirect-scheme.md) and run the payment form to complete the payment in. The result will be obtained using the [launch contract](#url-flow-register-launcher) `YPayLauncher`.

{% note info %}

If you encounter any problems with the setup, see the [integration example](https://github.com/yandexmobile/yandex-pay-demo-android).

{% endnote %}

## Setup for devices with Android version lower than 7.0 {#min-sdk-support}

Owners of devices with Android 7.0 (API level 24) or higher can use the Yandex Pay SDK without any restrictions. There may be restrictions for devices with Android version lower than 7.0:

- No official support.
- Limited SDK functionality.
- Additional environment setup is required as described below.

1. Enable the SDK dependency in your project's `build.gradle` file:

    ```Gradle
    dependencies{
        ...
        implementation "com.yandex.pay:*pay/other*:*version*"
        ...
    }
    ```

2. Sync the project and try to build it. This should result in the manifest merger error:

    ```logcatfilter
    Manifest merger failed : uses-sdk:minSdkVersion *Your min version* cannot be smaller than version 24 declared in library
    ```

3. Open the AndroidManifest.xml file of the module where you're adding the dependency and list all the libraries this error refers to.

   Example:

    ```xml
    <manifest xmlns:tools="http://schemas.android.com/tools">
        <uses-sdk tools:overrideLibrary="com.yandex.pay, ...* other libraries *... ,com.yandex.pay.base"/>
    </manifest>
    ```

4. Check if the SDK is supported via the YPay object and initialize all the necessary components after the check:

    ```Kotlin
    if (YPay.isSupported){
        // init Yandex pay
    } else {
        // do some other logic
    }
    ```

   {% note warning %}

   Run the `YPay.isSupported` availability check each time the Yandex Pay SDK is accessed.

   {% endnote %}
