> ## Documentation Index
> Fetch the complete documentation index at: https://docs.meridian.vip/llms.txt
> Use this file to discover all available pages before exploring further.

# Ecom-платежи (карта)

<Info>
  **Ecom** — приём платежей через hosted-страницу оплаты картой. Клиент перенаправляется на защищённую страницу, где вводит данные карты. Выбор банка **не требуется**.
</Info>

## Создание платежа

```
POST https://api.meridian.vip/api/v1/ecom/payments
```

### Обязательные параметры

| Параметр            | Тип      | Описание                                                                   |
| ------------------- | -------- | -------------------------------------------------------------------------- |
| `amount`            | `number` | Сумма платежа в рублях                                                     |
| `currency`          | `string` | Код валюты. На данный момент есть поддержка `"RUB"`                        |
| `internalId`        | `string` | Уникальный идентификатор заказа в вашей системе для идемпотентности        |
| `customerEmail`     | `string` | Email клиента, необязательно настоящий. Строка должна быть в формате email |
| `notificationUrl`   | `string` | URL для webhook уведомлений по этому платежу                               |
| `notificationToken` | `string` | Секретный токен для подписи webhook уведомлений, мин длина 32 символа      |

***

## Пример запроса

<CodeGroup>
  ```javascript Node.js theme={null}
  const crypto = require('crypto');

  function calculateSignature(method, url, body, secret) {
    const stringToSign = method + url + (body || '');
    const hmac = crypto.createHmac('sha256', secret);
    hmac.update(stringToSign);
    return hmac.digest('base64');
  }

  const method = 'POST';
  const url = 'https://api.meridian.vip/api/v1/ecom/payments';
  const body = JSON.stringify({
    amount: 1000,
    currency: 'RUB',
    internalId: 'order-12345',
    customerEmail: 'customer@example.com',
    notificationUrl: 'https://your-site.com/webhooks/ecom',
    notificationToken: 'your-webhook-secret-token'
  });

  const apiKey = 'meridian_abc123...:meridian_xyz789...';
  const [keyId, secret] = apiKey.split(':');
  const signature = calculateSignature(method, url, body, secret);

  const response = await fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': apiKey,
      'X-Signature': signature
    },
    body
  });

  const result = await response.json();
  console.log(result);
  // result.paymentUrl — перенаправьте клиента на этот URL
  ```

  ```python Python theme={null}
  import hmac
  import hashlib
  import base64
  import requests
  import json

  def calculate_signature(method, url, body, secret):
      string_to_sign = method + url + (body or '')
      signature = hmac.new(
          secret.encode('utf-8'),
          string_to_sign.encode('utf-8'),
          hashlib.sha256
      ).digest()
      return base64.b64encode(signature).decode('utf-8')

  method = 'POST'
  url = 'https://api.meridian.vip/api/v1/ecom/payments'
  body = json.dumps({
      'amount': 1000,
      'currency': 'RUB',
      'internalId': 'order-12345',
      'customerEmail': 'customer@example.com',
      'notificationUrl': 'https://your-site.com/webhooks/ecom',
      'notificationToken': 'your-webhook-secret-token'
  })

  api_key = 'meridian_abc123...:meridian_xyz789...'
  key_id, secret = api_key.split(':')
  signature = calculate_signature(method, url, body, secret)

  response = requests.post(
      url,
      headers={
          'Content-Type': 'application/json',
          'X-API-Key': api_key,
          'X-Signature': signature
      },
      data=body
  )

  result = response.json()
  print(result)
  # result['paymentUrl'] — перенаправьте клиента на этот URL
  ```

  ```php PHP theme={null}
  <?php

  function calculateSignature($method, $url, $body, $secret) {
      $stringToSign = $method . $url . ($body ?? '');
      $signature = hash_hmac('sha256', $stringToSign, $secret, true);
      return base64_encode($signature);
  }

  $method = 'POST';
  $url = 'https://api.meridian.vip/api/v1/ecom/payments';
  $body = json_encode([
      'amount' => 1000,
      'currency' => 'RUB',
      'internalId' => 'order-12345',
      'customerEmail' => 'customer@example.com',
      'notificationUrl' => 'https://your-site.com/webhooks/ecom',
      'notificationToken' => 'your-webhook-secret-token'
  ]);

  $apiKey = 'meridian_abc123...:meridian_xyz789...';
  list($keyId, $secret) = explode(':', $apiKey);
  $signature = calculateSignature($method, $url, $body, $secret);

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Content-Type: application/json',
      'X-API-Key: ' . $apiKey,
      'X-Signature: ' . $signature
  ]);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $response = curl_exec($ch);
  curl_close($ch);

  $result = json_decode($response, true);
  print_r($result);
  // $result['paymentUrl'] — перенаправьте клиента на этот URL
  ?>
  ```
</CodeGroup>

***

## Пример ответа (успех)

**HTTP Status: 201 Created**

```json theme={null}
{
  "id": "cm3k8x7y80001z8j4k5m6n7o8",
  "status": "new",
  "amount": "1000",
  "currency": "RUB",
  "paymentUrl": "https://web.tele.store/pay/card?...",
  "dealRate": "95.50",
  "expireAt": "2025-11-03T15:10:00.000Z",
  "createdAt": "2025-11-03T15:00:00.000Z",
  "updatedAt": "2025-11-03T15:00:00.000Z",
  "internalId": "order-12345"
}
```

<Warning>
  **Важно**: Перенаправьте клиента на `paymentUrl` сразу после создания платежа. Ссылка имеет ограниченный срок действия (`expireAt`).
</Warning>

***

## Поля ответа

| Поле         | Тип      | Описание                                                             |
| ------------ | -------- | -------------------------------------------------------------------- |
| `id`         | `string` | Уникальный идентификатор платежа в системе Meridian                  |
| `status`     | `string` | Статус: `new`, `paid`, `expired`, `canceled`                         |
| `amount`     | `string` | Сумма платежа                                                        |
| `currency`   | `string` | Валюта (`RUB`)                                                       |
| `paymentUrl` | `string` | URL hosted-страницы оплаты картой. Перенаправьте клиента на этот URL |
| `dealRate`   | `string` | Курс сделки                                                          |
| `expireAt`   | `string` | Время истечения платежа. ISO 8601                                    |
| `createdAt`  | `string` | Время создания платежа. ISO 8601                                     |
| `updatedAt`  | `string` | Время последнего обновления. ISO 8601                                |
| `internalId` | `string` | Ваш идентификатор заказа                                             |

***

## Webhook-уведомления

Подробнее см. [Webhook-уведомления](/webhooks).

### Пример тела webhook для ecom-платежа

```json theme={null}
{
  "id": "cm3k8x7y80001z8j4k5m6n7o8",
  "amount": "1000.0000",
  "status": "paid",
  "currency": "RUB",
  "dealRate": "95.50",
  "expireAt": "2025-11-03T15:10:00.000Z",
  "createdAt": "2025-11-03T15:00:00.000Z",
  "direction": "in",
  "updatedAt": "2025-11-03T15:05:00.000Z",
  "paymentMethod": "ECOM",
  "internalId": "order-12345",
  "merchantName": "MerchantName"
}
```
