tencent cloud

Cloud Contact Center

Web

Baixar
Modo Foco
Tamanho da Fonte
Última atualização: 2026-09-17 15:41:28
Traduzido e Verificado por IA



Introduce the SDK through the <script> tag. After loading, obtain all external APIs through the global variable window.TcccUserCall.
When introducing the SDK, append the sdkAppId and userId query parameters to the URL. Use the same values as those passed in createUser.
<script src="https://connect.tencentcloud.com/sdk/tccc-user-call-sdk.umd.js?sdkAppId=your_sdkAppId&userId=your_userId"></script>
<script>
const { createUser, TcccSipError, ErrorCode } = window.TcccUserCall;
</script>

Exporting Content

Term
Type
Description
createUser
Function
Factory function for creating user instances.
TcccSipError
Class
Unified error class of the SDK. All exceptions are instances of this class or its subclasses.
ErrorCode
Object
Constant object for error codes, used to determine specific error types.

Quick Start

async function start () {
const sdkAppId = 20000000;
const userId = 'xxx';
const audioChannelId = 'xxx';
// 1. Call the service provider's backend API to obtain the userSig.
// Refer to the Node.js example in "Preliminary Preparation".
const response = await fetch('https://example.api.com/genUserSig?userId=' + encodeURIComponent(userId), {
method: 'GET',
});
if (!response.ok) {
throw new Error(`HTTP error! Status code: ${response.status}`);
}
const { userSig } = await response.json();
// 2. Create a user instance.
const { createUser, TcccSipError, ErrorCode } = window.TcccUserCall;
const user = createUser({
sdkAppId,
userId,
userSig,
});
// 3. Listen for the ready event.
user.on('ready', () => {
console.log('SDK is ready. You can initiate a call.');
// 5. Initiate an audio call (call this after the ready event is triggered).
makeCall(audioChannelId)
});
// 4. Initialize (establish a connection).
user.init();
async function makeCall(audioChannelId) {
try {
const session = await user.startAudioCall(audioChannelId);
session.on('progress', (event) => {
const { status_code, reason_phrase } = event.response;
if (status_code === 180 || status_code === 183) {
console.log('The line is ringing.', reason_phrase);
}
});
session.on('accepted', () => {
console.log('The other party has answered the call.');
});
session.on('ended', (event) => {
console.log('Call ended', event.cause);
});
session.on('failed', (event) => {
console.error('Call failed', event.cause);
});
} catch (err) {
if (err instanceof TcccSipError) {
console.error('Call error [' + err.code + ']: ' + err.message);
}
}
}
// 6. When outbound calls are no longer needed (for example, when the page is terminated), call cleanup to release resources.
async function cleanup() {
await user.unInit();
}
}

start();

createUser (Create User)

Create and return a user instance.
Note:
The SDK allows only one TcccSipUser instance at a time. To create a new instance, you must first call the unInit() method of the current instance to terminate it. Otherwise, a User.InstanceExists error will be thrown.
Parameter description:
Parameter
Type
Required
Description
sdkAppId
number
Yes
SDKAppId of Tencent Cloud Contact Center.
userId
string
Yes
The business-side user ID cannot be empty and cannot contain the @ character. If an email address is used as the user identifier, replace it with a URL-safe identifier.
userSig
string
Yes
User identity signature. For the obtaining process, see Reference.
userClientData
string
No
If the ClientData parameter is specified when the CreateUserSig API is called to obtain the userSig, it must be passed in as well. For details, see Reference.
Return value: TcccSipUser - a user instance object.
const user = createUser({
sdkAppId: 1400000000, // The type is number.
userId: 'your_userId',
userSig: 'your_userSig',
});

TcccSipUser (User Instance)

Represents a user instance. It is created through createUser() and is responsible for managing the connection with the server, initiating calls, and so on.

Methods

Initializing

user.init(): Promise<void>

Initialize the SDK and establish a WebSocket connection with the server. After the connection is successfully established, the ready event is triggered for the first time.

Terminating

user.unInit(): Promise<void>

Terminate the instance, disconnect the connection, and clean up all event listeners and active sessions. Call this method to release resources when the page is unloaded or no longer needed. After termination, you can create a new instance through createUser().

Updating User Signature

user.updateUserSig(userSig, userClientData): void

Update the user signature. If an error occurs during an outbound call and the error code code is User.InvalidUserSig, you can call this method to update the signature and then initiate the call again.
Parameter
Type
Required
Description
userSig
string
Yes
New user signature, which is the user identity signature. For the obtaining process, see Reference.
userClientData
string
No
If the ClientData parameter is specified when the CreateUserSig API is called to obtain the userSig, it must be passed in as well. For details, see Reference.
try {
await user.startAudioCall('xxx');
} catch (err) {
if (err.code === ErrorCode.User.InvalidUserSig) {
user.updateUserSig('new userSig');
// Initiate the call again after the update.
}
}

Initiating Outbound Calls

user.startAudioCall(audioChannelId): Promise<Session>

Note:
Initiate an audio call. It can be called only after the ready event is triggered.
Only one active call is allowed at a time. If a call is already in progress, calling this method again throws the User.CallInProgress error. You must wait for the current call to end or proactively call session.terminate() to hang up before initiating a new call.
Parameter
Type
Required
Description
audioChannelId
string
Yes
Channel ID. For the obtaining method, see Preliminary Preparation.
Return value: Promise<Session> - resolves to a call session object. For details, see the Session (Call Session) section.
try {
const session = await user.startAudioCall('xxx');
} catch (err) {
if (err.code === ErrorCode.User.CallInProgress) {
console.error('A call is already in progress.');
}
}

Events

Listen through user.on(eventName, callback).

Initialization Completed Event

ready

The SDK is ready for the first time (the connection is established successfully). After that, you can initiate a call. No event object parameters are provided.

WS Connecting Event

connecting

The WebSocket connection is being established.
Event object parameters:
Field
Type
Description
attempts
number
Current number of connection attempts.

WS Connected Event

connected

The WebSocket connection is established successfully (including reconnection). No event object parameters are provided.

WS Disconnected Event

disconnected

The WebSocket connection is disconnected.
Event object parameters:
Field
Type
Description
error
boolean
Indicates whether the disconnection is abnormal.
code
number
Disconnection status code (optional).
reason
string
Disconnection reason description (optional).

Session (Call Session)

Session is a call session object returned by user.startAudioCall(). It provides call control methods and call status events.
Note:
Represents a call session. If the call has ended, do not use this object for any further operations.

Methods

Hang Up Call

session.terminate(): void

Hang up / end the current call.
session.terminate();

Muting Local Microphone

session.muteAudio(mute): Promise<void>

Mute or unmute the local microphone.
Note:
You can call this method only after entering the room (you can listen for the onRoomEntered event).
Parameter
Type
Description
mute
boolean
true mutes, false unmutes.
await session.muteAudio(true); // Mute the audio.
await session.muteAudio(false); // Unmute the audio.

Sending DTMF

session.sendDTMFTone(tone, options?): Promise<void>

Send a single DTMF key signal (for example, for IVR key navigation). When this method is called consecutively, signals are automatically queued and sent in order.
Parameter
Type
Required
Description
tone
string
Yes
A single DTMF key character, with a value range of 0-9, #, and *.
options.duration
number
No
DTMF signal duration (ms).
options.interToneGap
number
No
Interval from the next DTMF signal (ms).
await session.sendDTMFTone('1');
await session.sendDTMFTone('#');

Querying Microphone Mute Status

session.isMuted(): { audio: boolean }

Returns the current mute status of the microphone.
const { audio } = session.isMuted();
console.log('Muted:', audio);

Querying Whether the Call Has Ended

session.isEnded(): boolean

Check whether the current call has ended.

Querying Whether the Call Is Being Established

session.isInProgress(): boolean

Check whether the current call is being established.

Querying Whether the Call Has Been Established

session.isEstablished(): boolean

Check whether the current call has been established.

Events

Listen through session.on(eventName, callback).

Call Establishment Progress Event

progress

The remote party is ringing. The response in the event object parameters is an object that contains the following fields:
Field
Type
Description
response.status_code
number
SIP status code, for example, 180 indicates ringing and 183 indicates session progress.
response.reason_phrase
string
SIP status description, for example, 'Ringing' and 'Session Progress'.

Callee Answered Event

accepted

The remote party answers the call. This event has no event object parameters.

Call Confirmed Event

confirmed

This event is triggered when the remote party answers the call and the local protocol stack confirms it (by sending an ack signal). No event object parameters are provided.

TRTC Room Entry Event

onRoomEntered

The local client has entered the audio room, and the audio channel is ready. This event has no event object parameters.

Call Ended Normally Event

ended

The call ends normally. Event object parameters:
Field
Type
Description
cause
string
End reason (see the cause mapping table below).

Call Failed Event

failed

The call fails (rejected, timed out, and so on). After this event is triggered, the current session has ended, and a new call can be initiated. Event object parameters:
Field
Type
Description
cause
string
Failure reason (see the cause mapping table below).

Call End Reasons (cause Mapping)

Possible values of the cause field in the ended and failed events:
cause Value
Description
Terminated
The call ended normally.
Canceled
The caller canceled the call before the callee answered.
Busy
The callee is busy.
Rejected
The call was rejected.
Not Found
The callee number does not exist.
Unavailable
The callee is temporarily unavailable.
No Answer
The callee did not answer.
Expires
The call timed out.
Request Timeout
Requests timed out.
Connection Error
Network connection error.
SIP Failure Code
Other SIP errors.
Internal Error
Internal error.
Address Incomplete
Incomplete number address.
Authentication Error
Authentication error.
Dialog Error
Dialog error.
User Denied Media Access
The user denied media access permission.
WebRTC Error
WebRTC error.
RTP Timeout
RTP timeout (media stream interrupted).

Error Code Reference

All exceptions thrown by SDK methods are raised in the form of TcccSipError (or its subclasses).

Error Object Properties

Attribute
Type
Description
code
string
Error code, in the format of module.description, for example, User.NotReady.
message
string
Human-readable error description.
detail
object | undefined
Structured additional information (available for some error codes).
fullMessage
string
Complete error chain information, with multiple layers of errors connected by line breaks.

Error Identification Methods

const { TcccSipError, ErrorCode } = window.TcccUserCall;

try {
await user.startAudioCall('xxx');
} catch (err) {
// Method 1: Use instanceof to check.
if (err instanceof TcccSipError) {
console.error(err.code, err.message);
}

// Method 2: Use ErrorCode constants for exact matching.
if (err.code === ErrorCode.User.InvalidUserSig) {
user.updateUserSig('new userSig');
}

// Method 3: View the complete error chain.
if (err instanceof TcccSipError) {
console.error(err.fullMessage);
}
}

User Module

Error code
Constant
Description
User.InvalidUserId
ErrorCode.User.InvalidUserId
Invalid userId: it cannot be empty and cannot contain @.
User.InstanceExists
ErrorCode.User.InstanceExists
A user instance already exists. Call unInit() to terminate it before creating a new instance.
User.NotReady
ErrorCode.User.NotReady
The SDK is not ready yet. Initiate a call only after the ready event.
User.Disconnected
ErrorCode.User.Disconnected
The WebSocket connection is disconnected.
User.CallInProgress
ErrorCode.User.CallInProgress
A call is already in progress.
User.InvalidUserSig
ErrorCode.User.InvalidUserSig
The userSig is invalid or has expired.
User.Destroyed
ErrorCode.User.Destroyed
The instance has been terminated. Do not call unInit() again.

Rtc Module

Errors related to devices and audio/video. The detail field of some errors may contain RtcDetail information (see the description below).
Error code
Constant
Description
detail
Rtc.NotInRoom
ErrorCode.Rtc.NotInRoom
The user is not in the room and cannot perform operations such as muting.
-
Rtc.Destroyed
ErrorCode.Rtc.Destroyed
The TRTC instance has been terminated.
-
Rtc.PublishStopped
ErrorCode.Rtc.PublishStopped
Audio publishing failed or was stopped.
RtcDetail
Rtc.JoinRoomFailed
ErrorCode.Rtc.JoinRoomFailed
Failed to enter the audio room.
RtcDetail
Rtc.Trtc
ErrorCode.Rtc.Trtc
TRTC general error.
RtcDetail
Rtc.KickedOut
ErrorCode.Rtc.KickedOut
Kicked out of the room (for example, due to duplicate login).
-
Rtc.CheckDeviceFailed
ErrorCode.Rtc.CheckDeviceFailed
Device detection failed (other unknown reasons).
-
Rtc.MicNotFound
ErrorCode.Rtc.MicNotFound
No microphone device detected.
RtcDetail
Rtc.MicNotAllowed
ErrorCode.Rtc.MicNotAllowed
The user denied microphone permission.
RtcDetail
Rtc.MicNotReadable
ErrorCode.Rtc.MicNotReadable
The microphone is not readable (it may be occupied by another application).
RtcDetail
Rtc.MicTimeout
ErrorCode.Rtc.MicTimeout
Microphone capture timed out (the user did not respond to the authorization pop-up).
-
Rtc.InsecureContext
ErrorCode.Rtc.InsecureContext
In a non-HTTPS environment, the browser prohibits access to the microphone.
-
RtcDetail: The detail field may not exist. Even if it exists, the code and extraCode fields within it may not have values. If they do, refer to the TRTC error code documentation for their specific meanings.
Field
Type
Description
code
number
TRTC error code.
extraCode
number
TRTC additional error code, used to further distinguish the cause.

Cgi Module

Errors related to network requests. The detail field of some errors may contain CgiDetail information (see the description below).
Error code
Constant
Description
detail
Cgi.BizError
ErrorCode.Cgi.BizError
Server-side business logic error (HTTP succeeds but the business response fails).
CgiDetail
Cgi.Error
ErrorCode.Cgi.Error
Network request exception (timeout/network unreachable).
CgiDetail
CgiDetail: The detail field may not exist. Even if it exists, the fields within it may not have values. When troubleshooting, provide the requestId to technical support.
Field
Type
Description
bizCode
string
Business error code returned by the server.
httpStatus
number
HTTP response status code.
requestId
string
Unique request identifier. Provide it to technical support when troubleshooting issues.
code
string
Network-layer error code (for example, ERR_NETWORK).

Session Module

Errors related to call sessions.
Error code
Constant
Description
Session.TrtcClientNotExist
ErrorCode.Session.TrtcClientNotExist
The TRTC client instance does not exist. The call may not have been established yet or may have already ended.

Dtmf Module

Errors related to DTMF key sending.
Error code
Constant
Description
Dtmf.InvalidParam
ErrorCode.Dtmf.InvalidParam
The DTMF parameter is invalid (for example, tone is empty or not a single character).
Dtmf.InvalidState
ErrorCode.Dtmf.InvalidState
The current call state does not allow sending DTMF (the call is not established).
Dtmf.SendFailed
ErrorCode.Dtmf.SendFailed
Failed to send DTMF.
Dtmf.Timeout
ErrorCode.Dtmf.Timeout
DTMF sending timed out.
Dtmf.TransportError
ErrorCode.Dtmf.TransportError
DTMF transport layer error.
Dtmf.DialogError
ErrorCode.Dtmf.DialogError
DTMF dialog error.
Dtmf.ResponseError
ErrorCode.Dtmf.ResponseError
DTMF response error.

Browser Requirements

Must be used in an HTTPS environment (or on localhost). Otherwise, the browser will block microphone access.
Recommended browsers: Chrome 75+, Edge 80+, Firefox 80+.

FAQs

Q1: What should I do if an error is reported when createUser is called? The error code is User.InstanceExists.

The SDK allows only one user instance at a time. Call the unInit() method of the existing instance to terminate it before creating a new one.

Q2: What should I do if an error is reported when startAudioCall is called? The error code is User.NotReady.

Make sure to initiate the call only after the ready event is triggered. The ready event indicates that the connection is established and the SDK is ready.

Q3: What should I do if the error Rtc.MicNotAllowed is reported?

The browser displayed a microphone permission prompt, but the user denied it. Guide the user to click the lock icon on the left side of the browser address bar to re-enable microphone access.

Q4: What should I do if the error User.InvalidUserSig is reported?

The userSig has expired or the signature was calculated incorrectly. Check the backend signature generation logic, call user.updateUserSig() to update the signature, and then initiate the call again.

Q5: What should I do if the error Rtc.InsecureContext is reported?

The page is not loaded over HTTPS. For security reasons, the browser blocks microphone access on HTTP pages. Deploy the page in an HTTPS environment, or use localhost for local development.

Q6: Can multiple calls be initiated at the same time?

Not supported. The SDK allows only one active call at a time. If you call startAudioCall again while a call is already in progress, the User.CallInProgress error is thrown.

Ajuda e Suporte

Esta página foi útil?

comentários