# Изменение параметров при click-to-call

Инициализация звонка из CRM может не сработать по следующим причинам:

* Телефонный номер в CRM начинается с символа "+";
* На Asterisk настроен особый набор номера – например, звонить можно только через 9.

Логика такой доработки будет следующая: будем получать последние 10 символов (для России) и прибавлять к полученному результату нужный префикс. В примере префиксом будет цифра 8.

{% hint style="info" %}
Кастомизация настраивается в файле **process\_originate\_params.php,** он находится в каталоге:
{% endhint %}

|          itgrix\_bx (Битрикс24)         |           itgrix\_amo (amoCRM)           |
| :-------------------------------------: | :--------------------------------------: |
| **/opt/itgrix\_bx/customizer/actions/** | **/opt/itgrix\_amo/customizer/actions/** |

{% hint style="info" %}
Для более ранних версий:
{% endhint %}

| itgrix\_bx (Битрикс24) ДО версии 3.4.0 | itgrix\_amo (amoCRM) ДО версии 2.6.0 |
| :------------------------------------: | :----------------------------------: |
|       **/opt/itgrix\_bx/custom/**      |     **/opt/itgrix\_amo/custom/**     |

### Параметры

**Вход:**

```javascript
{
  "params": {
    "caller_id": “<caller_id>”,
    "channel": “<channel>”,
    "context": “<context>”,
    "extension": “<extension>”,
    "priority": “<priority>”,
    "request_data": “<request_data>”
  }
}
```

**Вернуть:**

```javascript
{
  "data": {
    "caller_id": “<caller_id>”,
    "channel": “<channel>”,
    "context": “<context>”,
    "extension": “<extension>”,
    "priority": “<priority>”
  }
}
```

Параметр `request_data` содержит все данные запроса от CRM. Он будет удалён перед выполнением Originate.\
Пример содержимого `request_data` при запросе от Bitrix24:

```json
{
  "action": "make_call",
  "auth": {
    "access_token": "0000000001111111111111122222222222333333334444444444445555555",
    "application_token": "aaaaaaaabbbbbbbbbbbccccccccddddddddddd",
    "client_endpoint": "https:\/\/example.bitrix24.ru\/rest\/",
    "domain": "example.bitrix24.ru",
    "expires": "1645749061",
    "expires_in": "3600",
    "member_id": "eeeeeeffffffffffgggggggggg",
    "scope": "crm,entity,user,telephony,im,task,call,department,imopenlines",
    "server_endpoint": "https:\/\/oauth.bitrix.info\/rest\/",
    "status": "L",
    "user_id": "1"
  },
  "code": "0",
  "data": {
    "CALL_ID": "externalCall.abcdefg123456789.1645744511",
    "CALL_LIST_ID": "0",
    "CRM_ENTITY_ID": "12345",
    "CRM_ENTITY_TYPE": "LEAD",
    "EXTENSION": "111",
    "IS_MOBILE": "0",
    "LINE_NUMBER": "",
    "PHONE_NUMBER": "89120000000",
    "PHONE_NUMBER_INTERNATIONAL": "+79120000000",
    "USER_ID": "1"
  },
  "event": "ONEXTERNALCALLSTART",
  "portal": "example.bitrix24.ru",
  "ts": "1645745461"
}
```

Пример содержимого `request_data` при запросе от amoCRM:

```json
{
  "action": "make_call",
  "code": "0",
  "data": {
    "id": "12345678",
    "type": "contact"
  },
  "phone": "89120000000",
  "portal": "itgro.amocrm.ru",
  "target": "https://apix.itgrix.ru:9004/v1/amo/make_call",
  "user_id": "1"
}
```

К возвращаемому массиву данных `"data"` можно добавить переменные `"codecs"` и `"variables"`:

```javascript
    "codecs": “<codecs>”,
    "variable": “<variable>”,
```

### Добавлем префикс

```php
//имена параметров как в конфиге
$phone = &$params['extension'];

//Получаем в $match последние 10 цифр номера
if(preg_match('~(\d{10})$~', $phone, $match)){
    //Добавляем к найденому префикс
    $phone = '8' . $match[1];
}

return array(
    'state' => 'success',
    'data' => $params
);
```

### Разные контексты

Бывает, появляется необходимость звонить через разные контексты. В примере звонки с номеров 161, 162, 163 пойдут через контекст *custom-context-1*; а с номеров 141, 140 через контекст *custom-context-2*; остальные звонки пойдут через стандартный контекст, указанный в настройках.

```php
//имена параметров как в конфиге
$phone = &$params['extension'];
$channel = explode('/', $params['channel']);

$contexts = array(
    'custom-context-1' => array(161, 162, 163),
    'custom-context-2' => array(141, 140),
);

foreach($contexts as $context => $phones){
    if(in_array($channel[1], $phones)){
        $params['context'] = $context;
        break;
    }
}

return array(
    'state' => 'success',
    'data' => $params
);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.itgrix.ru/custom_common/c2c.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
