Howwise RSS
VoIP & Phone Systems9 min read

Asterisk to 3CX SIP Trunk: Route Calls by Caller Lookup

Short answer

An Asterisk to 3CX SIP trunk is an IP-based generic trunk in 3CX plus a PJSIP endpoint in Asterisk. To route by caller lookup, Dial a different DID per outcome, because 3CX inbound rules match the called number, not custom headers.

Key takeaways
  • Use one 3CX DID (or extension) per lookup outcome, because 3CX inbound rules route on the called number and not on arbitrary SIP headers.
  • Define the 3CX trunk in Asterisk with an endpoint, an aor with a static contact, and an identify section matching 3CX's IP, with direct_media=no and allow=ulaw,alaw.
  • Cap the lookup with CURLOPT(httptimeout)=2 and always set a default DID so a failed or slow API never drops or stalls the call.
  • Most 3CX failures are visible in the SIP trace: a 403 or 401 means the source IP or auth is wrong, and a 404 or 488 means the DID or codec does not match.
  • Keep the trunk locked to the peer IP, cap channels with GROUP_COUNT, and make sure 3CX never routes a DID back to Asterisk, or the two PBXs will loop.

What is the best way to connect Asterisk to a 3CX SIP trunk and route by lookup?

Run the lookup in the Asterisk dialplan (AGI, CURL(), func_odbc or AstDB), then Dial() a different number on the 3CX trunk for each outcome. For example, a VIP caller goes to DID 7001001 (a queue), a known customer to 7001002 (an extension), and an unknown caller or a failed lookup to 7001000 (the IVR).

3CX treats the Asterisk box as a SIP provider. Its inbound rules match on the called number, so each DID can point to a queue, extension, IVR or digital receptionist with no extra logic on the 3CX side. The decision lives in one place (Asterisk) and 3CX only does what it does best.

The rest of this page covers the trunk on both sides, the dialplan, why headers are a poor carrier, workarounds, and a test and troubleshooting checklist.

How do I set up the trunk on the 3CX side?

In the 3CX Management Console, add a trunk and choose a generic SIP trunk (Generic VoIP Provider). Menu names shift a little between versions, but the settings below are what matter.

  1. Choose IP-based authentication (no registration) and enter the Asterisk server's IP as the host. Registration-based works too, but a static IP match is simpler between two PBXs you control.
  2. Set Simultaneous Calls to the number you are licensed and sized for. 3CX enforces its own license limit, and this trunk counts against it.
  3. Add the DID range or the individual numbers you will dial from Asterisk (for example 7001000 to 7001003). Digits must match exactly what Asterisk sends in the Request-URI.
  4. Create an inbound rule for each DID and point it at the queue, extension or IVR. Add a rule for the default DID first.
  5. Check the trunk's source identification and caller ID options. If 3CX is set to replace or override caller ID with a trunk-level number, your lookup-aware caller ID will be lost.
  6. Allow the Asterisk IP in the 3CX firewall or in any front SBC, and allow UDP 5060 (or your TLS port) plus the RTP range.
Tip: Make every DID unique across all trunks in 3CX. If two trunks claim the same number, 3CX picks one and the other call path silently breaks.

Asterisk side: ready-to-paste PJSIP trunk and dialplan

This config assumes 3CX at 192.0.2.20 and Asterisk at 192.0.2.10 on the same routed network. Replace the addresses and add a pjsip.conf transport only once. On FreePBX, create the same thing as a custom trunk or put it in pjsip_custom.conf.

direct_media=no keeps RTP flowing through Asterisk so both sides never try to negotiate a path they cannot reach. rtp_symmetric and force_rport help when NAT is involved. If Asterisk sits behind NAT, also set external_media_address, external_signaling_address and local_net on the transport.

; pjsip.conf
[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0:5060

[3cx-trunk]
type=endpoint
transport=transport-udp
context=from-3cx
aors=3cx-trunk
disallow=all
allow=ulaw,alaw
direct_media=no
rtp_symmetric=yes
force_rport=yes
rewrite_contact=yes
dtmf_mode=rfc4733

[3cx-trunk]
type=aor
contact=sip:192.0.2.20:5060
qualify_frequency=60
max_contacts=1

[3cx-trunk]
type=identify
endpoint=3cx-trunk
match=192.0.2.20
Warning: Do not leave the from-3cx context pointing at an outbound-capable context. Anything 3CX sends in would be able to dial out through your carrier trunks, which is a classic toll fraud path.

How do I map a caller lookup result to a 3CX DID in the dialplan?

Do the lookup with a short timeout, sanitize the result, translate it to a DID through a small map, and fall back to a default. The map can be AstDB (shown here), a func_odbc function, or a GotoIf chain. A map is easier to change than hard-coded branches.

Seed the map once from the CLI, for example: database put lookupmap vip 7001001, database put lookupmap customer 7001002, database put lookupmap default 7001000.

; extensions.conf
[route-to-3cx]
exten => _X.,1,NoOp(Lookup for ${CALLERID(num)})
 same => n,Set(GROUP()=to3cx)
 same => n,GotoIf($[${GROUP_COUNT(to3cx)}>20]?busy)
 same => n,Set(CURLOPT(conntimeout)=1)
 same => n,Set(CURLOPT(httptimeout)=2)
 same => n,Set(RAW=${CURL(https://crm.example.com/lookup?num=${URIENCODE(${CALLERID(num)})})})
 same => n,Set(RESULT=${FILTER(a-z0-9_,${TOLOWER(${RAW})})})
 same => n,Set(DEST=${DB(lookupmap/${RESULT})})
 same => n,ExecIf($["${DEST}"=""]?Set(DEST=${DB(lookupmap/default)}))
 same => n,NoOp(result=${RESULT} dest=${DEST})
 same => n,Dial(PJSIP/${DEST}@3cx-trunk,60)
 same => n,Hangup()
 same => n(busy),Busy()

[from-3cx]
; only accept calls you expect, never route back to 3cx
exten => _X.,1,Hangup()
Tip: An empty or error body from CURL() produces an empty RESULT, so the DB lookup returns nothing and the default DID is used. Timeouts behave the same way, which is why the fallback must always exist. If you use an AGI script instead, give it its own timeout and set the channel variable even on failure.

Can I pass the lookup result in a SIP header instead?

You can send it, but 3CX will not route on it. 3CX inbound rules key on the DID (called number) and optionally the caller ID mask; there is no rule condition for an arbitrary X- header. A header is useful only if something downstream, such as a session border controller or your own logging, reads it.

A header set on the calling channel is not automatically copied to the outbound leg. Use a pre-dial handler so it lands on the channel that is actually being created:

Carrier of the resultCan 3CX route on it?Notes
Different DID per outcomeYes, via inbound rulesMost robust. Visible in the SIP trace and easy to test.
Different extension number on the trunkYes, if the number is a DID on the trunkWorks the same as DID; keep numbers within the trunk's DID range.
Caller ID prefix or display name tagOnly through caller ID mask rules or Call Flow Designer logicChanges what agents see and can corrupt CRM matching; use only if needed.
Custom header such as X-LookupNoPassed through but ignored for routing; may be dropped by SBCs.
P-Asserted-Identity, Diversion, History-InfoPartly, as identity or diverted-number infoIntended for identity and redirection, not for carrying arbitrary tags.
exten => _X.,n,Dial(PJSIP/${DEST}@3cx-trunk,60,b(add-hdr^s^1(${RESULT})))

[add-hdr]
exten => s,1,Set(PJSIP_HEADER(add,X-Lookup)=${ARG1})
 same => n,Return()

What can I do when only one DID is possible?

Sometimes the 3CX trunk or provider contract gives you a single number. Then you need to carry the outcome in something 3CX can read, and every option has a cost.

The cleanest alternative is a caller ID or display name tag, for example prefixing the display name with VIP. Then use 3CX caller ID mask rules or a Call Flow Designer script to branch on it. The downside is that tagging can leak into CRM records and reports.

Another option is to move the lookup to the 3CX side, using its CRM integration or an API call from Call Flow Designer. This removes the tag but adds latency inside 3CX and splits the logic across two systems. Keep a timeout there as well.

If the number of outcomes is large, ask whether the 3CX DID range can be extended instead. A block of 10 or 100 internal DIDs is usually cheaper than building tag parsing.

Why does the call fail, drop or have one-way audio?

Most problems show up in the first INVITE and its response. Turn on logging in Asterisk and in 3CX before you place test calls, then match the symptom to the table.

In Asterisk run pjsip set logger on and, ideally, sngrep to see the dialog as a ladder. In 3CX, enable the SIP trace for the trunk in the log/diagnostics view. For audio, use rtp set debug on and confirm packets flow in both directions.

SymptomLikely causeFix
403 Forbidden or 401 Unauthorized from 3CXSource IP not allowed, or trunk expects registration or authSet IP-based auth in 3CX with the exact Asterisk IP; check firewall and any SBC
404 Not Found, or 3CX hangs up with no ruleDialed DID is not in the trunk's DID list or no inbound rule matchesAdd the DID and an inbound rule; verify digits in the Request-URI
488 Not Acceptable HereCodec mismatchUse allow=ulaw,alaw on both sides and disable video or other codecs
503 Service UnavailableTrunk channel limit or license limit reachedRaise simultaneous calls on the trunk and check licensing
Rings but one-way audioNAT, wrong media address, SIP ALG, or direct_media ondirect_media=no, rtp_symmetric=yes, set external_media_address, disable SIP ALG, open RTP range
Wrong caller ID at the agent3CX trunk replaces or overrides caller IDCheck trunk outbound/inbound caller ID options and the PAI/From handling
Call loops or channels climb3CX routes a DID back to AsteriskRemove the return route; use GROUP_COUNT and a catch-all hangup in from-3cx

How do I test it and keep it secure?

Test every branch, including failure, before cutover. Each test should produce a clear result in a log you can point to.

  1. Run pjsip show endpoints and pjsip show aors and confirm 3cx-trunk is reachable (qualify shows Avail).
  2. Run pjsip set logger on, then place a call for each lookup outcome. Confirm the INVITE Request-URI shows the expected DID.
  3. Place a call with the lookup API blocked or pointed at a dead host. It should wait about 2 seconds and then go to the default DID.
  4. Run core show channels during the call and confirm one PJSIP channel to 3cx-trunk appears, then clears on hangup.
  5. Check the 3CX trace and agent screen to confirm the call reached the intended queue, extension or IVR and that the original caller ID is intact.
  6. Hold a call for two minutes and talk both ways to catch NAT timeouts and one-way RTP.
Warning: Do not expose UDP 5060 to the internet for this link. Restrict it by firewall to the peer IP, and use TLS and SRTP if traffic crosses an untrusted network. Also cap simultaneous calls with GROUP_COUNT so a loop or flood cannot exhaust channels.

Common questions

Should I use a register-based or IP-based trunk between Asterisk and 3CX?

IP-based is simpler and more reliable when both PBXs have static addresses, since there is no registration to expire. Use registration only when one side is behind a changing IP, and then protect it with strong credentials.

Can I use an AGI script instead of CURL() for the caller lookup?

Yes. An AGI script can query a database or API, set a channel variable such as DEST, and return, after which the dialplan dials PJSIP/${DEST}@3cx-trunk. Give the script its own timeout and a default value so a hung lookup never blocks the call.

Why does 3CX show the wrong caller ID after the call arrives?

The 3CX trunk may be configured to override or normalize inbound caller ID, or to prefer a header such as P-Asserted-Identity over From. Check the trunk's caller ID options and send the number in the format 3CX expects, consistently across all test calls.

How many calls can the trunk carry?

The limit is the lower of the 3CX trunk's simultaneous calls setting, your 3CX license, and your network bandwidth. A G.711 call uses roughly 87 kbps each way on Ethernet with 20 ms packets, so size the link accordingly.

When should I involve a 3CX partner or vendor?

Ask for help when license or simultaneous call limits are unclear, when an SBC is required, or when multi-tenant routing makes DID planning complicated. A partner can confirm what the license allows before you build around it.

Related topics:asterisk3cxsip trunkpjsipcall routing