1C-Bitrix Integration with CoMagic
Calls disappear into nowhere, and managers keep asking for data again? CoMagic is one of the few call tracking platforms that stores not just the call source but the complete visitor touch chain. But without linking to 1C-Bitrix, this data remains in the CoMagic interface and doesn't affect business processes. We set up the integration so that every targeted call automatically creates a lead in CRM, and the card shows the entire history of website interactions.
Our experience with CoMagic-Bitrix integrations spans over 30 projects. A typical result is reducing lead processing time by 40% and lowering cost per lead by up to 30% due to precise attribution. We guarantee transparency and stable operation of the solution.
What Problems Does Integration Solve?
- Loss of call attribution. Without visitor_id, the manager doesn't see which channel the client came from. CoMagic Data API attaches all session data to the lead.
- Manual data entry. Calls don't automatically enter CRM — you have to enter them manually, taking up to 5 minutes per lead. Webhook reduces this process to seconds.
- Duplicate leads. The same number may call multiple times. We implement deduplication: if a lead with that number already exists, we update it instead of creating a copy.
How Does CoMagic Transfer Calls to CRM?
CoMagic uses two mechanisms: webhook and Data API. Webhook sends a POST request to your server when a call ends, and Data API lets you request complete session information by visitor_id at any time. We implement both — for instant lead creation and subsequent enrichment.
Webhook: Verification and Processing
CoMagic signs each webhook with HMAC-SHA256. We verify the signature and discard calls shorter than 10 seconds — they are almost always spam or misdials.
// /local/api/comagic-webhook.php
require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_before.php');
$data = json_decode(file_get_contents('php://input'), true);
$signature = $_SERVER['HTTP_X_COMAGIC_SIGNATURE'] ?? '';
$secret = \Bitrix\Main\Config\Option::get('local.comagic', 'webhook_secret');
$expected = hash_hmac('sha256', file_get_contents('php://input'), $secret);
if (!hash_equals($expected, $signature)) {
http_response_code(403);
exit;
}
$event = $data['event_type'] ?? '';
if ($event === 'call_session_completed') {
$processor = new \Local\CoMagic\CallProcessor();
$processor->handle($data['call_session']);
}
http_response_code(200);
Call Processor: Creating a Lead
If the call is deemed targeted, we create a lead with UTM tags and CoMagic ID. If a lead with this number already exists, we update it to avoid duplicates.
namespace Local\CoMagic;
class CallProcessor
{
public function handle(array $session): void
{
if (($session['is_lost_call'] ?? false) && ($session['duration_total'] ?? 0) < 10) {
return;
}
$phone = $this->normalizePhone($session['visitor_phone_number'] ?? '');
if (!$phone) {
return;
}
$existingLeadId = $this->findRecentLead($phone);
$fields = [
'TITLE' => 'CoMagic Call: ' . $phone,
'PHONE' => [['VALUE' => $phone, 'VALUE_TYPE' => 'WORK']],
'SOURCE_ID' => 'CALL',
'STATUS_ID' => 'NEW',
'UF_COMAGIC_ID' => (string)($session['id'] ?? ''),
'UF_UTM_SOURCE' => $session['utm_source'] ?? '',
'UF_UTM_MEDIUM' => $session['utm_medium'] ?? '',
'UF_UTM_CAMPAIGN' => $session['utm_campaign'] ?? '',
'UF_UTM_CONTENT' => $session['utm_content'] ?? '',
'UF_UTM_TERM' => $session['utm_term'] ?? '',
'COMMENTS' => $this->buildComment($session),
];
$lead = new \CCrmLead(false);
if ($existingLeadId) {
$lead->Update($existingLeadId, $fields, true);
} else {
$lead->Add($fields, true);
}
}
private function buildComment(array $session): string
{
return implode("\n", [
'CoMagic Session ID: ' . ($session['id'] ?? ''),
'Operator: ' . ($session['employee_full_name'] ?? '—'),
'Duration: ' . ($session['duration_total'] ?? 0) . ' sec.',
'Traffic source: ' . ($session['traffic_type'] ?? '—'),
'Entry page: ' . ($session['site_domain_url'] ?? '—'),
'Tags: ' . implode(', ', $session['tags'] ?? []),
]);
}
}
What Does visitor_id Provide?
CoMagic writes a comagic_visitor cookie on the website. When a lead goes through the chain, we request the full session via Data API on the server and populate custom fields: number of sessions, first and last source. This allows the manager to see which channel the client came from, even if the call wasn't the first touch.
class VisitorEnricher
{
private ApiClient $api;
public function enrichLead(int $leadId, string $visitorId): void
{
try {
$result = $this->api->call('visitors.get_visitor_info', [
'visitor_id' => $visitorId,
'date_from' => date('Y-m-d', strtotime('-1 day')),
'date_till' => date('Y-m-d'),
]);
$visitor = $result['data'][0] ?? null;
if (!$visitor) {
return;
}
$updateFields = [
'UF_CM_VISITOR_ID' => $visitorId,
'UF_CM_SESSION_COUNT' => (int)($visitor['sessions_count'] ?? 0),
'UF_CM_FIRST_SOURCE' => $visitor['first_session']['utm_source'] ?? '',
'UF_CM_LAST_SOURCE' => $visitor['last_session']['utm_source'] ?? '',
];
$lead = new \CCrmLead(false);
$lead->Update($leadId, $updateFields, true);
} catch (\RuntimeException $e) {
\CEventLog::Add([
'SEVERITY' => 'WARNING',
'AUDIT_TYPE_ID' => 'COMAGIC_ENRICH_FAIL',
'MODULE_ID' => 'local.comagic',
'DESCRIPTION' => $e->getMessage(),
]);
}
}
}
Click-to-Call: Calling Directly from CRM
CoMagic SIP allows outbound calls via API. We add a "Call" button to the lead and deal cards. After clicking, the operator receives a call on their SIP line, and CoMagic connects them to the client.
public function initiateCall(int $leadId, string $operatorLogin): array
{
$lead = \CCrmLead::GetByID($leadId);
$phones = \CCrmFieldMulti::GetList(
[],
['ENTITY_ID' => 'LEAD', 'ELEMENT_ID' => $leadId, 'TYPE_ID' => 'PHONE']
);
$phoneRow = $phones->Fetch();
if (!$phoneRow) {
return ['success' => false, 'error' => 'No phone'];
}
$result = $this->api->call('calls.make_call', [
'virtual_phone_number' => \Bitrix\Main\Config\Option::get('local.comagic', 'virtual_number'),
'operator_login' => $operatorLogin,
'destination_number' => $phoneRow['VALUE'],
]);
return ['success' => true, 'call_id' => $result['data']['call_session_id'] ?? null];
}
CoMagic vs. Other Call Tracking Systems
CoMagic stands out from competitors with data depth. For example, Callibri considers a visit as one touch, while CoMagic breaks it into points (pages, channels) — providing multi-touch attribution "out of the box." Additionally, CoMagic API allows flexible call management: initiating calls, changing scripts, getting call recordings. According to CoMagic, implementing end-to-end analytics with their platform increases conversion to sale by up to 30%.
| Feature | CoMagic | Callibri | Alibra |
|---|---|---|---|
| Multi-touch attribution | Yes (built-in) | Only first touch | Only last touch |
| Webhook | Yes | Yes | Yes, but without HMAC |
| Data API | Full (sessions, calls, chats) | Limited | Limited |
| Click-to-call | Yes | Yes (via third-party API) | No |
| Call recording | Yes | Yes | Yes |
Custom Fields We Create
| Code | Entity | Type | Source |
|---|---|---|---|
| UF_COMAGIC_ID | Lead | string | Webhook |
| UF_CM_VISITOR_ID | Lead | string | Cookie |
| UF_CM_SESSION_COUNT | Lead | integer | Data API |
| UF_CM_FIRST_SOURCE | Lead | string | Data API |
| UF_CM_LAST_SOURCE | Lead | string | Data API |
| UF_UTM_SOURCE..TERM | Lead, Deal | string | Webhook / API |
What's Included in the Integration?
-
local.comagicmodule: API client, event processors, logger. - Webhook endpoint with HMAC signature verification.
- Creating/updating leads in CRM from calls and chats.
- JS form interception to pass visitor_id.
- Server-side enrichment with session data via Data API.
- Optional: click-to-call from CRM card and "CoMagic" dashboard.
- Documentation, admin training, 2 weeks of post-launch support.
Technical Implementation Details
CoMagic authentication uses JSON-RPC 2.0. The base ApiClient class is already tailored for Bitrix — it's in a separate namespace and uses \Bitrix\Main\Config\Option to store credentials. All external calls are logged in CEventLog.
namespace Local\CoMagic;
class ApiClient
{
private string $baseUrl = 'https://dataapi.comagic.ru/v2.0';
private ?string $accessToken = null;
private string $login;
private string $password;
public function __construct(string $login, string $password)
{
$this->login = $login;
$this->password = $password;
}
public function call(string $method, array $params = []): array
{
if (!$this->accessToken) {
$this->authenticate();
}
$payload = [
'jsonrpc' => '2.0',
'id' => uniqid('cm_', true),
'method' => $method,
'params' => array_merge(['access_token' => $this->accessToken], $params),
];
$ch = curl_init($this->baseUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_TIMEOUT => 10,
]);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
if (isset($response['error'])) {
throw new \RuntimeException('CoMagic API error: ' . $response['error']['message']);
}
return $response['result'] ?? [];
}
private function authenticate(): void
{
$payload = [
'jsonrpc' => '2.0',
'id' => 'auth',
'method' => 'login.user',
'params' => ['login' => $this->login, 'password' => $this->password],
];
$ch = curl_init($this->baseUrl);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);
$this->accessToken = $result['result']['data']['access_token']
?? throw new \RuntimeException('CoMagic auth failed');
}
}
Timeline and Pricing
Basic integration (webhook → lead + UTM) — 1–2 weeks. Full stitching with multi-touch attribution, click-to-call, and data showcase — 4–6 weeks. Pricing is calculated individually after auditing your CRM and traffic volumes. Contact us for an audit and project estimate within one business day.







