The Sinch Node.js SDK allows you to quickly interact with the suite of APIs from inside your Node.js applications. When using the Node.js SDK, the code representing requests and queries sent to and responses received from the suite of APIs are structured similarly to those that are sent and received using the suite of APIs.
The following links are available for your reference:
When using the Sinch Node.js SDK, you initialize communication with the Sinch backend by initializing the Node.js SDK's main client class. This client allows you to access the functionality of the Sinch Node.js SDK.
Initialization of the Node.js SDK client can be done in two ways, depending on which product you are using.
Before initializing a client using this SDK, you'll need three pieces of information:
- Your Project ID
- An access key ID
- An access key Secret
These values can be found on the <b>Access Keys</b> page of the Sinch Build Dashboard. You can also create new access key IDs and Secrets, if required.
If you have trouble accessing the above link, ensure that you have gained access to the Conversation API by accepting the corresponding terms and conditions.
To start using the SDK, you need to initialize the main client class with your credentials from your Sinch dashboard.
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
projectId: "YOUR_project_id",
keyId: "YOUR_access_key",
keySecret: "YOUR_access_secret"
});
For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials, as in the following example:
.env
File
PROJECTID="YOUR_project_id"
ACCESSKEY="YOUR_access_key"
ACCESSSECRET="YOUR_access_secret"
app.js
File
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
projectId: process.env.PROJECTID,
keyId: process.env.ACCESSKEY,
keySecret: process.env.ACCESSSECRET
});
If you are using the Node.js SDK for multiple products that use different sets of authentication credentials, you can include all of the relevant credentials in the same configuration object, as in the following example:
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
projectId: "YOUR_project_id",
keyId: "YOUR_access_key",
keySecret: "YOUR_access_secret",
applicationKey: "YOUR_application_key",
applicationSecret: "YOUR_application_secret"
});
To start using the SDK, you need to initialize the main client class with your credentials from your Sinch dashboard.
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
applicationKey: "YOUR_application_key",
applicationSecret: "YOUR_application_secret"
});
For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials, as in the following example:
.env
File
APPKEY="YOUR_application_key"
APPSECRET="YOUR_application_secret"
app.js
File
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
applicationKey: process.env.APPKEY,
applicationSecret: process.env.APPSECRET
});
If you are using the Node.js SDK for multiple products that use different sets of authentication credentials, you can include all of the relevant credentials in the same configuration object, as in the following example:
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
projectId: "YOUR_project_id",
keyId: "YOUR_access_key",
keySecret: "YOUR_access_secret",
applicationKey: "YOUR_application_key",
applicationSecret: "YOUR_application_secret"
});
The Node.js SDK currently supports the following products:
This guide describes the syntactical structure of the Node.js SDK for the Numbers API, including any differences that may exist between the API itself and the SDK. For a full reference on Numbers API calls and responses, see the Numbers API Reference.
The code sample below is an example of how to use the Node.js SDK to list the available numbers given a set of constraints. We've also provided an example that accomplishes the same task using the REST API.
// eslint-disable-next-line no-unused-vars
import { Numbers, NumbersService } from '@sinch/sdk-core';
/** @param {NumbersService} numbersService */
export const execute = async (numbersService) => {
/** @type {Numbers.ListAvailableNumbersRequestData} */
const requestData = {
regionCode: 'US',
type: 'LOCAL',
capabilities: ['SMS', 'VOICE'],
};
const response = await numbersService.availableNumber.list(requestData);
console.log(`Available numbers to rent:\n${JSON.stringify(response, null, 2)}`);
};
This example highlights the following required to successfully make a Numbers API call using the Sinch Node.js SDK:
The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.numbers.[endpoint_category].[method()]
.
In the Sinch Node.js SDK, Numbers API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:
numbers.availableNumber
numbers.activeNumber
numbers.availableRegions
numbers.callbackConfiguration
For example:
var numbers = await sinchClient.numbers.availableNumber.list({
regionCode: 'US',
type: 'LOCAL'
});
The numbers.availableNumber
category of the Node.js SDK corresponds to the availableNumbers endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Rent the first available number matching the provided criteria | rentAny() |
Rent a specified available phone number | rent() |
Search for available phone numbers | list() |
Checks the availability of a specific phone number | checkAvailability() |
The numbers.activeNumber
category of the Node.js SDK corresponds to the activeNumbers endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
List active numbers for a project | list() |
Update active number | update() |
Retrieve active number | get() |
Release active number | release() |
The numbers.availableRegions
category of the Node.js SDK corresponds to the availableRegions endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
List available regions | list() |
The numbers.callbackConfiguration
category of the Node.js SDK corresponds to the callbackConfiguration endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Get callbacks configuration | get() |
Update callback configuration | update() |
Requests and queries made using the Node.js SDK are similar to those made using the Numbers API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.
For example, consider this example in which the get()
method of the numbers.activeNumber
class is invoked:
var numResponse = sinchClient.numbers.activeNumber.get({
phoneNumber: "PHONE_NUMBER"
});
url = "https://numbers.api.sinch.com/v1/projects/" + projectId + "/activeNumbers/" + phoneNumber
When using the Numbers API, projectId
and phoneNumber
would be included as path parameters in the request. With the Node.js SDK, the phoneNumber
parameter is included as an argument in the get()
method.
Response fields match the API responses. They are delivered as JavaScript objects.
This guide describes the syntactical structure of the Node.js SDK for the SMS API, including any differences that may exist between the API itself and the SDK. For a full reference on SMS API calls and responses, see the SMS REST API Reference.
The code sample below is an example of how to use the Node.js SDK to send an SMS message. We've also provided an example that accomplishes the same task using the REST API.
// eslint-disable-next-line no-unused-vars
import { Sms, SmsService } from '@sinch/sdk-core';
/** @param {SmsService} smsService */
export const execute = async (smsService) => {
const from = 'YOUR_sinch_phone_number';
const recipient = 'YOUR_recipient_phone_number';
const body = 'This is a test SMS message using the Sinch Node.js SDK.';
/** @type {Sms.SendSMSRequestData} */
const requestData= {
sendSMSRequestBody: {
type: 'mt_text',
from,
to: [recipient],
body,
},
};
const response = await smsService.batches.send(requestData);
console.log(`Response:\n${JSON.stringify(response, null, 2)}`);
};
The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.sms.[endpoint_category].[method()]
.
In the Sinch Node.js SDK, SMS API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:
sms.batches
sms.deliveryReports
sms.groups
sms.inbounds
For example:
const response = await sinchClient.sms.batches.send({
sendSMSRequestBody: {
to: [
"+13215013855"
],
from: "+12074193397",
body: "This is a test message from the Node.js SDK."
}
});
The sms.batches
category of the Node.js SDK corresponds to the batches endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Send | send() |
List batches | list() |
Dry run | dryRun() |
Get a batch message | get() |
Update a batch message | update() |
Replace a batch | replace() |
Cancel a batch message | cancel() |
Send delivery feedback for a message | sendDeliveryFeedback() |
The sms.deliveryReports
category of the Node.js SDK corresponds to the delivery_report and delivery_reports endpoints. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Retrieve a delivery report | get() |
Retrieve a recipient delivery report | getByPhoneNumber() |
Retrieve a list of delivery reports | list() |
The sms.groups
category of the Node.js SDK corresponds to the groups endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
List groups | list() |
Create a group | create() |
Retrieve a group | get() |
Update a group | update() |
Replace a group | replace() |
Delete a group | delete() |
List group member phone numbers | listMembers() |
The sms.inbounds
category of the Node.js SDK corresponds to the inbounds endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
List incoming messages | list() |
Retrieve inbound message | get() |
Requests and queries made using the Node.js SDK are similar to those made using the SMS API. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.
For example, consider this example in which the get()
method of the sms.batches
class is invoked:
const smsResponse = sinchClient.sms.batches.get({
batch_id: "BATCH_ID"
});
When using the SMS API, service_plan_id
and batch_id
would be included as path parameters in the JSON payload. With the Node.js SDK, the batch_id
parameter is included as an argument in the get()
method.
Note that the service_plan_id
path parameter does not need to be included in any requests created by the Node.js SDK.
Response fields match the API responses. They are delivered as JavaScript objects.
This guide describes the syntactical structure of the Node.js SDK for the Conversation API, including any differences that may exist between the API itself and the SDK. For a full reference on Conversation API calls and responses, see the Conversation REST API Reference.
The code sample below is an example of how to use the Node.js SDK to send a text message on the SMS channel of a Conversation API app. We've also provided an example that accomplishes the same task using the REST API (note that this REST API example would be included in an mjs
instead of a js
file, and it uses Basic Authentication instead of OAuth2).
const { SinchClient } = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
projectId: "YOUR_project_id",
keyId: "YOUR_access_key",
keySecret: "YOUR_access_secret"
});
async function run(){
const response = await sinchClient.conversation.messages.send({
sendMessageRequestBody: {
app_id: "YOUR_app_ID",
recipient: {
identified_by: {
channel_identities: [
{
channel: "SMS",
identity: "RECIPIENT_number"
}
]
}
},
message: {
text_message: {
text: "This is a test message using the Sinch Node.js SDK"
}
},
channel_properties: {
SMS_SENDER: "YOUR_sms_sender"
}
}
});
console.log(JSON.stringify(response));
}
run();
The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.conversation.[endpoint_category].[method()]
.
In the Sinch Node.js SDK, Conversation API endpoints are accessible through the client (either a general client or a Conversation-specific client). The naming convention of the endpoint's representation in the SDK matches the API:
messages
app
contact
events
transcoding
capability
templatesV1
templatesV2
webhooks
conversation
For example:
const response = await sinchClient.conversation.messages.send({
sendMessageRequestBody: {
app_id: "YOUR_app_ID",
recipient: {
identified_by: {
channel_identities: [
{
channel: "SMS",
identity: "RECIPIENT_number"
}
]
}
},
message: {
text_message: {
text: "This is a test message using the Sinch Node.js SDK"
}
},
channel_properties: {
SMS_SENDER: "YOUR_sms_sender"
}
}
});
The messages
category of the Node.js SDK corresponds to the messages endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
Send a message | send , or you could use any of the following message-specific methods: |
sendCardMessage | |
sendCarouselMessage | |
sendChoiceMessage | |
sendContactInfoMessage | |
sendListMessage | |
sendLocationMessage | |
sendMediaMessage | |
sendTemplateMessage | |
sendTextMessage | |
Get a message | get |
Delete a message | delete |
List messages | list |
Update a message's metadata | update |
The app
category of the Node.js SDK corresponds to the apps endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
List all apps for a given project | list |
Create an app | create |
Get an app | get |
Delete an app | delete |
Update an app | update |
The contact
category of the Node.js SDK corresponds to the contacts endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
List contacts | list |
Create a contact | create |
Get a contact | get |
Delete a contact | delete |
Update a contact | update |
Merge two contacts | mergeContact |
Get channel profile | getChannelProfile |
The conversation
category of the Node.js SDK corresponds to the conversations endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
List conversations | list |
Create a conversation | create |
Get a conversation | get |
Delete a conversation | delete |
Update a conversation | update |
Stop conversation | stopActive |
Inject a message | injectMessage |
Inject an event | injectEvent |
List recent conversations | listRecent |
The events
category of the Node.js SDK corresponds to the events endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
Send an event | send , or you could use any of the following message-specific methods: sendComposingEvent , sendComposingEndEvent , sendCommentReplyEvent , sendAgentJoinedEvent , sendAgentLeftEvent , or sendGenericEvent |
Get an event | get |
Delete an event | delete |
List events | list |
The transcoding
category of the Node.js SDK corresponds to the messages:transcode endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
Transcode a message | transcodeMessage |
The capability
category of the Node.js SDK corresponds to the capability endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
Capability lookup | lookup |
The webhooks
category of the Node.js SDK corresponds to the webhooks endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
List webhooks | list |
Create a new webhook | create |
Get a webhook | get |
Update an existing webhook | update |
Delete an existing webhook | delete |
The templatesV1
category of the Node.js SDK corresponds to the Templates endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
List all templates belonging to a project ID | list |
Creates a template | create |
Updates a template | update |
Get a template | get |
Delete a template | delete |
The templatesV2
category of the Node.js SDK corresponds to the Templates-V2 endpoint. The mapping between the API operations and corresponding methods are described below:
API operation | SDK method |
---|---|
List all templates belonging to a project ID | list |
Creates a template | create |
Lists translations for a template | listTranslations |
Updates a template | update |
Get a template | get |
Delete a template | delete |
Requests and queries made using the Node.js SDK are similar to those made using the Conversation API. Many of the fields are named and structured similarly. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.
app_id: "{APP_ID}"
Note that the fields have the same name. Additionally, path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding method. For example, consider this example in which the get
method of the message
class is invoked:
const response = await sinchClient.conversation.messages.get({
message_id:"YOUR_message_id"
messages_source:"CONVERSATION_SOURCE"
});
When using the Conversation API, message_id
would be included as a path parameter, and messages_source
would be included as a query parameter in the JSON payload. With the Node.js SDK, both parameters are included as arguments in the get
method.
Response fields match the API responses. They are delivered as JavaScript objects.
This guide describes the syntactical structure of the Node.js SDK for the Voice API, including any differences that may exist between the API itself and the SDK. For a full reference on Voice API calls and responses, see the Voice API Reference.
The code sample below is an example of how to use the Node.js SDK to make a Text to speech phone call. We've also provided an example that accomplishes the same task using the REST API.
// eslint-disable-next-line no-unused-vars
import { Voice, VoiceService } from '@sinch/sdk-core';
/** @param {VoiceService} voiceService */
export const execute = async (voiceService) => {
const recipientPhoneNumber = 'the_phone_number_to_call';
const callingNumber = 'the_calling_number';
/** @type {Voice.TtsCalloutRequestData} */
const requestData = {
ttsCalloutRequestBody: {
method: 'ttsCallout',
ttsCallout: {
destination: {
type: 'number',
endpoint: recipientPhoneNumber,
},
cli: callingNumber,
locale: 'en-US/male',
text: 'Hello, this is a call from Sinch.',
},
},
};
const response = await voiceService.callouts.tts(requestData);
console.log(`Callout response: \n${JSON.stringify(response, null, 2)}`);
};
This example highlights the following required to successfully make a Voice API call using the Sinch Node.js SDK:
The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.voice.[endpoint_category].[method()]
.
In the Sinch Node.js SDK, Voice API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:
voice.callouts
voice.calls
voice.conferences
voice.applications
For example:
const response = await sinchClient.voice.callouts.tts({
ttsCalloutRequestBody: {
method: 'ttsCallout',
ttsCallout: {
cli: 'YOUR_Sinch_number',
destination: {
type: 'number',
endpoint: 'YOUR_phone_number'
},
text: 'This is a test call from Sinch using the Node.js SDK.'
}
}
});
The voice.callouts
category of the Node.js SDK corresponds corresponds to the callouts endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Makes a Text-to-speech callout | tts() |
Makes a Conference callout | conference() |
Makes a Custom callout | custom() |
The voice.calls
category of the Node.js SDK corresponds corresponds to the calls endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Get information about a call | get() |
Manage call with callLeg | manageWithCallLeg() |
Updates a call in progress | update() |
The voice.conferences
category of the Node.js SDK corresponds corresponds to the conferences endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Get information about a conference | get() |
Manage a conference participant | manageParticipant() |
Remove a participant from a conference | kickParticipant() |
Remove all participants from a conference | kickAll() |
The voice.applications
category of the Node.js SDK corresponds corresponds to the configuration endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Return all the numbers assigned to an application | listNumbers() |
Assign a number or list of numbers to an application | assignNumbers() |
Unassign a number from an application | unassignNumber() |
Return the callback URLs for an application | getCallbackUrls() |
Update the callback URL for an application | updateCallbackUrls() |
Returns information about a number | QueryNumber() |
The Voice API uses call events and SVAML responses to dynamically control calls throughout their life cycle. The Node.js SDK has a number of builder and helper methods designed to aid in quickly constructing the correct SVAML responses for the various call events. The builder and helper methods available and their parameters are described in the example and tables below.
const iceResponse = new Voice.IceSvamletBuilder()
.setAction(Voice.iceActionHelper.hangup())
.addInstruction(Voice.iceInstructionHelper.say('Thank you for calling Sinch! This call will now end.', 'en-US'))
.build();
Call event | Builder method name | Methods |
---|---|---|
Answered Call Event | AceSvamletBuilder() | setAction() or addInstruction() |
Incoming Call Event | IceSvamletBuilder() | setAction() or addInstruction() |
Prompt Input Event | PieSvamletBuilder() | setAction() or addInstruction() |
Using these builder methods you can then build your SVAML responses using the following methods:
Actions:
Helper method name | Action |
---|---|
Voice.aceActionHelper.connectConf | connectConf |
Voice.aceActionHelper.continue | continue |
Voice.aceActionHelper.hangup | hangup |
Voice.aceActionHelper.runMenu | runMenu |
Voice.iceActionHelper.connectConf | connectConf |
Voice.iceActionHelper.connectMxp | connectMxp |
Voice.iceActionHelper.connectPstn | connectPstn |
Voice.iceActionHelper.connectSip | connectSip |
Voice.iceActionHelper.hangup | hangup |
Voice.iceActionHelper.park | park |
Voice.iceActionHelper.runMenu | runMenu |
Voice.pieActionHelper.connectConf | connectConf |
Voice.pieActionHelper.connectSip | connectSip |
Voice.pieActionHelper.continue | continue |
Voice.pieActionHelper.hangup | hangup |
Voice.pieActionHelper.runMenu | runMenu |
Instructions:
Helper method name | Action |
---|---|
Voice.aceActionHelper.playFiles | playFiles |
Voice.aceActionHelper.say | say |
Voice.aceActionHelper.setCookie | setCookie |
Voice.aceActionHelper.startRecording | startRecording |
Voice.iceActionHelper.answer | answer |
Voice.iceActionHelper.playFiles | playFiles |
Voice.iceActionHelper.say | say |
Voice.iceActionHelper.sendDtmf | sendDtmf |
Voice.iceActionHelper.setCookie | setCookie |
Voice.iceActionHelper.startRecording | startRecording |
Voice.pieActionHelper.playFiles | playFiles |
Voice.pieActionHelper.say | say |
Voice.pieActionHelper.sendDtmf | sendDtmf |
Voice.pieActionHelper.setCookie | setCookie |
Voice.pieActionHelper.startRecording | startRecording |
Voice.pieActionHelper.stopRecording | stopRecording |
Requests and queries made using the Node.js SDK are similar to those made using the Voice API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.
For example, consider this example in which the get()
method of the voice.calls
class is invoked:
const response = await sinchClient.voice.calls.get({
callId: 'YOUR_call_id'
});
url = "https://calling.api.sinch.com/calling/v1/calls/id/" + callId
When using the Voice API, callId
would be included as a path parameter in the request. With the Node.js SDK, the callId
parameter is used in an object passed as an argument in the get()
method.
Response fields match the API responses. They are delivered as Javascript objects.
This guide describes the syntactical structure of the Node.js SDK for the Verification API, including any differences that may exist between the API itself and the SDK. For a full reference on Verification API calls and responses, see the Verification API Reference.
The code sample below is an example of how to use the Node.js SDK to initiate an Verification SMS PIN request. We've also provided an example that accomplishes the same task using the REST API.
// eslint-disable-next-line no-unused-vars
import { Verification, VerificationService, VerificationsApi } from '@sinch/sdk-core';
import inquirer from 'inquirer';
/**
* Class to handle a phone number verification using SMS.
*/
export class VerificationSample {
/**
* @param { VerificationService } verificationService - the VerificationService instance from the Sinch SDK containing the API methods.
*/
constructor(verificationService) {
this.verificationService = verificationService;
}
/**
* Starts the verification process by prompting the user for a phone number,
* sending a verification request, asking for the verification code, and reporting it.
* @return {Promise<void>}
*/
async start() {
// Step 1: Ask the phone number to verify
const e164Number = await this.promptPhoneNumber();
try {
// Step 2: Start the phone number verification
const verificationId = await this.startSmsVerification(this.verificationService.verifications, e164Number);
// Step 3: Ask the user for the received verification code
const code = await this.promptSmsCode();
// Step 4: Report the verification code and complete the process
await this.reportSmsVerification(this.verificationService.verifications, code, verificationId);
console.log('Verification successfully completed.');
} catch (error) {
console.error('An error occurred during the verification process:', error);
}
}
/**
* Prompts the user to enter their phone number.
* @return {Promise<string>} The phone number entered by the user.
*/
async promptPhoneNumber() {
const userInput = await inquirer.prompt([
{
type: 'input',
name: 'phoneNumber',
message: 'Enter the phone number you want to verify (E.164 format):',
validate: (input) => input ? true : 'Phone number cannot be empty.',
},
]);
return userInput.phoneNumber;
}
/**
* Sends a request to start SMS verification for a phone number.
* @param {VerificationsApi} verificationStarter - The VerificationsApi instance.
* @param {string} phoneNumber - The phone number to verify.
* @return {Promise<string>} The verification ID if the request is successful.
*/
async startSmsVerification(verificationStarter, phoneNumber) {
console.log(`Sending a verification request to ${phoneNumber}`);
const requestData = Verification.startVerificationHelper.buildSmsRequest(phoneNumber);
try {
const response = await verificationStarter.startSms(requestData);
if (!response.id) {
throw new Error('Verification ID is undefined.');
}
console.log(`Verification started successfully. Verification ID: ${response.id}`);
return response.id;
} catch (error) {
console.error('Failed to start SMS verification:', error);
throw error;
}
}
/**
* Prompts the user to enter the verification code they received.
* @return {Promise<string>} The verification code entered by the user.
*/
async promptSmsCode() {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'code',
message: 'Enter the verification code you received:',
validate: (input) => input ? true : 'Verification code cannot be empty.',
},
]);
return answers.code;
}
/**
* Sends a request to report the verification code for a specific verification ID.
* @param { VerificationsApi } verificationReporter - The VerificationsApi instance.
* @param {string} code - The verification code to report.
* @param {string} id - The verification ID corresponding to the process.
* @return {Promise<void>}
*/
async reportSmsVerification(verificationReporter, code, id) {
const requestData = Verification.reportVerificationByIdHelper.buildSmsRequest(id, code);
try {
const response = await verificationReporter.reportSmsById(requestData);
console.log(`Verification reported successfully. Response status: ${response.status}`);
} catch (error) {
console.error('Failed to report SMS verification:', error);
throw error;
}
}
}
This example highlights the following required to successfully make a Verification API call using the Sinch Node.js SDK:
The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.verification.[endpoint_category].[method()]
.
In the Sinch Node.js SDK, Verification API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:
verification.verifications
verification.verificationStatus
For example:
const startRequestData = verificationsHelper.buildStartSmsVerificationRequest(
"YOUR_phone_number");
const smsVerification = await sinchClient.verification.verifications.startSms(
startRequestData);
The verification.verifications
category of the Node.js SDK corresponds to the verifications start endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Start an SMS PIN verification request | startSms() |
Start a FlashCall verification request | startFlashCall() |
Start a Phone Call verification request | startCallout() |
Start a Data verification request | startSeamless() |
Report an SMS verification PIN code by the identity of the recipient | reportSmsByIdentity() |
Report a FlashCall verification code (CLI) by the identity of the recipient | reportFlashCallByIdentity() |
Report a Phone Call verification code by the identity of the recipient | reportByCalloutIdentity() |
Report an SMS verification PIN code by the ID of the verification request | reportSmsById() |
Report a FlashCall verification code (CLI) by the ID of the verification request | reportFlashCallById() |
Report a Phone Call verification code by the ID of the verification request | reportCalloutById() |
The verification.verificationStatus
category of the Node.js SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
API operation | SDK method |
---|---|
Get the status of a verification by the ID of the verification request | getById() |
Get the status of a verification by the identity of the recipient | getByIdentity() |
Get the status of a verification by a reference value | getByReference() |
The Node.js SDK has a number of helper methods designed to aid in quickly constructing the correct request bodies for the various methods. The helper methods available and their parameters are described in the example and table below.
const requestData = verificationHelper.buildStartSmsVerificationRequest(
"YOUR_phone_number");
Request body | Helper method name | Parameters |
---|---|---|
Start SMS Verification | buildStartSmsVerificationRequest() |
|
Start FlashCall Verification | buildStartFlashCallVerificationRequest() |
|
Start Callout Verification | buildStartCalloutVerificationRequest() |
|
Start Data Verification | buildStartSeamlessVerificationRequest() |
|
Report SMS Verification by ID | buildReportSmsVerificationByIdRequest() |
|
Report FlashCall Verification by ID | buildReportFlashCallVerificationByIdRequest() |
|
Report Phone Call Verification by ID | buildReportCalloutVerificationByIdRequest() |
|
Report SMS Verification by Identity | buildReportSmsVerificationByIdentityRequest() |
|
Report FlashCall Verification by Identity | buildReportFlashCallVerificationByIdentityRequest() |
|
Report Phone Call Verification by Identity | buildReportCalloutVerificationByIdentityRequest() |
|
Requests and queries made using the Node.js SDK are similar to those made using the Verification API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.
For example, consider this example in which the getByIdentity()
method of the verification.verificationStatus
class is invoked:
const response = await sinchClient.verification.verificationStatus.getByIdentity({
endpoint: 'PHONE_NUMBER',
method: 'sms'
});
url = "https://verification.api.sinch.com/verification/v1/verifications/" + method + "/number/" + endpoint
When using the Verification API, method
and endpoint
would be included as path parameters in the request. With the Node.js SDK, the method
and endpoint
parameters are used in an object passed as an argument in the getByIdentity()
method.
Response fields match the API responses. They are delivered as JavaScript objects.
For operations that return multiple pages of objects, such as list operations, the API response that would normally be an array is instead wrapped inside an ApiPromiseList
object. This object can take two forms, depending on how you have made the call:
If you are using a traditional await
in front of the method, the ApiPromiseList
will take the form of a PageResult
, as demonstrated by the following example:
const requestData: ListActiveNumbersRequestData = {
regionCode: 'US',
type: 'LOCAL',
pageSize: 2,
};
// This call will return the data of the current page wrapped in a PageResult
// We can then loop on the response while it has more pages
let response: PageResult<ActiveNumber> = await sinchClient.numbers.activeNumber.list(requestData);
// The ActiveNumber are in the `data` property
let activeNumbers: ActiveNumber[] = response.data;
console.log(activeNumbers); // prints the content of a page
The array is contained in the data
field and the object contains a hasNextPage
boolean as well as a nextPage()
function which can be used to iterate through the results.
// Loop on all the pages to get all the active numbers
let reachedEndOfPages = false;
while (!reachedEndOfPages) {
if (response.hasNextPage) {
response = await response.nextPage();
activeNumbers = response.data;
console.log(activeNumbers); // prints the content of a page
} else {
reachedEndOfPages = true;
}
}
Each call to the Sinch servers is visible in the code in the while
loop.
If you using an iterator (for await (... of ...)
), the ApiPromiseList
will take the form of a AsyncIteratorIterable
object which can be used to iterate through the results, as demonstrated by the following example:
const requestData: ListActiveNumbersRequestData = {
regionCode: 'US',
type: 'LOCAL',
pageSize: 2,
};
for await (const activeNumber of sinchClient.numbers.activeNumber.list(requestData)) {
console.log(activeNumber); // prints a single ActiveNumber
}
With the iterator, the code is more concise but you have less control over the number of calls made to the API; the iterator will continue to make calls to the API to fetch the next page until the final page is returned.