# Create subscription payment

Recurring payments via **SberPay** let you charge using a **token** linked to the subscription bank account. With an active subscription, debits run automatically — no payer action is required.

Contact your 1Payment account manager to enable this feature in your project.

## How it works

The SberPay subscription flow consists of four steps:

1. **Link subscription (first request)** — complete a successful payment with `subscribe=1` via the [payment form](/en/pages/sberpay/init-form) or [GATE](/en/pages/sberpay/host2host). The payer confirms the link in the SberBank Online app.
2. **Receive token** — after successful payment, 1Payment sends a unique `token` in the callback to `notify_url` or in the [status request](/en/pages/sberpay/status) response. Save it for subsequent charges.
3. **Auto-debit (recurring)** — for repeat payments, your server calls [GATE (host2host)](/en/pages/sberpay/host2host) (`init_payment`) with the saved `token`. If the subscription is active, the debit runs without payer involvement.
4. **Notification** — after each debit attempt, a callback arrives with the final transaction result.


## Technical details

| Stage | Endpoint | Methods |
|  --- | --- | --- |
| Subscription registration (form) | `https://api.1payment.com/init_form` | `GET`, `POST` |
| Subscription registration (GATE) | `https://api.1payment.com/init_payment` | `GET`, `POST` |
| Recurring debit (GATE) | `https://api.1payment.com/init_payment` | `POST` (recommended), `GET` |


Response format: **JSON**. For SberPay, specify `payment_type=sberpay` in requests.

## 1. Subscription registration (first request)

To register a subscription, complete a **successful payment** with `subscribe=1`. See [Create payment via form](/en/pages/sberpay/init-form) and [Create payment via host2host (GATE)](/en/pages/sberpay/host2host) for form and GATE parameters. Below is the required set for linking.

### Required parameters (initiation via form)

| Parameter | Type | Description |
|  --- | --- | --- |
| `partner_id` | Integer | Your unique ID in the 1Payment system. |
| `project_id` | Integer | Your project identifier. |
| `amount` | Number | Payment amount for linking (for example, `50.00`). |
| `subscribe` | Integer | Subscription creation flag. Always `1`. |
| `payment_type` | String | For SberPay, always `sberpay`. |
| `user_data` | String | Your unique order ID for matching. |
| `shop_url` | String | URL of the site where the purchase is made. |
| `sign` | String | Request signature (see below). |


### Required parameters (initiation via GATE)

| Parameter | Type | Description |
|  --- | --- | --- |
| `partner_id` | Integer | Your unique ID in the 1Payment system. |
| `payment_type` | String | Always `sberpay`. |
| `project_id` | Integer | Your project identifier. |
| `amount` | Number | Payment amount for linking (for example, `50.00`). |
| `subscribe` | Integer | Subscription creation flag. Always `1`. |
| `sberpay_type` | String | Interaction mode: `app2app`, `web2app`, or `mweb2app`. |
| `user_data` | String | Your unique order ID for matching. |
| `sign` | String | Request signature (see below). |


### Optional parameters (initiation)

| Parameter | Type | Description |
|  --- | --- | --- |
| `description` | String | Subscription description for the customer. |
| `phone` | String | Payer phone number. |
| `email` | String | Payer email address. |
| `success_url` | String | Customer return URL on success (form). |
| `failure_url` | String | Customer return URL on failure (form). |
| `deep_link` | String | Return address to your app after payment (GATE). |
| `user_id` | String | Payer ID in your system. |


**Signature for form registration** — prefix `init_form`. **Via GATE** — prefix `init_payment`.


```text
MD5(init_form + <params_excluding_sign_in_alphabetical_order_joined_with_&> + <API_KEY>)
```


```text
MD5(init_payment + <params_excluding_sign_in_alphabetical_order_joined_with_&> + <API_KEY>)
```

## 2. Recurring debit (repeat payments)

For automatic debits, send a request to [GATE (host2host)](/en/pages/sberpay/host2host) with the saved `token`. With an active subscription, no customer action is required.

### Required parameters (recurring)

| Parameter | Type | Description |
|  --- | --- | --- |
| `partner_id` | Integer | Your unique ID in the 1Payment system. |
| `payment_type` | String | Always `sberpay`. |
| `project_id` | Integer | Your project identifier. |
| `amount` | Number | Amount of the scheduled debit (for example, `500.00`). |
| `token` | String | Token received at subscription registration (from callback or status request). |
| `user_data` | String | New unique transaction ID. |
| `sign` | String | Request signature (prefix `init_payment`). |


### Signature (`sign`)


```text
MD5(init_payment + <params_excluding_sign_in_alphabetical_order_joined_with_&> + <API_KEY>)
```

### Verify signature (recurring debit)

## Request examples

Node.js

```javascript
const crypto = require("crypto");
const axios = require("axios");

// 1. Инициация подписки через форму (первичная привязка)
async function setupSberpaySubscriptionForm(apiKey, params) {
  const sortedKeys = Object.keys(params).sort();
  const queryString = sortedKeys.map((k) => `${k}=${params[k]}`).join("&");

  const baseString = `init_form${queryString}${apiKey}`;
  params.sign = crypto.createHash("md5").update(baseString).digest("hex");

  const response = await axios.post(
    "https://api.1payment.com/init_form",
    params,
  );
  return response.data; // поле url — ссылка на форму
}

// 2. Инициация подписки через GATE
async function setupSberpaySubscriptionGate(apiKey, params) {
  const sortedKeys = Object.keys(params).sort();
  const queryString = sortedKeys.map((k) => `${k}=${params[k]}`).join("&");

  const baseString = `init_payment${queryString}${apiKey}`;
  params.sign = crypto.createHash("md5").update(baseString).digest("hex");

  const response = await axios.post(
    "https://api.1payment.com/init_payment",
    params,
  );
  return response.data; // redirect_url, deep_link
}

// 3. Рекуррентное списание (по токену)
async function chargeSberpayByToken(apiKey, params) {
  const sortedKeys = Object.keys(params).sort();
  const queryString = sortedKeys.map((k) => `${k}=${params[k]}`).join("&");

  const baseString = `init_payment${queryString}${apiKey}`;
  params.sign = crypto.createHash("md5").update(baseString).digest("hex");

  const response = await axios.post(
    "https://api.1payment.com/init_payment",
    params,
  );
  return response.data;
}

const secretKey = process.env.ONEPAYMENT_API_KEY;

// Пример: привязка через форму
const setupFormData = {
  partner_id: 1234,
  project_id: 5678,
  amount: "50.00",
  subscribe: 1,
  payment_type: "sberpay",
  user_data: "sberpay_setup_777",
  shop_url: "test.com",
};
// setupSberpaySubscriptionForm(secretKey, setupFormData).then(console.log);

// Пример: привязка через GATE
const setupGateData = {
  partner_id: 1234,
  project_id: 5678,
  amount: "50.00",
  subscribe: 1,
  payment_type: "sberpay",
  sberpay_type: "app2app",
  user_data: "sberpay_setup_777",
};
// setupSberpaySubscriptionGate(secretKey, setupGateData).then(console.log);

// Пример: списание
const recurringData = {
  partner_id: 1234,
  payment_type: "sberpay",
  project_id: 5678,
  token: "sberpay_t_1a2b3c",
  amount: "500.00",
  user_data: "sberpay_order_888",
};
chargeSberpayByToken(secretKey, recurringData).then(console.log);
```

Python

```python
import hashlib
import os
import requests

def charge_sberpay_by_token(api_key: str, params: dict) -> dict:
    # 1. Сортировка параметров
    sorted_keys = sorted(params.keys())
    query_string = "&".join(f"{k}={params[k]}" for k in sorted_keys)

    # 2. Подпись init_payment
    base_string = f"init_payment{query_string}{api_key}"
    params["sign"] = hashlib.md5(base_string.encode("utf-8")).hexdigest()

    # 3. POST-запрос (рекуррент)
    response = requests.post("https://api.1payment.com/init_payment", data=params)
    response.raise_for_status()
    return response.json()

api_key = os.environ["ONEPAYMENT_API_KEY"]
data = {
    "partner_id": 1234,
    "payment_type": "sberpay",
    "project_id": 5678,
    "token": "sberpay_t_1a2b3c",
    "amount": "500.00",
    "user_data": "sberpay_order_888",
}
print(charge_sberpay_by_token(api_key, data))
```

PHP

```php
<?php

function chargeSberpayByToken(string $apiKey, array $params): string
{
    // 1. Сортировка параметров по алфавиту
    ksort($params, SORT_LOCALE_STRING);
    $tail = '';
    foreach ($params as $k => $v) {
        if ($k === 'sign') {
            continue;
        }
        $tail .= "{$k}={$v}&";
    }
    $tail = substr($tail, 0, -1);

    // 2. Формирование подписи (префикс init_payment)
    $params['sign'] = md5('init_payment' . $tail . $apiKey);

    // 3. Запрос к API
    $ch = curl_init('https://api.1payment.com/init_payment');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

// Пример данных запроса
$apiKey = getenv('ONEPAYMENT_API_KEY');
$data = [
    'partner_id' => 1234,
    'payment_type' => 'sberpay',
    'project_id' => 5678,
    'token' => 'sberpay_t_1a2b3c',
    'amount' => '500.00',
    'user_data' => 'sberpay_order_888',
];

echo chargeSberpayByToken($apiKey, $data);
```

cURL

```bash
# Рекуррент: sign = md5("init_payment" + amount=500.00&partner_id=1234&payment_type=sberpay&project_id=5678&token=...&user_data=... + API_KEY)
curl -sS -X POST "https://api.1payment.com/init_payment" \
  -d "partner_id=1234&payment_type=sberpay&project_id=5678&token=sberpay_t_1a2b3c&amount=500.00&user_data=sberpay_order_888&sign=PASTE_MD5_HEX"
```

## API response

On successful **recurring** request (`200`):


```json
{
  "order_id": "8p3brmb19gfg0sg8gcwhws8kgc748s87",
  "status": 2,
  "status_description": "PENDING"
}
```

For **registration via form**, the response includes `url` (see [Create payment via form](/en/pages/sberpay/init-form)); via GATE — `redirect_url` and `deep_link` (see [Create payment via host2host (GATE)](/en/pages/sberpay/host2host)).

Request error (`400`):


```json
{
  "error_code": 2
}
```

## Status notifications (callbacks)

On successful linking or debit, the system sends a **POST** request in JSON format to your `notify_url`.

| Parameter | Type | Req. | Description |
|  --- | --- | --- | --- |
| `payment_type` | String | Yes | Payment type (`sberpay`). |
| `order_id` | String | Yes | Payment ID in the 1Payment system. |
| `project_id` | Integer | Yes | Your project ID. |
| `status` | Integer | Yes | State: `2` (pending), `3` (success), `4` (declined). |
| `status_description` | String | Yes | `PENDING`, `SUCCESS`, or `FAILURE`. |
| `init_time` | String | Yes | Payment creation time. |
| `status_time` | String | Yes | Time the final status was received. |
| `merchant_price` | Number | Yes | Payment amount. |
| `user_price` | Number | Yes | Partner payout amount. |
| `currency` | String | Yes | Currency (ISO 4217). |
| `account` | String | Yes | Technical marker (`sberpay`). |
| `user_data` | String | Yes | Your transaction ID passed at creation. |
| `sign` | String | Yes | Callback signature. |
| `token` | String | No | Token for subsequent debits — **save** when linking. |
| `test` | Integer | No | `1` for test transactions. |
| `status_code` | String | No | Decline reason code. |


**Important:** your server must return **HTTP 200 OK**. Otherwise the system retries the callback **once per minute for 10 minutes**.

**Callback signature verification:** MD5 of parameters in alphabetical order joined with `&` + `API_KEY` (**without** the `init_payment` prefix). See [API request format](/en/pages/init-request#%D0%BA%D0%BE%D0%BB%D0%B1%D0%B5%D0%BA%D0%B8-%D1%83%D0%B2%D0%B5%D0%B4%D0%BE%D0%BC%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F) for details.

You can also obtain the subscription token via [payment status request](/en/pages/sberpay/status) — the `token` field in the API response.

## Related sections

- [Create payment via form](/en/pages/sberpay/init-form)
- [Create payment via host2host (GATE)](/en/pages/sberpay/host2host)
- [Payment statuses](/en/pages/sberpay/status)
- [Payment refunds](/en/pages/sberpay/refund)
- [Transaction statuses](/en/pages/transaction-statuses)
- [Error codes (API)](/en/pages/error-codes-api)
- [Error codes (declines)](/en/pages/decline-error-codes)