# Sinch Node.js SDK for Verification API The Sinch Node.js SDK allows you to quickly interact with the 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 are structured similarly to those that are sent and received using the . The fastest way to get started with the SDK is to check out our [getting started](/docs/verification/getting-started/node-sdk/sms-verification) guides. There you'll find all the instructions necessary to download, install, set up, and start using the SDK. ## Syntax Note: 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](/docs/verification/api-reference/verification). 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. SDK verificationSample.js // 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} */ 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} 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} 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} 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} */ 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; } } } REST API ```javascript const axios = require('axios'); const APPLICATION_KEY = ""; const APPLICATION_SECRET = ""; const TO_NUMBER = ""; const SINCH_URL = "https://verification.api.sinch.com/verification/v1/verifications"; const basicAuthentication = APPLICATION_KEY + ":" + APPLICATION_SECRET; const payload = { identity: { type: 'number', endpoint: TO_NUMBER }, method: 'sms' }; const headers = { 'Authorization': 'Basic ' + Buffer.from(basicAuthentication).toString('base64'), 'Content-Type': 'application/json; charset=utf-8' }; axios.post(SINCH_URL, payload, { headers }) .then(response => console.log(response.data) ).catch(error => console.error('There was an error!', error) ); ``` This example highlights the following required to successfully make a Verification API call using the Sinch Node.js SDK: - [Client initialization](#client) - [Verification domain access](#verification-domain) - [Endpoint usage](#endpoint-categories) - [Field population](#request-and-query-parameters) ## Client 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 To start using the SDK, you need to initialize the main client class with your credentials from your Sinch [dashboard](https://dashboard.sinch.com/dashboard). ```javascript const {SinchClient} = require('@sinch/sdk-core'); const sinchClient = new SinchClient({ applicationKey: "YOUR_application_key", applicationSecret: "YOUR_application_secret" }); ``` Note 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** ```shell APPKEY="YOUR_application_key" APPSECRET="YOUR_application_secret" ``` **`app.js` File** ```javascript const {SinchClient} = require('@sinch/sdk-core'); const sinchClient = new SinchClient({ applicationKey: process.env.APPKEY, applicationSecret: process.env.APPSECRET }); ``` Note 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: ```javascript 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" }); ``` ## Verification domain 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: ```javascript 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](/docs/verification/api-reference/verification/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](/docs/verification/api-reference/verification/verifications-start/startverification) | `startSms()` | | [Start a FlashCall verification request](/docs/verification/api-reference/verification/verifications-start/startverification) | `startFlashCall()` | | [Start a Phone Call verification request](/docs/verification/api-reference/verification/verifications-start/startverification) | `startCallout()` | | [Start a Data verification request](/docs/verification/api-reference/verification/verifications-start/startverification) | `startSeamless()` | | [Report an SMS verification PIN code by the identity of the recipient](/docs/verification/api-reference/verification/verifications-report/reportverificationbyidentity) | `reportSmsByIdentity()` | | [Report a FlashCall verification code (CLI) by the identity of the recipient](/docs/verification/api-reference/verification/verifications-report/reportverificationbyidentity) | `reportFlashCallByIdentity()` | | [Report a Phone Call verification code by the identity of the recipient](/docs/verification/api-reference/verification/verifications-report/reportverificationbyidentity) | `reportByCalloutIdentity()` | | [Report an SMS verification PIN code by the ID of the verification request](/docs/verification/api-reference/verification/verifications-report/reportverificationbyid) | `reportSmsById()` | | [Report a FlashCall verification code (CLI) by the ID of the verification request](/docs/verification/api-reference/verification/verifications-report/reportverificationbyid) | `reportFlashCallById()` | | [Report a Phone Call verification code by the ID of the verification request](/docs/verification/api-reference/verification/verifications-report/reportverificationbyid) | `reportCalloutById()` | The `verification.verificationStatus` category of the Node.js SDK corresponds to the [verifications](/docs/verification/api-reference/verification/verification-status/) 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](/docs/verification/api-reference/verification/verification-status/verificationstatusbyid) | `getById()` | | [Get the status of a verification by the identity of the recipient](/docs/verification/api-reference/verification/verification-status/verificationstatusbyidentity) | `getByIdentity()` | | [Get the status of a verification by a reference value](/docs/verification/api-reference/verification/verification-status/verificationstatusbyreference) | `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. ```javascript const requestData = verificationHelper.buildStartSmsVerificationRequest( "YOUR_phone_number"); ``` | Request body | Helper method name | Parameters | | --- | --- | --- | | Start SMS Verification | `buildStartSmsVerificationRequest()` | `phoneNumber`***required**`reference` | | Start FlashCall Verification | `buildStartFlashCallVerificationRequest()` | `phoneNumber`***required**`reference``dialTimeout` | | Start Callout Verification | `buildStartCalloutVerificationRequest()` | `phoneNumber`***required**`reference` | | Start Data Verification | `buildStartSeamlessVerificationRequest()` | `phoneNumber`***required**`reference` | | Report SMS Verification by ID | `buildReportSmsVerificationByIdRequest()` | `id`***required**`code`***required**`cli` | | Report FlashCall Verification by ID | `buildReportFlashCallVerificationByIdRequest()` | `id`***required**`cli`***required** | | Report Phone Call Verification by ID | `buildReportCalloutVerificationByIdRequest()` | `id`***required**`code`***required** | | Report SMS Verification by Identity | `buildReportSmsVerificationByIdentityRequest()` | `identity`***required**`code`***required**`cli` | | Report FlashCall Verification by Identity | `buildReportFlashCallVerificationByIdentityRequest()` | `identity`***required**`cli`***required** | | Report Phone Call Verification by Identity | `buildReportCalloutVerificationByIdentityRequest()` | `identity`***required**`code`***required** | 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: ```javascript const response = await sinchClient.verification.verificationStatus.getByIdentity({ endpoint: 'PHONE_NUMBER', method: 'sms' }); ``` ```JSON 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.