telnyx-webrtc-client-react-native

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Telnyx WebRTC - React Native SDK

Telnyx WebRTC - React Native SDK

Build real-time voice communication into React Native apps (Android & iOS) using the
@telnyx/react-voice-commons-sdk
library.
Prerequisites: Create WebRTC credentials and generate a login token using the Telnyx server-side SDK. See the
telnyx-webrtc-*
skill in your server language plugin (e.g.,
telnyx-python
,
telnyx-javascript
).
使用
@telnyx/react-voice-commons-sdk
库为React Native应用(安卓&iOS)集成实时语音通信能力。
前提条件:创建WebRTC凭证,并使用Telnyx服务端SDK生成登录令牌。请参考对应服务端语言插件中的
telnyx-webrtc-*
skill(例如
telnyx-python
telnyx-javascript
)。

Features

功能特性

  • Reactive Streams: RxJS-based state management
  • Automatic Lifecycle: Background/foreground handling
  • Native Call UI: CallKit (iOS) and ConnectionService (Android)
  • Push Notifications: FCM (Android) and APNs/PushKit (iOS)
  • TypeScript Support: Full type definitions
  • 响应式流:基于RxJS的状态管理
  • 自动生命周期:前后台切换自动处理
  • 原生通话界面:支持CallKit(iOS)和ConnectionService(安卓)
  • 推送通知:支持FCM(安卓)和APNs/PushKit(iOS)
  • TypeScript支持:提供完整的类型定义

Installation

安装

bash
npm install @telnyx/react-voice-commons-sdk

bash
npm install @telnyx/react-voice-commons-sdk

Basic Setup

基础配置

tsx
import { TelnyxVoiceApp, createTelnyxVoipClient } from '@telnyx/react-voice-commons-sdk';

// Create VoIP client instance
const voipClient = createTelnyxVoipClient({
  enableAppStateManagement: true,  // Auto background/foreground handling
  debug: true,                     // Enable logging
});

export default function App() {
  return (
    <TelnyxVoiceApp 
      voipClient={voipClient} 
      enableAutoReconnect={false} 
      debug={true}
    >
      <YourAppContent />
    </TelnyxVoiceApp>
  );
}

tsx
import { TelnyxVoiceApp, createTelnyxVoipClient } from '@telnyx/react-voice-commons-sdk';

// 创建VoIP客户端实例
const voipClient = createTelnyxVoipClient({
  enableAppStateManagement: true,  // 自动处理前后台切换
  debug: true,                     // 开启日志
});

export default function App() {
  return (
    <TelnyxVoiceApp 
      voipClient={voipClient} 
      enableAutoReconnect={false} 
      debug={true}
    >
      <YourAppContent />
    </TelnyxVoiceApp>
  );
}

Authentication

身份验证

Credential-Based Login

基于凭证的登录

tsx
import { createCredentialConfig } from '@telnyx/react-voice-commons-sdk';

const config = createCredentialConfig('sip_username', 'sip_password', {
  debug: true,
  pushNotificationDeviceToken: 'your_device_token',
});

await voipClient.login(config);
tsx
import { createCredentialConfig } from '@telnyx/react-voice-commons-sdk';

const config = createCredentialConfig('sip_username', 'sip_password', {
  debug: true,
  pushNotificationDeviceToken: 'your_device_token',
});

await voipClient.login(config);

Token-Based Login (JWT)

基于令牌的登录(JWT)

tsx
import { createTokenConfig } from '@telnyx/react-voice-commons-sdk';

const config = createTokenConfig('your_jwt_token', {
  debug: true,
  pushNotificationDeviceToken: 'your_device_token',
});

await voipClient.loginWithToken(config);
tsx
import { createTokenConfig } from '@telnyx/react-voice-commons-sdk';

const config = createTokenConfig('your_jwt_token', {
  debug: true,
  pushNotificationDeviceToken: 'your_device_token',
});

await voipClient.loginWithToken(config);

Auto-Reconnection

自动重连

The library automatically stores credentials for seamless reconnection:
tsx
// Automatically reconnects using stored credentials
const success = await voipClient.loginFromStoredConfig();

if (!success) {
  // No stored auth, show login UI
}

本库会自动存储凭证以实现无感重连:
tsx
// 使用已存储的凭证自动重连
const success = await voipClient.loginFromStoredConfig();

if (!success) {
  // 无已存储的身份信息,展示登录界面
}

Reactive State Management

响应式状态管理

tsx
import { useEffect, useState } from 'react';

function CallScreen() {
  const [connectionState, setConnectionState] = useState(null);
  const [calls, setCalls] = useState([]);
  
  useEffect(() => {
    // Subscribe to connection state
    const connSub = voipClient.connectionState$.subscribe((state) => {
      setConnectionState(state);
    });
    
    // Subscribe to active calls
    const callsSub = voipClient.calls$.subscribe((activeCalls) => {
      setCalls(activeCalls);
    });
    
    return () => {
      connSub.unsubscribe();
      callsSub.unsubscribe();
    };
  }, []);
  
  return (/* UI */);
}
tsx
import { useEffect, useState } from 'react';

function CallScreen() {
  const [connectionState, setConnectionState] = useState(null);
  const [calls, setCalls] = useState([]);
  
  useEffect(() => {
    // 订阅连接状态
    const connSub = voipClient.connectionState$.subscribe((state) => {
      setConnectionState(state);
    });
    
    // 订阅活跃通话
    const callsSub = voipClient.calls$.subscribe((activeCalls) => {
      setCalls(activeCalls);
    });
    
    return () => {
      connSub.unsubscribe();
      callsSub.unsubscribe();
    };
  }, []);
  
  return (/* UI */);
}

Individual Call State

单通话状态

tsx
useEffect(() => {
  if (call) {
    const sub = call.callState$.subscribe((state) => {
      console.log('Call state:', state);
    });
    return () => sub.unsubscribe();
  }
}, [call]);

tsx
useEffect(() => {
  if (call) {
    const sub = call.callState$.subscribe((state) => {
      console.log('通话状态:', state);
    });
    return () => sub.unsubscribe();
  }
}, [call]);

Making Calls

拨打电话

tsx
const call = await voipClient.newCall('+18004377950');

tsx
const call = await voipClient.newCall('+18004377950');

Receiving Calls

接听来电

Incoming calls are handled automatically via push notifications and the
TelnyxVoiceApp
wrapper. The native call UI (CallKit/ConnectionService) is displayed automatically.

来电会通过推送通知和
TelnyxVoiceApp
封装层自动处理,原生通话界面(CallKit/ConnectionService)会自动弹出。

Call Controls

通话控制

tsx
// Answer incoming call
await call.answer();

// Mute/Unmute
await call.mute();
await call.unmute();

// Hold/Unhold
await call.hold();
await call.unhold();

// End call
await call.hangup();

// Send DTMF
await call.dtmf('1');

tsx
// 接听来电
await call.answer();

// 静音/取消静音
await call.mute();
await call.unmute();

// 保持/取消保持
await call.hold();
await call.unhold();

// 挂断通话
await call.hangup();

// 发送DTMF信号
await call.dtmf('1');

Push Notifications - Android (FCM)

推送通知 - 安卓(FCM)

1. Place
google-services.json
in project root

1. 将
google-services.json
放置在项目根目录

2. MainActivity Setup

2. MainActivity配置

kotlin
// MainActivity.kt
import com.telnyx.react_voice_commons.TelnyxMainActivity

class MainActivity : TelnyxMainActivity() {
    override fun onHandleIntent(intent: Intent) {
        super.onHandleIntent(intent)
        // Additional intent processing
    }
}
kotlin
// MainActivity.kt
import com.telnyx.react_voice_commons.TelnyxMainActivity

class MainActivity : TelnyxMainActivity() {
    override fun onHandleIntent(intent: Intent) {
        super.onHandleIntent(intent)
        // 额外的intent处理逻辑
    }
}

3. Background Message Handler

3. 后台消息处理器

tsx
// index.js or App.tsx
import messaging from '@react-native-firebase/messaging';
import { TelnyxVoiceApp } from '@telnyx/react-voice-commons-sdk';

messaging().setBackgroundMessageHandler(async (remoteMessage) => {
  await TelnyxVoiceApp.handleBackgroundPush(remoteMessage.data);
});

tsx
// index.js 或 App.tsx
import messaging from '@react-native-firebase/messaging';
import { TelnyxVoiceApp } from '@telnyx/react-voice-commons-sdk';

messaging().setBackgroundMessageHandler(async (remoteMessage) => {
  await TelnyxVoiceApp.handleBackgroundPush(remoteMessage.data);
});

Push Notifications - iOS (PushKit)

推送通知 - iOS(PushKit)

AppDelegate Setup

AppDelegate配置

swift
// AppDelegate.swift
import PushKit
import TelnyxVoiceCommons

@UIApplicationMain
public class AppDelegate: ExpoAppDelegate, PKPushRegistryDelegate {
  
  public override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
  ) -> Bool {
    // Initialize VoIP push registration
    TelnyxVoipPushHandler.initializeVoipRegistration()
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  // VoIP Push Token Update
  public func pushRegistry(_ registry: PKPushRegistry, 
                           didUpdate pushCredentials: PKPushCredentials, 
                           for type: PKPushType) {
    TelnyxVoipPushHandler.shared.handleVoipTokenUpdate(pushCredentials, type: type)
  }
  
  // VoIP Push Received
  public func pushRegistry(_ registry: PKPushRegistry, 
                           didReceiveIncomingPushWith payload: PKPushPayload, 
                           for type: PKPushType, 
                           completion: @escaping () -> Void) {
    TelnyxVoipPushHandler.shared.handleVoipPush(payload, type: type, completion: completion)
  }
}
Note: CallKit integration is automatically handled by the internal CallBridge component.

swift
// AppDelegate.swift
import PushKit
import TelnyxVoiceCommons

@UIApplicationMain
public class AppDelegate: ExpoAppDelegate, PKPushRegistryDelegate {
  
  public override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
  ) -> Bool {
    // 初始化VoIP推送注册
    TelnyxVoipPushHandler.initializeVoipRegistration()
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
  
  // VoIP推送令牌更新
  public func pushRegistry(_ registry: PKPushRegistry, 
                           didUpdate pushCredentials: PKPushCredentials, 
                           for type: PKPushType) {
    TelnyxVoipPushHandler.shared.handleVoipTokenUpdate(pushCredentials, type: type)
  }
  
  // 收到VoIP推送
  public func pushRegistry(_ registry: PKPushRegistry, 
                           didReceiveIncomingPushWith payload: PKPushPayload, 
                           for type: PKPushType, 
                           completion: @escaping () -> Void) {
    TelnyxVoipPushHandler.shared.handleVoipPush(payload, type: type, completion: completion)
  }
}
注意:CallKit集成由内部CallBridge组件自动处理。

Configuration Options

配置选项

createTelnyxVoipClient Options

createTelnyxVoipClient选项

OptionTypeDefaultDescription
enableAppStateManagement
booleantrueAuto background/foreground handling
debug
booleanfalseEnable debug logging
选项类型默认值说明
enableAppStateManagement
布尔值true自动处理前后台切换
debug
布尔值false开启调试日志

TelnyxVoiceApp Props

TelnyxVoiceApp属性

PropTypeDescription
voipClient
TelnyxVoipClientThe VoIP client instance
enableAutoReconnect
booleanAuto-reconnect on disconnect
debug
booleanEnable debug logging

属性类型说明
voipClient
TelnyxVoipClientVoIP客户端实例
enableAutoReconnect
布尔值断开连接时自动重连
debug
布尔值开启调试日志

Storage Keys (Managed Automatically)

存储键(自动管理)

The library manages these AsyncStorage keys internally:
  • @telnyx_username
    - SIP username
  • @telnyx_password
    - SIP password
  • @credential_token
    - JWT token
  • @push_token
    - Push notification token
You don't need to manage these manually.

本库会在内部管理以下AsyncStorage键:
  • @telnyx_username
    - SIP用户名
  • @telnyx_password
    - SIP密码
  • @credential_token
    - JWT令牌
  • @push_token
    - 推送通知令牌
你无需手动管理这些键。

Troubleshooting

问题排查

IssueSolution
Double loginDon't call
login()
manually when using
TelnyxVoiceApp
with auto-reconnect
Background disconnectCheck
enableAutoReconnect
setting
Android push not workingVerify
google-services.json
and MainActivity extends
TelnyxMainActivity
iOS push not workingEnsure AppDelegate implements
PKPushRegistryDelegate
and calls
TelnyxVoipPushHandler
Memory leaksUnsubscribe from RxJS observables in useEffect cleanup
Audio issuesiOS audio handled by CallBridge; Android check ConnectionService
问题解决方案
重复登录
TelnyxVoiceApp
开启自动重连时,不要手动调用
login()
后台断开连接检查
enableAutoReconnect
设置
安卓推送不生效验证
google-services.json
是否正确,且MainActivity继承自
TelnyxMainActivity
iOS推送不生效确保AppDelegate实现了
PKPushRegistryDelegate
并调用了
TelnyxVoipPushHandler
内存泄漏在useEffect清理函数中取消RxJS observable订阅
音频问题iOS音频由CallBridge处理;安卓请检查ConnectionService配置

Clear Stored Auth (Advanced)

清除已存储的身份信息(进阶操作)

tsx
import AsyncStorage from '@react-native-async-storage/async-storage';

await AsyncStorage.multiRemove([
  '@telnyx_username',
  '@telnyx_password', 
  '@credential_token',
  '@push_token',
]);

<!-- BEGIN AUTO-GENERATED API REFERENCE -- do not edit below this line -->
references/webrtc-server-api.md has the server-side WebRTC API — credential creation, token generation, and push notification setup. You MUST read it when setting up authentication or push notifications.
tsx
import AsyncStorage from '@react-native-async-storage/async-storage';

await AsyncStorage.multiRemove([
  '@telnyx_username',
  '@telnyx_password', 
  '@credential_token',
  '@push_token',
]);

<!-- BEGIN AUTO-GENERATED API REFERENCE -- do not edit below this line -->
references/webrtc-server-api.md包含服务端WebRTC API相关内容——凭证创建、令牌生成和推送通知配置。在配置身份验证或推送通知时,你必须阅读该文档。

API Reference

API参考

TelnyxVoipClient

TelnyxVoipClient

Class: TelnyxVoipClient

类:TelnyxVoipClient

The main public interface for the react-voice-commons module.
This class serves as the Façade for the entire module, providing a simplified API that completely hides the underlying complexity. It is the sole entry point for developers using the react-voice-commons package.
The TelnyxVoipClient is designed to be state-management agnostic, exposing all observable state via RxJS streams. This allows developers to integrate it into their chosen state management solution naturally.
react-voice-commons模块的主公开接口。
该类是整个模块的外观层,提供简化的API,完全隐藏底层复杂度,是开发者使用react-voice-commons包的唯一入口。
TelnyxVoipClient被设计为与状态管理方案无关,通过RxJS流暴露所有可观察状态,开发者可以自然地将其集成到自己选择的状态管理方案中。

Methods

方法

login()

login()

login(
config
):
Promise
<
void
>
login(
config
):
Promise
<
void
>

Parameters

参数

config

config

CredentialConfig
CredentialConfig

Returns

返回值

A Promise that completes when the connection attempt is initiated
连接尝试启动后完成的Promise

loginWithToken()

loginWithToken()

loginWithToken(
config
):
Promise
<
void
>
loginWithToken(
config
):
Promise
<
void
>

Parameters

参数

config

config

TokenConfig
TokenConfig

Returns

返回值

A Promise that completes when the connection attempt is initiated
连接尝试启动后完成的Promise

logout()

logout()

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

Returns

返回值

loginFromStoredConfig()

loginFromStoredConfig()

loginFromStoredConfig():
Promise
<
boolean
>
loginFromStoredConfig():
Promise
<
boolean
>

Returns

返回值

newCall()

newCall()

newCall(
destination
,
callerName?
,
callerNumber?
,
customHeaders?
):
Promise
<
Call
>
newCall(
destination
,
callerName?
,
callerNumber?
,
customHeaders?
):
Promise
<
Call
>

Parameters

参数

destination

destination

The destination number or SIP URI to call
要拨打的目标号码或SIP URI

callerName?

callerName?

Optional caller name to display
可选的主叫名称,用于展示

callerNumber?

callerNumber?

Optional caller ID number
可选的主叫ID号码

customHeaders?

customHeaders?

Optional custom headers to include with the call
可选的自定义头,随通话请求发送

Returns

返回值

A Promise that completes with the Call object once the invitation has been sent
邀请发送完成后返回Call对象的Promise

handlePushNotification()

handlePushNotification()

handlePushNotification(
payload
):
Promise
<
void
>
handlePushNotification(
payload
):
Promise
<
void
>

Parameters

参数

payload

payload

The push notification payload
推送通知负载

Returns

返回值

disablePushNotifications()

disablePushNotifications()

disablePushNotifications():
void
disablePushNotifications():
void

Returns

返回值

setCallConnecting()

setCallConnecting()

setCallConnecting(
callId
):
void
setCallConnecting(
callId
):
void

Parameters

参数

callId

callId

The ID of the call to set to connecting state
要设置为连接中状态的通话ID

Returns

返回值

findCallByTelnyxCall()

findCallByTelnyxCall()

findCallByTelnyxCall(
telnyxCall
):
Call
findCallByTelnyxCall(
telnyxCall
):
Call

Parameters

参数

telnyxCall

telnyxCall

The Telnyx call object to find
要查找的Telnyx通话对象

Returns

返回值

Call
Call

queueAnswerFromCallKit()

queueAnswerFromCallKit()

queueAnswerFromCallKit(
customHeaders
):
void
queueAnswerFromCallKit(
customHeaders
):
void

Parameters

参数

customHeaders

customHeaders

Optional custom headers to include with the answer
可选的自定义头,随接听请求发送

Returns

返回值

queueEndFromCallKit()

queueEndFromCallKit()

queueEndFromCallKit():
void
queueEndFromCallKit():
void

Returns

返回值

dispose()

dispose()

dispose():
void
dispose():
void

Returns

返回值

Call

Call

Class: Call

类:Call

Represents a call with reactive state streams.
This class wraps the underlying Telnyx Call object and provides reactive streams for all call state changes, making it easy to integrate with any state management solution.
代表一个带有响应式状态流的通话。
该类封装了底层Telnyx Call对象,为所有通话状态变更提供响应式流,便于集成到任意状态管理方案中。

Methods

方法

answer()

answer()

answer(
customHeaders?
):
Promise
<
void
>
answer(
customHeaders?
):
Promise
<
void
>

Parameters

参数

customHeaders?

customHeaders?

Optional custom headers to include with the answer
可选的自定义头,随接听请求发送

Returns

返回值

hangup()

hangup()

hangup(
customHeaders?
):
Promise
<
void
>
hangup(
customHeaders?
):
Promise
<
void
>

Parameters

参数

customHeaders?

customHeaders?

Optional custom headers to include with the hangup request
可选的自定义头,随挂断请求发送

Returns

返回值

hold()

hold()

hold():
Promise
<
void
>
hold():
Promise
<
void
>

Returns

返回值

resume()

resume()

resume():
Promise
<
void
>
resume():
Promise
<
void
>

Returns

返回值

mute()

mute()

mute():
Promise
<
void
>
mute():
Promise
<
void
>

Returns

返回值

unmute()

unmute()

unmute():
Promise
<
void
>
unmute():
Promise
<
void
>

Returns

返回值

toggleMute()

toggleMute()

toggleMute():
Promise
<
void
>
toggleMute():
Promise
<
void
>

Returns

返回值

setConnecting()

setConnecting()

setConnecting():
void
setConnecting():
void

Returns

返回值

dispose()

dispose()

dispose():
void
dispose():
void

Returns

返回值

TelnyxCallState

TelnyxCallState

Enumeration: TelnyxCallState

枚举:TelnyxCallState

Represents the state of a call in the Telnyx system.
This enum provides a simplified view of call states, abstracting away the complexity of the underlying SIP call states.
代表Telnyx系统中的通话状态。
该枚举提供了简化的通话状态视图,抽象了底层SIP通话状态的复杂度。

Enumeration Members

枚举成员

RINGING

RINGING

RINGING:
"RINGING"
RINGING:
"RINGING"

CONNECTING

CONNECTING

CONNECTING:
"CONNECTING"
CONNECTING:
"CONNECTING"

ACTIVE

ACTIVE

ACTIVE:
"ACTIVE"
ACTIVE:
"ACTIVE"

HELD

HELD

HELD:
"HELD"
HELD:
"HELD"

ENDED

ENDED

ENDED:
"ENDED"
ENDED:
"ENDED"

FAILED

FAILED

FAILED:
"FAILED"
FAILED:
"FAILED"

DROPPED

DROPPED

DROPPED:
"DROPPED"
DROPPED:
"DROPPED"

TelnyxConnectionState

TelnyxConnectionState

Enumeration: TelnyxConnectionState

枚举:TelnyxConnectionState

Represents the connection state to the Telnyx platform.
This enum provides a simplified view of the connection status, abstracting away the complexity of the underlying WebSocket states.
代表与Telnyx平台的连接状态。
该枚举提供了简化的连接状态视图,抽象了底层WebSocket状态的复杂度。

Enumeration Members

枚举成员

DISCONNECTED

DISCONNECTED

DISCONNECTED:
"DISCONNECTED"
DISCONNECTED:
"DISCONNECTED"

CONNECTING

CONNECTING

CONNECTING:
"CONNECTING"
CONNECTING:
"CONNECTING"

CONNECTED

CONNECTED

CONNECTED:
"CONNECTED"
CONNECTED:
"CONNECTED"

RECONNECTING

RECONNECTING

RECONNECTING:
"RECONNECTING"
RECONNECTING:
"RECONNECTING"

ERROR

ERROR

ERROR:
"ERROR"
<!-- END AUTO-GENERATED API REFERENCE -->
ERROR:
"ERROR"
<!-- END AUTO-GENERATED API REFERENCE -->