Client class to interact with the Account API which enables users to manage their Vonage API Account programmatically.
Create a standalone Account client
import { Accounts } from '@vonage/account';
const accountClient = new Accounts({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create an Account client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
const accountClient = vonage.account;
Retrieves the current balance of the Vonage API account.
const balance = await accontClient.getBalance();
console.log(`The current account balance is ${balance.value} ${balance.currency}`);
console.log(`Auto-reload is ${balance.autoReload ? 'enabled' : 'disabled'}`);
Tops up the account balance when auto-reload is enabled. The top-up amount corresponds to the amount added when auto-reload was enabled.
const response = await accountClient.topUpBalance('00X123456Y7890123Z');
if (response['error-code'] === '200') {
console.log(`The account balance has been topped up`);
} else {
console.log(`The account balance could not be topped up`);
}
Updates the default webhook URLs associated with the account for:
- Inbound SMS messages
- Delivery receipts
const callbacks = {
moCallBackUrl: 'https://example.com/webhooks/inbound-sms',
drCallBackUrl: 'https://example.com/webhooks/delivery-receipts',
};
const response = await accountClient.updateAccountCallbacks(callbacks);
for (const [key, value] of Object.entries(response)) {
console.log(`New ${key}: ${value}`);
}
Client class to interact with the Account API to create secrets in their Vonage API Account programmatically.
This client is only available as a standalone client. It cannot be instantiated from the server-sdk package.
Create a standalone Secret client
import { Secrets } from '@vonage/account';
const secretClient = new Secrets({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create a new API secret for a given API key.
const { id } = await secretClient.createSecret(
'new-api-key',
'SuperSecret123!'
);
console.log(`Created secret with ID ${id}`);
Revoke (delete) an existing API secret for a given API key.
await secretClient.deleteSecret('my-api-key', 'my-secret-id');
Retrieve the details of a specific API secret for a given API key.
const { id } = await secretClient.getSecret('my-api-key', 'my-secret-id');
console.log(`Secret with ID ${id} has been retrieved`);
List all the secrets associated with a particular API key.
const response = await secretClient.listSecrets('my-api-key');
for (const secret of response._embedded.secrets) {
console.log(`Secret with ID ${secret.id} has been retrieved`);
}
Represents an SDK client for interacting with audit-related functionality.
This client is only available as a standalone client. It cannot be instantiated from a Vonage client.
Create a standalone Audit client
import { Audit } from '@vonage/audit';
const auditClient = new Audit({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Retrieves a specific audit event by its ID.
Retrieve a specific audit event
const auditEvent = await auditClient.getEvent('event-id');
console.log(auditEvent.id);
Retrieves a list of audit events based on specified parameters.
Retrieve a list of audit events
const auditEvents = auditClient.getEvents({
page: 1,
size: 10,
dateFrom: '2021-01-01T00:00:00Z',
dateTo: '2021-01-31T23:59:59Z',
eventType: 'message',
search: 'search term'
});
for await (const event of auditEvents) {
console.log(event.id);
console.log(event.type);
console.log(event.created);
console.log(event.accountId);
console.log(event.requestId);
console.log(event.request);
console.log(event.response);
console.log(event.ipAddress);
console.log(event.country);
console.log(event.msisdn);
}
Authentication class used for generating Authentication headers and query parameters.
This client is only available as a standalone client. It cannot be instantiated from the server-sdk package.
Create a standard authentication object.
import { Auth } from '@vonage/auth';
const auth = new Auth({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET,
applicationId: VONAGE_APPLICATION_ID,
privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH,
});
Generates a basic authentication header.
Generate a basic authentication headers
const basicAuthHeader = await auth.createBasicHeader();
Generates a bearer authentication header.
Generate a bearer authentication headers
const bearerAuthHeader = await auth.createBearerHeader();
Generates a signature hash for authentication, merging it with provided parameters.
Generate a signature hash
const signatureHash = await auth.createSignatureHash({
to: '15555555555',
from: '15555555556',
text: 'Hello from Vonage SMS API',
timestamp: '1516878400',
sig: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6',
});
Generates query parameters for authentication, optionally merging with provided parameters.
Generate query parameters
const queryParams = await auth.getQueryParams();
Generate query parameters and merge with additional Parameters
const queryParams = await auth.getQueryParams({
to: '15555555555',
from: '15555555556',
text: 'Hello from Vonage SMS API'
});
A client for talking to the Vonage Conversation API.
Create a standalone Conversation client
import { Conversations } from '@vonage/conversation';
const conversationClient = new Conversations({
applicationId: VONAGE_APPLICATION_ID,
privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH,
});
Create an Conversation client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
applicationId: VONAGE_APPLICATION_ID,
privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH,
});
const conversationClient = vonage.conversations
Creates a new conversation with the provided details.
Create a new conversation
const conversation = await conversationClient.createConversation({
name: 'My Conversation',
});
console.log(conversation.id);
Creates a new event with the provided details.
Create a new event
const event = await eventClient.createEvent({
name: 'My Event',
});
console.log(event.id);
Creates a new member with the provided details.
Create a new member
const member = await memberClient.createMember(
CONVERSATION_ID,
{
name: 'My Member',
},
);
console.log(member.id);
Deletes an conversation by its unique identifier.
Delete an conversation
await conversationClient.deleteConversation(conversation_ID);
Deletes an event by its unique identifier.
Delete an event
await eventClient.deleteEvent(conversation_ID);
Retrieves an conversation by its unique identifier.
Retrieve an conversation
const conversation = await conversationClient.getConversation(conversation_ID);
console.log(conversation.name);
Retrieves a page of conversations based on filter parameters.
Get a single page of conversations
const conversations = await conversationClient.getConversationPage({
page: 1,
size: 10
});
conversations.conversations.forEach(conversation => {
console.log(conversation.name);
});
Retrieves an event by its unique identifier.
Retrieve an event
const event = await eventClient.getEvent(CONVERSATION_ID, event_ID);
console.log(event.name);
Retrieves a page of events based on filter parameters.
Get a single page of events
const events = await eventClient.getEventPage({
page: 1,
size: 10
});
events.events.forEach(event => {
console.log(event.name);
});
This retrieves the member associated with the sub claim on the JWT
Retrieve an member
const member = await memberClient.getMe(CONVERSATION_ID);
console.log(member.name);
Retrieves an member by its unique identifier.
Retrieve an member
const member = await memberClient.getMember(CONVERSATION_ID, MEMBER_ID);
console.log(member.name);
Retrieves a page of members in a conversation based on filter parameters.
Get a single page of members
const members = await memberClient.getMemberPage(
CONVERSATION_ID,
{
page: 1,
size: 10
}
);
members.members.forEach(member => {
console.log(member.name);
});
Retrieves a page of sessions based on filter parameters.
Get a single page of sessions
const sessions = await conversationClient.getUserSessionPage(
USER_ID,
{
page: 1,
size: 10
}
);
sessions.sessions.forEach(session => {
console.log(session.id);
});
Retrieves all conversations, iterating over paginated results.
List conversations with pagination using an iterator
for await (const conversation of conversationClient.listAllConversations()) {
console.log(conversation.name);
}
Retrieves all events, iterating over paginated results.
List events with pagination using an iterator
for await (const event of eventClient.listAllEvents()) {
console.log(event.name);
}
Retrieves all members, iterating over paginated results.
List members with pagination using an iterator
for await (const member of memberClient.listAllMembers(CONVERSATION_ID)) {
console.log(member.name);
}
Retrieves all conversations, for a user
List conversations with pagination using an iterator
for await (const conversation of conversationClient.listAllUserConversations(USER_ID)) {
console.log(conversation.name);
}
Retrieves all session, for a user
List sessions with pagination using an iterator
for await (const session of conversationClient.listAllUserSessions(USER_ID)) {
console.log(session.id);
}
Updates an existing conversation with the provided details.
Update an conversation
const conversation = await conversationClient.updateConversation({
id: conversation_ID,
name: 'My Conversation',
});
console.log(conversation.name);
Updates an existing member with the provided details.
Setting the state to left will result in the member leaving the conversation.
import { MemberState } from '@vonage/conversation';
const member = await memberClient.updateMember(
CONVERSATION_ID,
MEMBER_ID,
{
state: MemberState.LEFT,
from: USER_ID,
},
);
console.log(member.name);
Creates a new application with the provided details.
Create a new application
const application = await applicationClient.createApplication({
name: 'My Application',
capabilities: {
voice: {
webhooks: {
answerUrl: {
address: 'https://example.com/answer',
httpMethod: 'GET'
},
eventUrl: {
address: 'https://example.com/event',
httpMethod: 'POST'
}
}
}
}
});
console.log(application.id);
Deletes an application by its unique identifier.
Delete an application
await applicationClient.deleteApplication(APPLICATION_ID);
Retrieves an application by its unique identifier.
Retrieve an application
const application = await applicationClient.getApplication(APPLICATION_ID);
console.log(application.name);
Retrieves a page of applications based on filter parameters.
Get a single page of applications
const applications = await applicationClient.getApplicationPage({
page: 1,
size: 10
});
applications.applications.forEach(application => {
console.log(application.name);
});
Retrieves all applications, iterating over paginated results.
List applications with pagination using an iterator
for await (const application of applicationClient.listAllApplications()) {
console.log(application.name);
}
Retrieves a list of applications with optional pagination parameters.
List a single page of applications
const applications = await applicationClient.listApplications({});
applications.applications.forEach(application => {
console.log(application.name);
});
Updates an existing application with the provided details.
Update an application
const application = await applicationClient.updateApplication({
id: APPLICATION_ID,
name: 'My Application',
});
console.log(application.name);
MissingPrivateKeyError
class for throwing an error when the private key
is missing. The private key must either be the string of the key or a buffer
from the key file. When you created the application, the private key would
have been downloaded then. If you lost the key, you will need to regenrate
the key.
Generates a JWT token.
Generate a JWT token with default claims.
const privateKey = fs.readFileSync(__dirname + '/private.key');
const token = tokenGenerate(applicationId, privateKey);
Generate a JWT token with custom claims.
const privateKey = fs.readFileSync(__dirname + '/private.key');
const token = tokenGenerate(applicationId, privateKey, {
subject: 'my-subject',
acl: {
paths: {
'/*/users/**': {},
'/*/conversations/**': {},
'/*/sessions/**': {},
},
},
});
Verifies a JWT token
Validate a JWT token
const privateKey = fs.readFileSync('./private.key');
if (verifySignature(token, privateKey)) {
console.log('JWT signature verified.');
} else {
console.log('JWT signature verification failed.');
}
Client for the Vonage Number Insights API.
Create a standalone Number Insight client
import { NumberInsights } from '@vonage/numberInsight';
const numberInsightClient = new NumberInsights({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create an Number Insight client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
const numberInsightClient = vonage.numberInsight;
Perform an advanced number lookup operation.
const lookup = await numberInsightsClient.advancedLookup('15555551212');
console.log(`Ths number is ${lookup.valid_number}`);
Perform an asynchronous advanced number lookup operation.
const lookup = await numberInsightsClient.asyncAdvancedLookup(
'15555551212',
'https://example.com/number-insights',
);
console.log(`The request ID is ${lookup.request_id}`);
Lookup with the CNAME option:
const lookup = await numberInsightsClient.asyncAdvancedLookup(
'15555551212',
'https://example.com/number-insights',
{ cname: true },
);
console.log(`The request ID is ${lookup.request_id}`);
Perform a basic number lookup operation.
const lookup = await numberInsightsClient.basicLookup(
'15555551212',
);
console.log(`The request ID is ${lookup.request_id}`);
Lookup with the country option:
const lookup = await numberInsightsClient.basicLookup(
'15555551212',
{ country: 'US' },
);
console.log(`The request ID is ${lookup.request_id}`);
Perform a standard number lookup operation.
const lookup = await numberInsightsClient.standardLookup(
'15555551212',
);
console.log(`The request ID is ${lookup.request_id}`);
Lookup with the cname option:
const lookup = await numberInsightsClient.standardLookup(
'15555551212',
{ cname: true },
);
console.log(`The request ID is ${lookup.request_id}`);
Client class to interact with the Media API which enables users to manage their media items programmatically.
This client is only available as a standalone client. It cannot be instantiated from the server-sdk package.
Create a standalone Secret client
import { Media } from '@vonage/media';
const mediaClient = new Media({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Deletes a specific media item by its unique identifier.
Delete a media item
await mediaClient.deleteMediaItem('my-media-id');
Retrieves information about a specific media item by its unique identifier.
Retrieve a media item by its ID
const media = await mediaClient.getMediaItem('my-media-id');
console.log(`Media item ${media.id} is ${media.public ? 'public' : 'private'}`);
console.log(` - Title: ${media.title}`);
console.log(` - Description: ${media.description}`);
Retrieves a page of media items based on the specified parameters.
List the first page of media items
const resp = await mediaClient.getMediaPage();
console.log(`There are ${resp.count} media items in total`);
console.log(`Showing ${resp._embedded.media.length} media items on this page`);
Retrieves a paginated list of media items, yielding each item sequentially.
List all media items
for await (const media of mediaClient.listAllMediaItems()) {
console.log(`Media item ${media.id} is ${media.public ? 'public' : 'private'}`);
console.log(` - Title: ${media.title}`);
console.log(` - Description: ${media.description}`);
};
List all public media items
for await (const media of mediaClient.listAllMediaItems({ public: true })) {
console.log(`Media item ${media.id} is public`);
console.log(` - Title: ${media.title}`);
console.log(` - Description: ${media.description}`);
};
Updates the information of a specific media item based on the provided data.
Update a media item
const media = await mediaClient.getMediaItem('my-media-id');
media.title = 'My new title';
media.description = 'My new description';
await mediaClient.updateMediaItem(media);
Client class to interact with the Meetings API to create and manage meeting rooms.
This client is only available as a standalone client. It cannot be instantiated from the server-sdk package.
Create a standalone Meetings Client
import { Meetings } from '@vonage/meetings';
const meetingsClient = new Meetings({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET,
applicationId: VONAGE_APPLICATION_ID,
privateKey: VONAGE_APPLICATION_PRIVATE_KEY_PATH
});
Creates a new meeting room.
Create a new meeting room
const room = await meetingsClient.createRoom({
displayName: 'My Room',
metadata: {
my_data: 'my_value'
}
});
console.log(`Created room with ID ${room.id}`);
Creates a new theme with the provided theme details.
Create a new themes
const theme = await meetingsClient.createTheme({
themeName: 'My Theme',
mainColor: '#C0FFEE',
brandText: 'My Brand',
shortCompanyUrl: 'my-brand'
});
console.log(`Created theme with ID ${theme.id}`);
Deletes a recording by its ID.
Delete a recording by ID
await meetingsClient.deleteRecording('my-recording-id');
console.log(`Recording with ID ${recordingId} has been deleted`);
Deletes a theme by its theme ID.
Delete a theme by ID
await meetingsClient.deleteTheme('my-theme-id');
console.log(`Theme with ID ${themeId} has been deleted`);
Retrieves a list of dial-in numbers.
Get a list of dial-in numbers
for await (const number of meetingsClient.getDialInNumbers()) {
console.log(`Dial-in number ${number.number} is in ${number.country}`);
}
Retrieves a recording by its ID.
Get a recording by ID
const recording = await meetingsClient.getRecording('my-recording-id');
console.log(`Recording ${recording.id} started at ${recording.startedAt}`);
console.log(`Recording ${recording.id} ended at ${recording.endedAt}`);
Retrieves a meeting room by its ID.
Get a meeting room by ID
const room = await meetingsClient.getRoom('my-room-id');
console.log(`Room ${room.id} has ${room.participants} participants`);
console.log(`Room ${room.id} has ${room.members} members`);
console.log(`Room ${room.id} has ${room.sessions} sessions`);
console.log(`Room ${room.id} has ${room.recordings} recordings`);
Retrieves a page of meeting rooms based on the provided parameters.
Get a page of meeting rooms
const resp = await meetingsClient.getRoomPage();
console.log(`There are ${resp.totalItems} meeting rooms`);
console.log(`There are ${resp.pageSize} meeting rooms per page`);
Get a specific page of meeting rooms
const resp = await meetingsClient.getRoomPage({pageSize: 10, pageNumber: 2});
console.log(`There are ${resp.totalItems} meeting rooms`);
console.log(`There are ${resp.pageSize} meeting rooms per page`);
Retrieves a list of meeting rooms until there are no more pages
Generate a list of meeting rooms
for await (const room of meetingsClient.getRooms()) {
console.log(`Room ${room.id} has ${room.participants} participants`);
console.log(`Room ${room.id} has ${room.sessions} sessions`);
console.log(`Room ${room.id} has ${room.recordings} recordings`);
console.log(`Room ${room.id} has ${room.members} members`);
}
Retrieves a list of meeting rooms associated with a specific theme. This will keep calling the API until there are no more pages
Get meeting rooms for a theme
for await (const room of meetingsClient.getRoomsForTheme('my-theme-id')) {
console.log(`Room ${room.id} has ${room.participants} participants`);
console.log(`Room ${room.id} has ${room.sessions} sessions`);
console.log(`Room ${room.id} has ${room.recordings} recordings`);
console.log(`Room ${room.id} has ${room.members} members`);
}
Retrieves a page of meeting rooms associated with a specific theme.
Get a page of meeting rooms for a theme
const resp = await meetingsClient.getRoomsForThemePage('my-theme-id');
console.log(`There are ${resp.totalItems} meeting rooms`);
console.log(`There are ${resp.pageSize} meeting rooms per page`);
Get a specific page of meeting rooms for a theme
const resp = await meetingsClient.getRoomsForThemePage('my-theme-id', {pageSize: 10, pageNumber: 2});
console.log(`There are ${resp.totalItems} meeting rooms`);
console.log(`There are ${resp.pageSize} meeting rooms per page`);
Retrieves recordings associated with a session by its ID until there are no more recordings
Get recordings for a session
for await (const recording of meetingsClient.getSessionRecordings('my-session-id')) {
console.log(`Recording ${recording.id} started at ${recording.startedAt}`);
console.log(`Recording ${recording.id} ended at ${recording.endedAt}`);
}
Retrieves a theme by its theme ID.
Get a theme by ID
const theme = await meetingsClient.getTheme('my-theme-id');
console.log(`Theme ${theme.themeName} has ID ${theme.id}`);
Retrieves a list of themes.
Get a list of getThemes
for await (const theme of meetingsClient.getThemes()) {
console.log(`Theme ${theme.themeName} has ID ${theme.id}`);
}
Sets the default theme for the application.
Set the default theme
await meetingsClient.setDefaultTheme('my-theme-id');
console.log(`Default theme has been set`);
Updates an existing meeting room.
Update a meeting room
const room = await meetingsClient.updateRoom('my-room-id', {
displayName: 'My Room',
metadata: {
my_data: 'my_value'
}
});
console.log(`Updated room with ID ${room.id}`);
Updates an existing theme with the provided theme details.
Update a theme
const theme = await meetingsClient.updateTheme('my-theme-id', {
themeName: 'My Theme',
mainColor: '#C0FFEE',
brandText: 'My Brand',
shortCompanyUrl: 'my-brand'
});
console.log(`Updated theme with ID ${theme.id}`);
Uploads an icon (logo) to a theme.
Upload an icon to a theme
await meetingsClient.uploadIcon('my-theme-id', LogoType.WHITE, '/path/to/white-logo.png');
console.log(`Icon has been uploaded`);
Client class to interact with the Messages API which enables users to manage send messages through various channels programmatically.
Create a standalone Messages client
import { Messages } from '@vonage/messages';
const messagesClient = new Messages({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create an Messages client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
const messagesClient = vonage.messages;
Update the status of outbound and/or inbound messages for certain channels. For example, you can revoke outbound messages or mark inbound messages as read.
Please not that this endpoint is region specifc. You will need to set the region when you create the client.
Update the status of a WhatsApp message to "read"
const vonage = new Vonage(
{
applicationId: myAppId,
privateKey: myPrivateKey
},
{
apiHost: 'https://api-eu.vonage.com'
}
)
await vonage.messages.updateMessage(messageId, UpdateMessageStatus.READ);
Represents an audio message for the Messenger channel.
Sends an audio message to the Facebook Messenger channel.
import { MessengerAudio } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MessengerAudio({
to: TO_NUMBER,
from: FROM_NUMBER,
audio: {
url: 'https://example.com/audio.mp3',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a file message for the Messenger channel.
Sends a file message to the Facebook Messenger channel.
import { MessengerFile } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MessengerFile({
to: TO_NUMBER,
from: FROM_NUMBER,
file: {
url: 'https://example.com/image.jpg',
caption: 'This is an image',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents an image message for the Messenger channel.
This class extends the
AbstractImageMessage
class and implements the
MessengerImageParams
interface.
It is used for sending image messages on the Messenger channel.
Send an image message using the Facebook Messenger channel.
import { MessengerImage } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MessengerImage({
to: TO_NUMBER,
from: FROM_NUMBER,
image: {
url: 'https://example.com/image.jpg',
caption: 'This is an image',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a text message for the Messenger channel.
Sends a text message to the Facebook Messenger channel.
import { MessengerText } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MessengerText({
to: TO_NUMBER,
from: FROM_NUMBER,
text: 'Hello world',
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a video message for the Messenger channel.
Send a video message using the Facebook Messenger channel.
import { MessagengerVideo } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MessagengerVideo({
to: TO_NUMBER,
from: FROM_NUMBER,
video: {
url: 'https://example.com/video.mp4',
caption: 'This is a video',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents an audio message for the MMS channel.
Send an MMS audio message.
import { MMSAudio } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MMSAudio({
to: TO_NUMBER,
from: FROM_NUMBER,
audio: {
url: 'https://example.com/audio.mp3',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents an image message for the MMS channel.
Send an MMS image message.
import { MMSImage } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MMSImage({
to: TO_NUMBER,
from: FROM_NUMBER,
image: {
url: 'https://example.com/image.jpg',
caption: 'This is an example image',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a vCard message for the MMS channel.
Send an MMS vCard message.
import { MMSVcard } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MMSVcard({
to: TO_NUMBER,
from: FROM_NUMBER,
vcard: {
url: 'https://example.com/vcard.vcf',
caption: 'Download my contact information',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a video message for the MMS channel.
Send an MMS video message.
import { MMSVideo } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new MMSVideo({
to: TO_NUMBER,
from: FROM_NUMBER,
video: {
url: 'https://example.com/video.mp4',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a custom message for RCS.
Sends a custom message through RCS
import { RCSCustom } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new RCSCustom({
to: TO_NUMBER,
from: FROM_NUMBER,
custom: {
foo: 'bar',
}
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a file message for the RCS channel.
Sends a file message to the RCS channel.
import { RCSFile } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new RCSFile({
to: TO_NUMBER,
from: FROM_NUMBER,
file: {
url: 'https://example.com/image.pdf',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents an image message for the RCS channel.
Send an RCS image message.
import { RCSImage } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new RCSImage({
to: TO_NUMBER,
from: FROM_NUMBER,
image: {
url: 'https://example.com/image.jpg',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a text message for the RCS channel.
Sends a text message through the RCS channel.
import { RCSText } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new RCSText({
to: TO_NUMBER,
from: FROM_NUMBER,
text: 'Hello world',
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents an video message for the RCS channel.
Send an RCS video message.
import { RCSVideo } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new RCSVideo({
to: TO_NUMBER,
from: FROM_NUMBER,
audio: {
url: 'https://example.com/video.mp4',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Send a text message using the SMS channel.
Send an SMS message
import { SMS } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new SMS({
to: TO_NUMBER,
from: FROM_NUMBER,
text: 'Hello world',
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Send SMS with entity ID and content ID
import { SMS } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new SMS({
to: TO_NUMBER,
from: FROM_NUMBER,
text: 'Hello world',
clientRef: 'my-personal-reference',
sms: {
entityId: 'MyEntityID',
contentId: 'MyContentID'
}
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a file message for the Viber Service channel.
Send a file message using the Viber Service channel.
import { ViberFile } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new ViberFile({
to: TO_NUMBER,
from: FROM_NUMBER,
file: {
url: 'https://my-host.com/my-file.pdf',
},
viberService: {
action: {
url: 'https://my-host.com/my-path',
text: 'My button text',
},
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents an image message for the Viber Service channel.
Send an image message using the Viber Service channel.
import { ViberImage } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new ViberImage({
to: TO_NUMBER,
from: FROM_NUMBER,
image: {
url: 'https://my-host.com/my-image.jpg',
},
viberService: {
action: {
url: 'https://my-host.com/my-path',
text: 'My button text',
},
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a text message for the Viber Service channel.
Send a text message using the Viber Service channel.
import { ViberText } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new ViberText({
to: TO_NUMBER,
from: FROM_NUMBER,
text: 'Hello world',
viberService: {
action: {
url: 'https://my-host.com/my-path',
text: 'My button text',
},
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a video message for the Viber Service channel.
Send a video message using the Viber Service channel.
import { ViberVideo } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new ViberVideo({
to: TO_NUMBER,
from: FROM_NUMBER,
text: 'Hello world',
video: {
url: 'https://my-host.com/my-video.mp4',
},
viberService: {
action: {
url: 'https://my-host.com/my-path',
text: 'My button text',
},
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents an audio message for WhatsApp.
Sends an audio message to a WhatsApp user.
import { WhatsAppAudio } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppAudio({
to: TO_NUMBER,
from: FROM_NUMBER,
audio: {
url: 'https://example.com/audio.mp3',
caption: 'This is an audio message',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a custom message for WhatsApp.
Sends a custom message to a WhatsApp user.
import { WhatsAppCustom } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppCustom({
to: TO_NUMBER,
from: FROM_NUMBER,
custom: {
type: 'template',
template: {
namespace: 'your-namespace',
name: 'your-template-name',
},
}
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a file message for WhatsApp.
Send a WhatsApp file message.
import { WhatsAppFile } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppFile({
to: TO_NUMBER,
from: FROM_NUMBER,
file: {
url: 'https://example.com/image.jpg',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents an image message for WhatsApp.
Sends an image message to a WhatsApp user.
import { WhatsAppImage } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppImage({
to: TO_NUMBER,
from: FROM_NUMBER,
image: {
url: 'https://example.com/image.jpg',
caption: 'This is an image message',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a reaction message for WhatsApp.
Sends a reaction message to a WhatsApp user.
Send a reaction
import { WhatsAppReaction } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppReaction({
to: TO_NUMBER,
from: FROM_NUMBER,
reaction: {
action: 'react',
emoji: '😍',
}
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Remove reaction
import { WhatsAppReaction } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppReaction({
to: TO_NUMBER,
from: FROM_NUMBER,
reaction: {
action: 'unreact',
}
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a sticker message for WhatsApp.
Send a sticker message to a WhatsApp user.
Send a sticker message with a sticker ID:
import { WhatsAppSticker } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppSticker({
to: TO_NUMBER,
from: FROM_NUMBER,
sticker: {
id: '0-0',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Send a sticker message with a sticker URL:
import { WhatsAppSticker } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppSticker({
to: TO_NUMBER,
from: FROM_NUMBER,
sticker: {
url: 'https://example.com/sticker.png',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a template message for WhatsApp.
Send a template message to a WhatsApp user.
import { WhatsAppTemplate, WhatsAppLanguageCode } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppTemplate({
to: TO_NUMBER,
from: FROM_NUMBER,
whatsapp: {
policy: 'deterministic',
locale: WhatsAppLanguageCode.EN,
},
template: {
name: 'your-template-name',
parameters: [
'foo',
'bar',
],
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a text message for WhatsApp.
Send a WhatsApp text message.
import { WhatsAppText } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppText({
to: TO_NUMBER,
from: FROM_NUMBER,
text: 'Hello world',
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Represents a video message for WhatsApp.
Sends a video message to a WhatsApp user.
import { WhatsAppVideo } from '@vonage/messages';
const { messageUUID } = await messagesClient.send(new WhatsAppVideo({
to: TO_NUMBER,
from: FROM_NUMBER,
video: {
url: 'https://example.com/video.mp4',
caption: 'This is a video message',
},
clientRef: 'my-personal-reference',
}));
console.log(`Message sent successfully with UUID ${messageUUID}`);
Number Insight v2 is designed to give fraud scores for Application Integrations. This class represents the client for making fraud check requests.
Make a fraud check request with the provided parameters.
Check for fraud on a phone number.
import { Insight } from '@vonage/number-insight-v2';
const score = await client.numberInsightV2.checkForFraud({
type: 'phone',
number: '447700900000',
insights: [
Insight.FRAUD_SCORE,
],
});
console.log(`Fraud score: ${score.riskScore}`);
Check for SIM swap on a phone number.
import { Insight } from '@vonage/number-insight-v2';
const score = await client.numberInsightV2.checkForFraud({
type: 'phone',
number: '447700900000',
insights: [
Insight.SIM_SWAP,
],
});
console.log(`SIM swap detected: ${score.simSwap ? 'Yes' : 'No'}`);
Check both fraud score and SIM swap on a phone number.
import { Insight } from '@vonage/number-insight-v2';
const score = await client.numberInsightV2.checkForFraud({
type: 'phone',
number: '447700900000',
insights: [
Insight.SIM_SWAP,
Insight.FRAUD_SCORE,
],
});
console.log(`SIM swap detected: ${score.simSwap ? 'Yes' : 'No'}`);
console.log(`Fraud score: ${score.riskScore}`);
Client for buying, canceling, and searching for phone numbers.
Create a standalone Numbers client
import { Numbers } from '@vonage/numbers';
const numbersClient = new Numbers({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create an Numbers client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
const numbersClient = vonage.numbers;
Buy a phone number.
Buy a phone number
import { Country } from '@vonage/numbers';
const resp = await numbersClient.buyNumber({
country: Country.US,
msisdn: '15555555555'
});
if (resp.errorCode) {
console.log(`Error: ${resp.errorCodeLabel}`);
} else {
console.log('Number bought successfully');
}
Cancel a phone number.
Cancel a phone number
const resp = await numbersClient.cancelNumber({
msisdn: '15555555555'
});
if (resp.errorCode) {
console.log(`Error: ${resp.errorCodeLabel}`);
} else {
console.log('Number cancled successfully');
}
Retrieves a list of available phone numbers based on the provided filter criteria.
Search for available numbers that can send SMS and make voice calls
import { Country, Feature } from '@vonage/numbers';
const resp = await numbersClient.getAvailableNumbers({
country: Country.US,
features: [Feature.SMS, Feature.VOICE],
});
console.log(`There are ${resp.count} numbers available`);
for (const number of resp.numbers) {
console.log(number.msisdn);
console.log(number.cost);
console.log(number.type);
}
Retrieves a list of owned phone numbers based on the provided filter criteria.
Search for owned numbers
const resp = await numbersClient.getOwnedNumbers();
console.log(`There are ${resp.count} numbers owned`);
for (const number of resp.numbers) {
console.log(number.msisdn);
console.log(number.type);
}
Updates the settings of a phone number.
const resp = await numbersClient.updateNumber({
msisdn: '15555555555',
voiceCallbackType: 'app',
voiceCallbackValue: 'APPLICATION_ID',
voiceStatusCallback: 'https://example.com/webhooks/voice',
});
if (resp.errorCode) {
console.log(`Error: ${resp.errorCodeLabel}`);
} else {
console.log('Number bought successfully');
}
The Pricing API allows you to retrieve pricing information for all countries and a specific service type, for a specific country and service type, or for a specific prefix and service type.
Create a standalone Pricing client
import { Pricing } from '@vonage/pricing';
const pricingClient = new Pricing({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create an Pricing client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
const pricingClient = vonage.pricing;
Retrieves pricing information for all countries and a specific service type.
import { ServiceType } from '@vonage/pricing';
const pricing = await pricingClient.listAllCountriesPricing(ServiceType.SMS);
for (const country in pricing.countries) {
console.log(`The current price for ${country.countryName} is ${country.defaultPrice}`);
}
Retrieves pricing information for a specific country and service type.
import { ServiceType } from '@vonage/pricing';
const pricing = await pricingClient.listCountryPricing(ServiceType.SMS, 'GB');
console.log(`The current price for Great Britian is ${pricing.defaultPrice}`);
Retrieves pricing information for a specific prefix and service type.
import { ServiceType } from '@vonage/pricing';
const pricing = await pricingClient.listPrefixPricing(ServiceType.SMS, '44');
console.log(`The current price for Great Britian is ${pricing.defaultPrice}`);
Client for sending legacy SMS messages using the Vonage API.
Create a standalone SMS client
import { AlgorithmTypes } from '@vonage/auth';
import { SMS } from '@vonage/sms';
const smsClient = new SMS({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
secret: {
secret: VONAGE_SIGNATURE_SECRET
algorithm: AlgorithmTypes.sha512hmac
},
});
Create an SMS client from the Vonage client
import { AlgorithmTypes } from '@vonage/auth';
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
secret: {
secret: VONAGE_SIGNATURE_SECRET
algorithm: AlgorithmTypes.sha512hmac
},
});
const smsClient = vonage.sms;
Sends an SMS message using the legacy Vonage SMS API.
const response = await smsClient.send({
to: TO_NUMBER,
from: FROM_NUMBER,
text: 'Hello from Vonage SMS API',
});
console.log(`Number of messages sent: ${response.messageCount}`););
Verifies the signature of a request using the specified algorithm and signature secret.
const params = Object.assign(request.query, request.body);
const { sig } = params;
sms.verifySignature(
sig,
{}, // request parameters
VONAGE_API_SIGNATURE_SECRET,
AlgorithmTypes.md5hash,
) === params.sig) {
console.log("Valid signature");
} else {
console.log("Invalid signature");
}
The Verify class provides methods for managing and performing verification processes using the Vonage Verify API.
It allows you to initiate new verification requests, check verification codes, search for verification request details, and perform control actions like canceling or triggering the next event for a verification process.
Create a standalone Verify client
import { Verify } from '@vonage/verify';
const verifyClient = new Verify({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create an Verify client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
const verifyClient = vonage.verify;
Cancels a specific verification request.
import { CheckStatus } from '@vonage/verify';
const result = await verifyClient.cancel('REQUEST_ID')
if (result.status === CheckStatus.SUCCESS) {
console.log('Verification request canceled.');
console.log(result.status);
} else {
console.log('Error canceling verification request.');
console.log(result.errorText);
}
Checks the verification code for a specific verification request.
import { CheckStatus } from '@vonage/verify';
const result = await verifyClient.check('REQUEST_ID', 'CODE')
if (result.status === CheckStatus.SUCCESS) {
console.log('Verification code is valid.');
} else {
console.log('Verification code is invalid.');
}
Searches for the status of a verification request by its request ID.
const result = await verifyClient.search('REQUEST_ID')
if (result.errorText) {
console.log(`Request found with error ${result.errorText}`);
} else {
console.log(`Request found and submitted on ${result.dateSubmitted}`);
}
Sends a control command for a specific verification request.
Cancel a verification request
import { Command, CheckStatus } from '@vonage/verify';
const result = await verifyClient.sendControl(Command.CANCEL, 'REQUEST_ID')
if (result.status === CheckStatus.SUCCESS) {
console.log('Verification request canceled.');
console.log(result.status);
} else {
console.log('Error canceling verification request.');
console.log(result.errorText);
}
Trigger the next event for a verification request
import { Command, CheckStatus } from '@vonage/verify';
const result = await verifyClient.sendControl(Command.TRIGGER_NEXT_EVENT, 'REQUEST_ID')
if (result.status === CheckStatus.SUCCESS) {
console.log('Next event triggered');
console.log(result.status);
} else {
console.log('Error triggering next event');
console.log(result.errorText);
}
Starts a verification request.
const result = await verifyClient.start({
number: TO_NUMBER,
brand: BRAND_NAME
});
if (result.requestId) {
console.log(`Request started with id ${result.requestId}`);
} else {
console.log(`Request failed with error: ${result.errorText}`);
}
Start a request with PSD2 parameters
const result = await verifyClient.start({
number: TO_NUMBER,
payee: PAYEE,
amount: AMOUNT,
})
if (result.requestId) {
console.log(`Request started with id ${result.requestId}`);
} else {
console.log(`Request failed with error: ${result.errorText}`);
}
Triggers the next verification event for a specific verification request.
import { CheckStatus } from '@vonage/verify';
const result = await verifyClient.trigger('REQUEST_ID')
if (result.status === CheckStatus.SUCCESS) {
console.log('Verification request canceled.');
console.log(result.status);
} else {
console.log('Error canceling verification request.');
console.log(result.errorText);
}
A class for interacting with the Vonage Verify API (Version 2).
Creates a new template with the provided details.
Create a new template:
const newTemplate = await templateClient.createTemplate({
name: 'My New Template',
});
console.log(newTemplate.name);
Creates a new template fragment with the provided details.
Create a new template fragment:
const newFragment = await templateClient.createTemplateFragment(
'22f571c1-f41a-4db2-bba7-f23a069200c1',
{
channel: 'sms',
locale: 'en-us',
text: 'Your verification code is ${code}',
},
);
console.log(newFragment.text);
Deletes a template by its unique identifier.
Delete a template by ID:
await templateClient.deleteTemplate('22f571c1-f41a-4db2-bba7-f23a069200c1');
console.log('Template deleted successfully');
Deletes a template fragment by its unique identifier.
Delete a template by ID:
await templateClient.deleteTemplateFragment(
'22f571c1-f41a-4db2-bba7-f23a069200c1'
'c70f446e-997a-4313-a081-60a02a31dc19',
);
console.log('Template Fragment deleted successfully');
Retrieves a single template by its unique identifier.
Get a template by ID:
const template = await templateClient.getTemplate('22f571c1-f41a-4db2-bba7-f23a069200c1');
console.log(template.name);
Retrieves a single template fragment by its unique identifier.
Get a template fragment by ID:
const fragment = await templateClient.getTemplateFragment('22f571c1-f41a-4db2-bba7-f23a069200c1', 'c70f446e-997a-4313-a081-60a02a31dc19');
console.log(fragment.text);
Retrieves a page of template fragments based on the provided pagination and filter parameters.
Get a page of template fragments:
const fragmentPage = await templateClient.getTemplateFragmentPage({
templateId: '22f571c1-f41a-4db2-bba7-f23a069200c1',
page: 1,
pageSize: 10,
});
fragmentPage._embedded.template_fragments.forEach(fragment => {
console.log(fragment.text);
});
Retrieves a single page of templates based on the provided pagination parameters.
Get a single page of templates:
const templatePage = await templateClient.getTemplatePage({
page: 1,
pageSize: 10
});
templatePage.templates.forEach(template => {
console.log(template.name);
});
Generator function to list all templates across multiple pages.
List all templates using pagination:
for await (const template of templateClient.listAllTemplateFragments({ pageSize: 5 })) {
console.log(template.name);
}
List all templates without pagination:
for await (const template of templateClient.listAllTemplateFragments()) {
console.log(template.name);
}
Generator function to list all templates across multiple pages.
List all templates using pagination:
for await (const template of templateClient.listAllTemplates({ pageSize: 5 })) {
console.log(template.name);
}
List all templates without pagination:
for await (const template of templateClient.listAllTemplates()) {
console.log(template.name);
}
Updates an existing template with the provided details.
Update a template:
const updatedTemplate = await templateClient.updateTemplate({
templateId: '22f571c1-f41a-4db2-bba7-f23a069200c1',
name: 'Updated Template Name',
isDefault: false,
});
console.log(updatedTemplate.name);
Updates an existing template with the provided details.
Update a template:
const updatedTemplateFragment = await templateClient.updateTemplateFragment(
'22f571c1-f41a-4db2-bba7-f23a069200c1',
{
templateId: '22f571c1-f41a-4db2-bba7-f23a069200c1',
name: 'Updated Template Name',
isDefault: false,
}
);
console.log(updatedTemplateFragment.name);
Video Client for managing and interacting with video-related operations in your application. This client allows you to control sessions, streams, archives, broadcasts, and various video-related features.
Usage:
- Create and manage video sessions with customizable settings.
- Control video streams, including muting, adding, and removing streams.
- Initiate SIP calls and establish WebSockets for real-time communication.
- Enable and disable captions for improved accessibility.
- Start, stop, and manage video archives and broadcasts.
- Render experiences and access detailed information about streams and archives.
- Generate client tokens for secure session connections.
- Perform various video-related operations with ease.
The Video Client is designed to simplify video management tasks within your application. It provides a comprehensive set of methods and options to configure and control video interactions seamlessly.
Create a standalone Video client
import { Video } from '@vonage/video';
const videoClient = new Video({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create an Video client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
const videoClient = vonage.video;
Adds a stream to an existing archive, allowing you to include additional streams in the archive recording.
await videoClient.addArchiveStream(ARCHIVE_ID, STREAM_ID);
Adds a stream to an existing broadcast, allowing you to include additional streams in the live broadcast.
await videoClient.addStreamToBroadcast(BROADCAST_ID, STREAM_ID);
Connects to a WebSocket for a specified session using the provided client token and WebSocket configuration.
const result = await videoClient.connectToWebsocket(
SESSION_ID,
CLIENT_TOKEN,
{
uri: 'wss://example.com',
},
)
console.log(result.id);
Creates a new session with the specified options.
Create a session with default options
const session = await videoClient.createSession({});
console.log(session.sessionId);
Create a session with archive mode set to manual
import { ArchiveMode } from '@vonage/video';
const session = await videoClient.createSession({
archiveMode: ArchiveMode.MANUAL,
});
console.log(session.sessionId);
Create a session with location set to a specific region
const session = await videoClient.createSession({
location: 'eu',
});
console.log(session.sessionId);
Create a session with media mode set to routed
import { MediaMode } from '@vonage/video';
const session = await videoClient.createSession({
mediaMode: MediaMode.ROUTED,
});
console.log(session.sessionId);
Deletes an archive with the specified archive ID.
await videoClient.deleteArchive(ARCHIVE_ID);
Disables captions for a specific caption ID.
await videoClient.disableCaptions(CAPTION_ID);
Disables force mute for a session, allowing audio for all streams.
const forceMute = await videoClient.disableForceMute(SESSION_ID);
console.log(forceMute.status);
Disconnects a client from a session.
await videoClient.disconnectClient(SESSION_ID, CONNECTION_ID);
Disconnects a WebSocket connection associated with a call or session.
await videoClient.disconnectWebsocket(CALL_ID);
Enables captions for a session using the specified client token and caption options.
const result = await videoClient.enableCaptions(SESSION_ID, CLIENT_TOKEN);
console.log(result.captionId);
Forces muting of all streams in a session, except those specified in the
const forceMute = await videoClient.forceMuteAll(SESSION_ID);
console.log(forceMute.status);
Generates a client token for connecting to a session with the specified options.
const token = videoClient.generateClientToken(SESSION_ID);
console.log(`The token is ${token}`);
Retrieves information about a specific archive by its ID.
const archive = await videoClient.getArchive(ARCHIVE_ID);
console.log(archive.createdAt);
Retrieves the status of a caption by its ID.
const captionStatus = await videoClient.getCaptionStatus(CAPTION_ID);
console.log(captionStatus.status);
Retrieves the details of an Experience Composer render by its ID.
const render = await videoClient.getExperienceComposerRender(RENDER_ID);
console.log(render.createdAt);
Retrieves information about one or more streams in a session.
const streamInfo = await videoClient.getStreamInfo(SESSION_ID);
if (streamInfo.items) {
streamInfo.items.forEach((item) => {
console.log(item.id);
});
} else {
console.log(streamInfo.id);
}
Initiates a SIP call within a session.
Start a SIP call with default options
const sipCall = await videoClient.intiateSIPCall(SESSION_ID);
console.log(sipCall.id);
Start a SIP call with custom options
const sipCall = await videoClient.intiateSIPCall(
SESSION_ID,
{
uri: 'sip://example.com',
}
);
console.log(sipCall.id);
Lists Experience Composer renders based on the specified filter criteria.
const renders = await videoClient.listExperienceComposerRenders();
for (const render of renders.items) {
console.log(render.id);
}
Mutes or unmutes all streams in a session, optionally excluding specific stream IDs from muting.
const forceMute = await videoClient.muteAll(SESSION_ID);
console.log(forceMute.status);
Mutes or unmutes a specific stream in a session.
const forceMute = await videoClient.muteStream(SESSION_ID, STREAM_ID);
console.log(forceMute.status);
Sends DTMF (Dual-Tone Multi-Frequency) tones to a specific session or connection.
await videoClient.playDTMF(SESSION_ID, '1234');
Removes a stream from an archive.
await videoClient.removeArchiveStream(ARCHIVE_ID, STREAM_ID);
Removes a stream from a broadcast.
await videoClient.removeStreamFromBroadcast(BROADCAST_ID, STREAM_ID);
Searches for archives based on the specified filter criteria.
const archives = await videoClient.searchArchives();
for (const archive of archives.items) {
console.log(archive.id);
}
Search for archives for a session
const archives = await videoClient.searchArchives({
sessionId: SESSION_ID,
});
for (const archive of archives.items) {
console.log(archive.id);
}
Searches for broadcasts based on the specified filter criteria.
const broadcasts = await videoClient.searchBroadcasts();
for (const broadcast of broadcasts.items) {
console.log(broadcast.id);
}
Get braodcasts for a session
const broadcasts = await videoClient.searchBroadcasts({
sessionId: SESSION_ID,
})
for (const broadcast of broadcasts.items) {
console.log(broadcast.id);
}
Sends a signal to a session or a specific connection within a session.
await videoClient.sendSignal(
{
type: 'text',
data: 'Hello world!',
},
SESSION_ID,
);
#### setStreamClassLists
Sets the stream class lists for one or more streams within a session.
```ts
await videoClient.setStreamClassLists(
SESSION_ID,
[
{
id: STREAM_ID,
layoutClassList: ['full'],
}
]
)
Starts an archive for a given session with optional configuration.
const archive = await videoClient.startArchive(SESSION_ID);
console.log(archive.id);
Starts a broadcast for a given session with the specified configuration.
const broadcast = await videoClient.startBroadcast(
SESSION_ID,
{
outputs: {
hls: {
lowLatency: true,
}
rtmp: [{
serverUrl: 'rtmp://example.com',
}],
}
}
);
Starts rendering an experience composer with the provided configuration.
const render = await videoClient.startExperienceComposerRender(
SESSION_ID,
token,
)
console.log(render.id);
Stops an archive with the given archive ID.
const archive = await videoClient.stopArchive(ARCHIVE_ID);
console.log(archive.status);
Stops a broadcast with the given broadcast ID.
const broadcast = await videoClient.stopBroadcast(BROADCAST_ID);
console.log(broadcast.status);
Stops an Experience Composer render with the given render ID.
await videoClient.stopExperienceComposerRender(RENDER_ID);
Updates the layout of an archive with the given archive ID.
await videoClient.updateArchiveLayout(
Updates the configuration of a broadcast with the given broadcast ID.
await videoClient.updateBroadcast({
broadcastId: BROADCAST_ID,
hasAudio: true,
})
A Clint to make calls to the Vonage Voice API.
Vonage API's will return information using
snake_case
. This represents the
pure response before the client will transform the keys into
camelCase
.
Create a standalone Voice client
import { Voice } from '@vonage/voice';
const voiceClient = new Voice({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
Create an Voice client from the Vonage client
import { Vonage } from '@vonage/server-client';
const vonage = new Vonage({
apiKey: VONAGE_API_KEY,
apiSecret: VONAGE_API_SECRET
});
const voiceClient = vonage.voice;
Send a call action to a specific call identified by its UUID.
await voiceClient.callAction(CALL_UUID, 'mute');
Initiates an outbound call with the specified configuration.
Create a call with answer NCCO
const call = await voiceClient.createOutboundCall({
to: [{
type: 'phone',
number: TO_NUMBER
}],
asnwer_url: ['https://example.com/answer'],
});
console.log(call.uuid);
Create a call with answer URL
const call = await voiceClient.createOutboundCall({
to: [{
type: 'phone',
number: TO_NUMBER
}],
ncco: [{
action: 'talk',
text: 'This is a text to speech call from Vonage'
}]
});
console.log(call.uuid);
Download the recording of a call to the specified file path.
await voiceClient.downloadRecording(RECORDING_UUID, './recording.mp3');
Download the transcription of a call to the specified file path.
await voiceClient.downloadTranscription(TRANSCRIPTION_UUID, './transcription.txt');
Places a call on earmuff, muting the audio for all participants except the user.
await voiceClient.earmuffCall(CALL_UUID);
Retrieves details of all calls using pagination.
for await (const call of voiceClient.getAllCalls()) {
console.log(call.startTime);
}
Retrieves detailed information about a specific call using its UUID.
const call = await voiceClient.getCall('CALL_UUID');
console.log(call.startTime);
Retrieves a page of call details based on the specified parameters.
const page = await voiceClient.getCallsPage();
for (const call of page._embedded.calls) {
console.log(call.startTime);
}
Get the next page of call details
const page = await voiceClient.getCallsPage({
pageSize: 4,
recordIndex: 10,
});
for (const call of page._embedded.calls) {
console.log(call.startTime);
}
Get all started calls
import { CallStatus } from '@vonage/voice';
const page = await voiceClient.getCallsPage({
pageSize: 4,
recordIndex: 10,
status: CallStatus.STARTED,
});
for (const call of page._embedded.calls) {
console.log(call.startTime);
}
Hang up an active call.
await voiceClient.hangupCall(CALL_UUID);
Mute an active call.
await voiceClient.muteCall(CALL_UUID);
Plays DTMF (Dual-Tone Multi-Frequency) tones on an active call.
const result = await voiceClient.playDTMF('CALL_UUID', '1234');
console.log(result.status);
Plays text-to-speech (TTS) audio on an active call.
const result = await voiceClient.playTTS(
CALL_UUID,
{
text: 'This is a text to speech call from Vonage',
},
);
console.log(result.status);
Searches for call details based on the provided filter.
const page = await voiceClient.search({
pageSize: 4,
});
for (const call of page._embedded.calls) {
console.log(call.startTime);
console.log(call.status);
console.log(call.direction);
console.log(call.duration);
};
Stop streaming audio to an active call.
const result = await voiceClient.stopStreamAudio(CALL_UUID);
console.log(result.message);
Stops any ongoing text-to-speech (TTS) audio playback on an active call.
const result = await voiceClient.stopTTS(CALL_UUID);
console.log(result.status);
Stream audio to an active call, allowing you to play audio files or live audio streams.
const result = await voiceClient.streamAudio(CALL_UUID, 'https://example.com/audio.mp3');
console.log(result.message);
Register a listener to receive asynchronous DTMF inputs from a call
This is only applicable to Input NCCO events with the mode set to asynchronous. The payload delivered to this URL will be an Input webhook event with a single DTMF digit every time the callee enters DTMF into the call.
const result = await voiceClient.subscribeDTMF('CALL_UUID', 'https://example.com/dtmf');
console.log(result.status);
Transfer an active call to a new destination using a Nexmo Call Control Object (NCCO).
await voiceClient.transferCallWithNCCO(
CALL_UUID,
[{
action: 'talk',
text: 'You will now be transferred to a new destination''
}],
)
Transfer an active call to a new destination using a URL.
await voiceClient.transferCallWithURL(
CALL_UUID,
'https://example.com/transfer',
);
Remove an earmuff from a call, allowing all participants to hear each other again.
await voiceClient.unearmuffCall(CALL_UUID);
Unmute a muted call, allowing audio to be transmitted again.
await voiceClient.unmuteCall(CALL_UUID);
Removes the registered DTMF listener
const result = await voiceClient.subscribeDTMF('CALL_UUID', 'https://example.com/dtmf');
console.log(result.status);