DEV Community

Cover image for Asterisk CRM Integration: Screen Pops, Click-to-Dial, Logs
Muhammad Ali Mughal
Muhammad Ali Mughal

Posted on

Asterisk CRM Integration: Screen Pops, Click-to-Dial, Logs

Most companies that run Asterisk or FreePBX end up with two systems that do not talk: the phone system knows who called, and the CRM knows who the customer is. Agents bridge the gap by hand, typing numbers into search boxes and pasting notes after the call. A good Asterisk CRM integration removes that work with three features: a screen pop when the phone rings, click-to-dial from the contact record, and call logs with recordings attached to the right customer.

I run Loop Origin, where we build VoIP and PBX integrations for businesses. I wrote this with help from AI tools and checked every config and code sample myself. This is the architecture I use, with the trade-offs and failure modes that show up in production.

How do you integrate Asterisk with a CRM?

Direct answer: Connect a small bridge service to the Asterisk Manager Interface (AMI). It listens for ringing and answer events, looks up the caller in the CRM and pushes a screen pop to the agent's browser. The CRM sends click-to-dial requests back through an AMI Originate action, and a scheduled job syncs CDR rows and recording files into call logs.

The architecture in one picture

 Asterisk / FreePBX ──AMI (127.0.0.1:5038)──> PBX bridge (Node)
        ^                                         │  HTTPS + token
        │ Originate                               v
        └──────────── Laravel CRM <──── CDR sync job (cron)
                          │
                          └─ WebSocket (Reverb / Pusher) ─> agent browser: screen pop
Enter fullscreen mode Exit fullscreen mode

The bridge is deliberately boring: one process, one AMI connection, no business logic. The CRM owns contact lookup, permissions and the call log. That split means you can restart or replace either side without touching the other.

AMI, ARI, CDR polling or a vendor connector?

Approach Best for Strengths Weaknesses
AMI events + Originate Screen pops and click-to-dial on an existing dialplan Observes calls without taking control; mature and well documented Text protocol; you must handle reconnects and event volume
ARI (Stasis apps) Building custom call flows in code Full control of channels, bridges and media from your app Calls must enter your Stasis app; more to build and operate
CDR / CEL polling only Call history and reporting Simple; no live connection No live screen pop; minutes of delay
Vendor CRM connector module Standard CRMs with an existing module Fast to switch on Limited to what the module supports; another licence or dependency

For most teams I start with AMI for live events and CDR sync for history. ARI is the right tool when you are replacing dialplan logic, not when you only want to watch it.

Step 1: a locked-down AMI user

On FreePBX, put custom AMI users in manager_custom.conf so the GUI does not overwrite them. On plain Asterisk, use manager.conf.

; /etc/asterisk/manager_custom.conf
[crm-bridge]
secret = use-a-long-random-value-from-your-secret-store
deny = 0.0.0.0/0.0.0.0
permit = 127.0.0.1/255.255.255.255
read = call,agent
write = originate
Enter fullscreen mode Exit fullscreen mode

Keep AMI bound to localhost or a private VPN interface. Port 5038 should never be reachable from the internet. Give this user only the classes it needs: call and agent events to read, originate to write. Reload with asterisk -rx "manager reload".

Step 2: the bridge listens for ringing

AMI is a plain text protocol: key-value lines, with a blank line ending each message. A minimal Node listener needs no library:

import net from "node:net";

function connect() {
  const sock = net.connect(5038, "127.0.0.1");
  let buf = "";
  sock.on("connect", () => sock.write(
    "Action: Login\r\nUsername: crm-bridge\r\n" +
    `Secret: ${process.env.AMI_SECRET}\r\nEvents: call,agent\r\n\r\n`));
  sock.on("data", (chunk) => {
    buf += chunk.toString();
    let i;
    while ((i = buf.indexOf("\r\n\r\n")) !== -1) {
      const raw = buf.slice(0, i); buf = buf.slice(i + 4);
      const msg = Object.fromEntries(raw.split("\r\n").map((l) => {
        const k = l.indexOf(":"); return [l.slice(0, k), l.slice(k + 1).trim()];
      }));
      if (msg.Event === "DialBegin") onRing(msg).catch(console.error);
    }
  });
  sock.on("close", () => setTimeout(connect, 3000)); // reconnect with a pause
  sock.on("error", () => sock.destroy());
}

async function onRing(e) {
  const ext = /^PJSIP\/(\d+)-/.exec(e.DestChannel || "")?.[1];
  if (!ext) return;
  await fetch(process.env.CRM_URL + "/api/pbx/ring", {
    method: "POST",
    headers: { "Content-Type": "application/json",
               Authorization: `Bearer ${process.env.BRIDGE_TOKEN}` },
    body: JSON.stringify({ ext, caller: e.CallerIDNum, linkedid: e.Linkedid }),
  });
}
connect();
Enter fullscreen mode Exit fullscreen mode

DialBegin fires when a specific extension starts ringing, so the pop reaches the right desk. For queues that ring many agents at once, you may prefer to pop on AgentConnect (the agent answered) and only show a small "incoming" toast on ring.

Rows of server racks in a blue-lit data center
Image: AI-generated.

Step 3: the CRM looks up the caller and pushes the pop

// routes/api.php -> PbxController@ring
public function ring(Request $request)
{
    abort_unless(hash_equals(config('pbx.bridge_token'), (string) $request->bearerToken()), 401);

    $phone = $this->phones->toE164($request->input('caller')); // your libphonenumber wrapper
    $contacts = Contact::where('phone_e164', $phone)->limit(3)->get(['id', 'name', 'company_id']);

    CallLog::firstOrCreate(
        ['linkedid' => $request->input('linkedid')],
        ['direction' => 'inbound', 'from_e164' => $phone, 'extension' => $request->input('ext')]
    );

    broadcast(new IncomingCall($request->input('ext'), $phone, $contacts));
    return response()->noContent();
}
Enter fullscreen mode Exit fullscreen mode

Store every phone number in E.164 and normalize the incoming caller ID the same way. Caller ID arrives in whatever format your trunk sends: with or without a country code, with a leading zero, or with a trunk prefix. Without normalization the lookup quietly fails and agents decide the feature "does not work". When several contacts share a number (a company switchboard), show all matches and let the agent pick.

Step 4: click-to-dial with Originate

public function dial(string $ext, string $number, int $contactId): void
{
    // Block header injection: AMI messages are line-based.
    if (!preg_match('/^\d{2,6}$/', $ext) || !preg_match('/^\+?\d{6,15}$/', $number)) {
        throw new InvalidArgumentException('Invalid extension or number');
    }
    $fp = fsockopen('127.0.0.1', 5038, $errno, $errstr, 3);
    $secret = config('pbx.ami_secret');
    fwrite($fp, "Action: Login\r\nUsername: crm-bridge\r\nSecret: {$secret}\r\nEvents: off\r\n\r\n");
    fwrite($fp, "Action: Originate\r\nChannel: PJSIP/{$ext}\r\nContext: from-internal\r\n"
        . "Exten: {$number}\r\nPriority: 1\r\nAsync: true\r\n"
        . "Variable: CRM_CONTACT_ID={$contactId}\r\n\r\n");
    fwrite($fp, "Action: Logoff\r\n\r\n");
    fclose($fp);
}
Enter fullscreen mode Exit fullscreen mode

Originate rings the agent's own phone first, then dials the customer once the agent answers. Sending it into the normal outbound context (from-internal on FreePBX) means your existing outbound routes, caller ID rules and toll-fraud restrictions still apply. Never build a separate context that bypasses them. The strict validation matters: AMI is line-based, so an unvalidated number containing a newline could inject extra AMI headers.

Step 5: call logs and recordings

On FreePBX, finished calls land in the asteriskcdrdb.cdr table with fields such as calldate, src, dst, disposition, billsec, uniqueid, linkedid and recordingfile. A job every few minutes reads rows newer than its last cursor and updates the matching CallLog by linkedid, which also keeps transfers grouped as one conversation.

For recordings, do not copy audio files into the CRM database. Store the path, serve the file through an authenticated, short-lived download link, and apply the same retention rule the PBX uses. Check the call recording notice and consent rules for every country you call before you switch recording on.

Failure modes I plan for

  • AMI connection drops after a PBX reload. The bridge must reconnect on its own and log the gap.
  • Pops for the wrong person when shared or hunt-group extensions ring. Map extensions to users in the CRM, not in the bridge.
  • Missed pops in queues because the agent's phone rang through a Local channel. Test with your real queue strategy, not just direct extension calls.
  • Event volume on busy systems. Subscribe only to the classes you need and drop events you do not use as early as possible.
  • Clock and timezone drift between CDR times and CRM times. Store UTC everywhere and convert at display time.

Rollout checklist

  1. Dedicated AMI user, localhost or VPN only, minimum read and write classes.
  2. All CRM phone numbers migrated to E.164.
  3. Extension-to-user mapping table in the CRM.
  4. Bridge runs under a process manager with automatic restart and health logging.
  5. Screen pop tested on direct calls, ring groups, queues and transfers.
  6. Click-to-dial input validation and permission check per user.
  7. Originate uses the normal outbound context and routes.
  8. CDR sync with a cursor and idempotent upserts by linkedid.
  9. Recording access through expiring links, with retention and consent rules written down.
  10. A pilot with one team for a week before company-wide rollout.

If you are still choosing the phone system itself, start with Planning a VoIP Phone System for a Small Business. For the bigger contact-center picture, see VoIP, SIP Trunking & Custom WebRTC Contact Center Architecture.

FAQ

Should I use AMI or ARI for a CRM integration?
Use AMI when you only need to observe calls and originate new ones from an existing dialplan. Use ARI when your application should control the call flow itself.

Does this work with FreePBX, or only plain Asterisk?
Both. FreePBX runs Asterisk underneath; put custom AMI users in manager_custom.conf and dial through from-internal so your FreePBX routes still apply.

Is it safe to expose AMI to a cloud-hosted CRM?
Not directly. Run the bridge on or next to the PBX, keep AMI on localhost or a VPN, and let the bridge call the CRM over HTTPS with a token.

When should the screen pop appear: on ring or on answer?
On ring for direct extensions, so the agent can greet the caller by name. For queues ringing many agents, pop fully on answer to avoid noise.

How do I link transfers to a single call log?
Use Asterisk's linkedid, which stays the same across the channels of one conversation, as the key of the call log.

Can click-to-dial work with WebRTC softphones?
Yes. Originate to the agent's WebRTC endpoint the same way you would to a desk phone, as long as it is registered as a PJSIP endpoint.

Wrap-up

A CRM phone integration does not need a new phone system. It needs a small, well-secured bridge, clean phone numbers and a call log keyed the right way. If you want help designing one for your Asterisk or FreePBX setup, that is the kind of work we do at Loop Origin.

Which part breaks first in your setup: caller ID matching, queues or recordings?


Follow & Connect

Watch on YouTube: Resume Boost AI · PixelValut · Daily AI News By Ali

Top comments (0)