Skip to main content

Public API Reference

🧩 Public React Native API Reference​

This section documents the complete consumer-facing TypeScript API exported by react-native-pitel-voip-v2. Native Android/iOS implementation classes and the bundled PJSIP classes are internal and are not part of the public API.

Exports​

import {
PitelVoipClient,
getPitelCallErrorMessage,
type PitelSettings,
type PitelUIConfig,
type PitelRegistrationState,
type PitelCallEvent,
type PitelCallCause,
} from 'react-native-pitel-voip-v2';

PitelVoipClient​

PitelVoipClient is a singleton. Use PitelVoipClient.instance; its constructor is not public.

const client: PitelVoipClient = PitelVoipClient.instance;

Properties​

PropertyTypeDescription
isLoggedInbooleantrue after the native SIP stack reports a successful registration; otherwise false. A resolved login() call alone does not guarantee registration.
registrationStatePitelRegistrationStateCurrent cached registration state. Subscribe with addRegistrationListener() to receive changes.

Registration and session methods​

login(settings)​
login(settings: PitelSettings & { uiConfig?: PitelUIConfig }): Promise<void>

Starts native SIP account registration and saves the supplied settings for a later autoLogin(). The Promise confirms that the native login command was accepted; observe addRegistrationListener() to know when registration succeeds or fails.

ParameterTypeRequiredDefaultDescription
extensionstringYes—SIP extension/username.
passwordstringYes—SIP password.
domainstringYes—SIP registrar domain or host.
teamIdstringYes—Apple Developer Team ID used for iOS VoIP push routing (found in Apple Developer Portal -> Membership).
displayNamestringNoextensionDisplay name associated with the SIP account.
proxystringYes—Outbound SIP proxy (e.g., 'sip:proxy.vn:5061').
portstringNo'50061'SIP server port.
appMode'dev' | 'production'No'production''dev' for Debug mode (Apple Sandbox APNs); 'production' for TestFlight / App Store (Apple Production APNs).
userAgentstringNo'Pitel VoIP React Native'Custom User-Agent identifier for SIP registration and PBX API. Automatically sanitized (alphanumeric and spaces only, accents/special characters removed, max 30 chars).
uiConfigPitelUIConfigNoNative presetCustomizes the native call screen. See UI Customization.

Returns: Promise<void>.

Rejects when: the native module is unavailable, required settings are missing, or the native registration command cannot be started. Registration failure after the command starts is reported through the registration listener.

logout()​
logout(): Promise<void>

Unregisters the SIP account, changes the local state to notRegistered, disables future automatic login, and clears saved SDK credentials. Native logout errors are logged as warnings while local cleanup still completes.

autoLogin()​
autoLogin(): Promise<boolean>

Attempts login() using saved settings only when a previous successful registration enabled automatic login.

Returns: true when the saved login command was started successfully; false when automatic login is disabled, required saved settings are unavailable, or the attempt fails. A true result is not a final SIP registration result; continue observing registrationState.

getSavedCredentials()​
getSavedCredentials(): Promise<Partial<PitelSettings> | null>

Returns the locally saved login settings, or null when none are available or storage cannot be read. Treat the returned object as sensitive and do not log it.

refreshRegistrationState()​
refreshRegistrationState(): Promise<PitelRegistrationState>

Reads the native registration state, updates the client's cached state, and returns it. If the native state API is unavailable, the current cached state is returned.

Call-control methods​

NOTE

All in-call controls (Mute, Speaker, Hold, Keypad, Hangup) are already pre-wired into the native CallScreen UI. You do not need to call these methods directly unless triggering programmatic actions from outside the call screen.

MethodReturnsDescription
makeCall(to: string, callerName?: string)Promise<void>Starts an outgoing call. to may be an extension/number or a complete sip: URI. For a number, the SDK builds a SIP URI from the domain and port used at login. Rejects if the native module is unavailable, the account is not registered, or native call setup fails.
hangup()Promise<void>Ends the current call.
mute()Promise<void>Mutes the microphone for the current call.
unmute()Promise<void>Unmutes the microphone.
hold()Promise<void>Places the current call on hold.
unhold()Promise<void>Resumes a held call.
sendDTMF(dtmf: string)Promise<void>Sends DTMF input for the current call. Pass the digit or symbol expected by the remote system, for example '1', '*', or '#'.
transferCall(to: string)Promise<void>Transfers the current call to an extension, number, or destination accepted by the native SIP stack.

Call-control methods require the corresponding native call state (for example, an active call for mute, hold, DTMF, or transfer). Native failures reject their returned Promise. Methods other than makeCall() return a resolved Promise without action when the native module is unavailable.

Push-notification methods​

setFCMToken(token)​
setFCMToken(token: string): Promise<void>

Passes the current Firebase Cloud Messaging token to the native SDK. Call it again whenever Firebase refreshes the token. iOS incoming calls use PushKit configuration described in the iOS VoIP Push guide.

handlePushNotification(data)​
handlePushNotification(data: Record<string, string>): Promise<boolean>

Passes an FCM data payload to the native SDK.

Returns: whether the native SDK handled the payload. On iOS this handles silent CANCEL_ALL and CANCEL_GROUP messages used to dismiss an incoming CallKit call; incoming-call delivery itself still uses PushKit.

Permission methods​

hasRequiredPermissions()​
hasRequiredPermissions(): Promise<boolean>

Returns whether the native SDK currently has its required runtime permissions. Returns false when the native module is unavailable.

requestPermissions()​
requestPermissions(): Promise<boolean>

Requests the SDK's required runtime permissions and resolves to whether they were granted. Returns false when the native module is unavailable. Platform declarations and capabilities must still be configured as described in Platform Configuration.

Diagnostics​

getDiagnostics()​
getDiagnostics(): Promise<Record<string, unknown> | null>

Returns native diagnostic information on iOS. It returns null on Android or when the native diagnostics API is unavailable. Diagnostic object fields are intended for troubleshooting and are not a stable application data contract.

🪝 React Hooks​

usePitelCall(options?)​

import { usePitelCall } from 'react-native-pitel-voip-v2';

const {
isCallActive,
callState,
callParams,
makeCall,
hangup,
mute,
unmute,
hold,
unhold,
setAudioRoute,
toggleSpeaker,
sendDTMF,
dismissCall,
} = usePitelCall(options?: { enabled?: boolean });

A headless React hook for custom in-app call screen integrations. It automatically manages telephony state, cold-start launches from notifications or full-screen intents, iOS CallKit answering synchronization, and foreground/background AppState transitions. See the Custom Call Screen Integration Guide for full usage examples.

Listeners and callbacks​

addEventListener(listener)​

addEventListener(listener: (event: PitelCallEvent) => void): () => void

Subscribes to call, media-control, and audio-route events. It returns an unsubscribe function.

const unsubscribe = client.addEventListener((event) => {
console.log(event.type, event);
});

// Call during component cleanup.
unsubscribe();

addRegistrationListener(listener)​

addRegistrationListener(
listener: (state: PitelRegistrationState) => void,
): () => void

Subscribes to SIP registration changes. The listener is invoked immediately with the current cached state and again after subsequent changes. It returns an unsubscribe function.

const unsubscribe = client.addRegistrationListener((state) => {
if (state === 'registered') {
// The account is ready to make and receive calls.
}
});

unsubscribe();

Event payloads​

PitelCallEvent is a discriminated union. Narrow the payload by checking event.type.

onIncomingCall​

Emitted when the native SDK reports an incoming call.

NOTE

In native mode, incoming calls are presented through Apple CallKit on iOS or the configured Android incoming-call UI. In custom mode, listen to call events and show your app's React Native UI; iOS still uses CallKit for the system incoming-call interface. See the Custom Call Screen Integration Guide for event handling and navigation.

{
type: 'onIncomingCall';
name: string;
callerId: string;
uuid: string;
}
FieldDescription
nameCaller display name when supplied by the remote party.
callerIdCaller number or SIP identifier.
uuidNative call UUID. Android may emit an empty string when no UUID is available.

onCallStateChanged​

Emitted when the current call state or duration changes.

{
type: 'onCallStateChanged';
state: string;
durationSec: number;
statusCode?: number;
reason?: string;
cause?: PitelCallCause;
}
FieldDescription
stateCall state exposed by the JS bridge. Android emits IDLE, INCOMING, CONNECTING, CALLING, CONNECTED, or DISCONNECTED; native ACTIVE is mapped to CONNECTED. Consumers should compare case-sensitively and tolerate additional platform values.
durationSecCurrent call duration in seconds.
statusCodeSIP status code when available.
reasonNative/SIP reason text when available.
causeNormalized disconnect cause when available.

onCallDisconnected​

Emitted when the call has disconnected.

{
type: 'onCallDisconnected';
statusCode?: number;
reason?: string;
cause?: PitelCallCause;
}

All diagnostic fields are optional because a locally ended call or platform callback may not provide a SIP response. Use getPitelCallErrorMessage(event) to obtain a user-facing English failure description or null for a normal disconnect.

onMuteStatusChanged​

{ type: 'onMuteStatusChanged'; isMuted: boolean }

Emitted after the native microphone mute state changes.

onHoldStatusChanged​

{ type: 'onHoldStatusChanged'; isHeld: boolean }

Emitted after the native call hold state changes.

onAudioRouteChanged​

{ type: 'onAudioRouteChanged'; route: string }

Emitted when the native audio route changes. JS route values are 'earpiece', 'speaker', 'bluetooth', and 'wiredHeadset' (see PitelAudioRoute).

Public types​

PitelRegistrationState​

type PitelRegistrationState =
| 'notRegistered'
| 'connecting'
| 'registered';

connecting is the client-side state used while registration is in progress. Native registration callbacks currently resolve to registered or notRegistered.

PitelSettings​

interface PitelSettings {
extension: string;
password: string;
domain: string;
proxy: string;
displayName?: string;
port?: string;
teamId: string;
appMode?: 'dev' | 'production';
incomingCallMode?: 'notification' | 'fullscreen';
callScreenMode?: 'native' | 'custom';
userAgent?: string; // Optional: Default 'Pitel VoIP React Native'
}

See login(settings) for field descriptions and defaults.

callScreenMode selects the UI for incoming and active calls. It accepts 'native' or 'custom'. When omitted, the SDK restores the saved choice and defaults to 'native' on a fresh installation, so native integrations do not need to add a setting. Use 'custom' for your own React Native screens; see the Custom Call Screen Integration Guide. The legacy nativeCallScreen field and setNativeCallScreen() method remain supported but deprecated. An explicit callScreenMode takes precedence over the legacy flag.

Android fullscreen status and Settings helpers are available through getFullScreenIntentStatus() and openFullScreenIntentSettings(). See the Full-Screen Intent guide.

PitelCallCause​

type PitelCallCause =
| 'CALL_REJECTED'
| 'UNALLOCATED_NUMBER'
| 'NO_USER_RESPONSE'
| 'USER_BUSY'
| 'INVALID_NUMBER_FORMAT'
| 'INCOMPATIBLE_DESTINATION'
| 'RECOVERY_ON_TIMER_EXPIRE'
| 'NO_ROUTE_DESTINATION'
| 'NETWORK_OUT_OF_ORDER'
| 'NORMAL_TEMPORARY_FAILURE'
| 'ORIGINATOR_CANCEL'
| 'NORMAL_CLEARING'
| 'UNKNOWN';

See the Call Disconnect Codes & Error Handling Reference for SIP status mappings and recommended handling.

PitelUIConfig​

All PitelUIConfig properties are optional. Omitted values use the native UI preset.

interface PitelUIConfig {
colors?: {
background?: string;
cardBackground?: string;
dialPadBackground?: string;
textPrimary?: string;
textSecondary?: string;
textStatus?: string;
buttonIconActive?: string;
buttonIconInactive?: string;
buttonBackgroundActive?: string;
buttonBackgroundInactive?: string;
hangupButtonBackground?: string;
hangupButtonIcon?: string;
dialPadNumber?: string;
dialPadLetters?: string;
dialPadButtonBackground?: string;
actionButtonGradient?: string[];
};
texts?: {
outgoing?: string;
incoming?: string;
unknownCaller?: string;
connected?: string;
connecting?: string;
mute?: string;
unmute?: string;
speaker?: string;
hold?: string;
unhold?: string;
keypad?: string;
transfer?: string;
endCall?: string;
accept?: string;
decline?: string;
transferCallTitle?: string;
keypadTitle?: string;
enterNumber?: string;
};
visibility?: {
showKeypadByDefault?: boolean;
showTransferButton?: boolean;
showHoldButton?: boolean;
showMuteButton?: boolean;
showSpeakerButton?: boolean;
};
}

Color values use CSS-style hexadecimal strings such as '#6C7BF4'. See UI Customization for an example.

Helper API​

getPitelCallErrorMessage(event)​

getPitelCallErrorMessage(
event:
| PitelCallEvent
| {
statusCode?: number;
cause?: PitelCallCause;
reason?: string;
},
): string | null

Maps a normalized call cause or SIP status to an English description. For SIP failures, the returned string is normally formatted as <statusCode> - <description>. It returns null for NORMAL_CLEARING or when the input does not identify an error.

Platform support summary​

APIAndroidiOSNotes
Registration and call controls✅✅Requires completed native platform setup.
setFCMToken()✅✅Android uses FCM for incoming-call delivery; iOS incoming calls use PushKit.
handlePushNotification()✅✅iOS handles silent call-cancellation payloads; incoming calls use PushKit.
Permission methods✅✅Manifest/Info.plist declarations are still required.
getDiagnostics()—✅Returns null outside iOS.

🎨 UI Customization​

IMPORTANT

The SDK's native call screen is the default and can be styled through uiConfig. Apps that need to provide their own React Native incoming and in-call screens can set callScreenMode: 'custom'; see the Custom Call Screen Integration Guide.

You can customize the native call screen's appearance (colors, text labels, button visibility) by passing a uiConfig inside your login settings:

await client.login({
extension: '...',
password: '...',
domain: '...',
proxy: 'YOUR_PROXY',
port: '50061',
teamId: '...',
uiConfig: {
colors: {
background: '#6C7BF4', // Main call screen background
dialPadBackground: '#FFFFFF', // Keypad sheet background
textPrimary: '#1A1F36', // Primary title text
textSecondary: '#4A5568', // Subtitle text
buttonIconInactive: '#1A1F36', // Inactive button color
buttonIconActive: '#6C7BF4', // Active highlight icon color
buttonBackgroundActive: '#6C7BF41A', // Active highlight overlay background
hangupButtonBackground: '#E53935', // End call button background
dialPadNumber: '#1A1F36', // Keypad numbers color
actionButtonGradient: ['#2E7D32', '#1B5E20'], // Green gradient action buttons
},
texts: {
outgoing: 'Outgoing Call...',
incoming: 'Incoming Call...',
connecting: 'Connecting...',
accept: 'Answer',
decline: 'Decline',
mute: 'Mute',
speaker: 'Speaker',
hold: 'Hold call',
keypad: 'Keypad',
endCall: 'Hang up',
},
visibility: {
showHoldButton: true,
showTransferButton: true,
showKeypadByDefault: false,
},
},
});

Note: If no uiConfig is provided, the SDK falls back to beautiful light and dark presets dynamically.


🛑 Error Handling & Disconnect Causes​

The SDK automatically normalizes low-level SIP error codes into standard PitelCallCause values (USER_BUSY, NO_USER_RESPONSE, UNALLOCATED_NUMBER, CALL_REJECTED, etc.) and provides a built-in helper function:

import { getPitelCallErrorMessage } from 'react-native-pitel-voip-v2';

client.addEventListener((event) => {
if (event.type === 'onCallStateChanged' && event.state === 'DISCONNECTED') {
const errorMsg = getPitelCallErrorMessage(event);
if (errorMsg) {
// Formatted as "<StatusCode> - <Description>" (e.g. "480 - Destination is temporarily unavailable or did not answer.")
console.log('Call Ended:', errorMsg);
}
}
});

👉 For the complete lookup table of all SIP codes, cause mappings, and suggested actions, see the Call Disconnect Codes & Error Handling Reference.