Setup SIP trunks between Asterisk Servers using PJSIP

I’ve been troubleshooting a Voice over IP (VoIP) issue at work, so I thought it would be a good time to try my hand at setting up a couple of Asterisk servers and linking them with SIP trunks.

Asterisk 16 now uses the PJSIP module by default and while I found plenty of examples of how to set up a trunk to a VoIP provider using PJSIP, there was nothing on how to configure the other end.

Finally after two days I figured it out, and hopefully to save others from the pain, I ‘ve documented the configuration below.

;
; Server A - pjsip.conf
;

[siptrunk-auth]
type = auth
auth_type = userpass
username = <USER>
password = <ASTRONGPASSWORD>

[siptrunk-aor]
type = aor
contact = sip:serverB.domain.tld

[siptrunk]
type = endpoint
context = from-serverB
allow = !all,g722,ulaw
outbound_auth = siptrunk-auth
aors = siptrunk-aor
direct_media = no

[siptrunk-registration]
type = registration
outbound_auth = siptrunk-auth
server_uri = sip:serverB.domain.tld
client_uri = sip:<USER>@serverB.domain.tld
retry_interval = 60

[siptrunk-identify]
type = identify
match = serverB.domain.tld
endpoint = siptrunk

;
; ServerB - pjsip.conf
;

[<USER>] ;
type = auth
auth_type = userpass
username = <USER>
password = <ASTRONGPASSWORD>

[<USER>]
type = aor
max_contacts = 1

[<USER>]
type = endpoint
context = from-ServerA
allow = !all,ulaw
direct_media = no
auth = <USER>
aors = <USER>

[<USER>]
type = identity
match = ServerA.domain.tld ; sometimes you might need to use the actuall IP Address
endpoint = <USER>

;
; ServerA - extensions.conf
;

[to-serverB]
; route extensions starting with 6XXX to Server B
exten => _6XXX,1,Dial(PJSIP/${EXTEN}@siptrunk,,25)
  same => n,Hangup()

;
; ServerB - extensions.conf
;

[to-serverA]
; route extensions starting with 7XXX to Server A
exten => _7XXX,1,Dial(PJSIP/${EXTEN}@<USER>,,25)
  same => n,Hangup()