### Setup Function for Initialization and WebSockets Source: https://developers.sinch.com/docs/functions/functions/runtimes/nodejs.md Export a setup() function to perform initialization tasks before the server starts accepting requests or to register WebSocket endpoints. This allows for tasks like creating tables, warming caches, or opening connections. ```typescript import type { SinchRuntime, FunctionContext } from '@sinch/functions-runtime'; export function setup(runtime: SinchRuntime) { runtime.onStartup(async (context: FunctionContext) => { // Create tables, warm caches, open connections }); runtime.onWebSocket('/stream', (ws, req) => { ws.on('message', (data) => { /* audio frames */ }); }); } ``` -------------------------------- ### Minimal Gemini Agent Example Source: https://developers.sinch.com/docs/est/integration-guides/livekit.md A basic Python agent setup for LiveKit using Google's Gemini model for a concise phone assistant. This example demonstrates agent initialization, session management, and generating an initial reply. ```env LIVEKIT_URL=ws://YOUR_LIVEKIT_HOST:7880 LIVEKIT_API_KEY=devkey LIVEKIT_API_SECRET=devsecretdevsecretdevsecretdevsec GOOGLE_API_KEY=YOUR_GOOGLE_API_KEY ``` ```text livekit-agents[google]~=1.5 python-dotenv>=1.0,<2.0 ``` ```python from livekit import agents from livekit.agents import Agent, AgentServer, AgentSession, JobContext from livekit.plugins import google class InboundAssistant(Agent): def __init__(self) -> None: super().__init__(instructions="You are a concise phone assistant.") server = AgentServer() @server.rtc_session(agent_name="inbound-agent") async def inbound_agent(ctx: JobContext) -> None: session = AgentSession( llm=google.realtime.RealtimeModel( model="gemini-2.5-flash-native-audio-preview-12-2025", voice="Puck", instructions="Greet the caller and confirm audio is working.", ), ) await session.start(room=ctx.room, agent=InboundAssistant()) await session.generate_reply( instructions="Answer the call and ask whether the caller can hear you." ) if __name__ == "__main__": agents.cli.run_app(server) ``` -------------------------------- ### Start Gradle Application Source: https://developers.sinch.com/docs/fax/getting-started/java/receive-fax.md Use this command to start your Java application server. ```shell gradle run ``` -------------------------------- ### Start and Report SMS Verification Source: https://developers.sinch.com/docs/sdks/java.md This example shows how to start an SMS verification for a given phone number and then report the received code. It includes prompts for user input and basic error handling for API calls. ```java package verification; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.utils.StringUtil; import com.sinch.sdk.domains.verification.api.v1.*; import com.sinch.sdk.domains.verification.models.v1.NumberIdentity; import com.sinch.sdk.domains.verification.models.v1.report.request.VerificationReportRequestSms; import com.sinch.sdk.domains.verification.models.v1.report.response.VerificationReportResponseSms; import com.sinch.sdk.domains.verification.models.v1.start.request.VerificationStartRequestSms; import com.sinch.sdk.domains.verification.models.v1.start.response.VerificationStartResponseSms; import com.sinch.sdk.models.E164PhoneNumber; import java.util.Scanner; public class VerificationsSample { private final VerificationService verificationService; public VerificationsSample(VerificationService verificationService) { this.verificationService = verificationService; } public void start() { E164PhoneNumber e164Number = promptPhoneNumber(); try { // Starting verification onto phone number String id = startSmsVerification(verificationService.verificationStart(), e164Number); // Ask user for received code Integer code = promptSmsCode(); // Submit the verification report reportSmsVerification(verificationService.verificationReport(), code, id); } catch (ApiException e) { echo("Error (%d): %s", e.getCode(), e.getMessage()); } } /** * Will start an SMS verification onto specified phone number * * @param service Verification Start service * @param phoneNumber Destination phone number * @return Verification ID */ private String startSmsVerification( VerificationsStartService service, E164PhoneNumber phoneNumber) { echo("Sending verification request onto '%s'", phoneNumber.stringValue()); VerificationStartRequestSms parameters = VerificationStartRequestSms.builder() .setIdentity(NumberIdentity.valueOf(phoneNumber)) .build(); VerificationStartResponseSms response = service.startSms(parameters); echo("Verification started with ID '%s'", response.getId()); return response.getId(); } /** * Will use Sinch product to retrieve verification report by ID * * @param service Verification Report service * @param code Code received by SMS * @param id Verification ID related to the verification */ private void reportSmsVerification(VerificationsReportService service, Integer code, String id) { VerificationReportRequestSms parameters = VerificationReportRequestSms.builder().setCode(String.valueOf(code)).build(); echo("Requesting report for '%s'", id); VerificationReportResponseSms response = service.reportSmsById(id, parameters); echo("Report response: %s", response); } /** * Prompt user for a valid phone number * * @return Phone number value */ private E164PhoneNumber promptPhoneNumber() { String input; boolean valid; do { input = prompt("\nEnter a phone number to start verification"); valid = E164PhoneNumber.validate(input); if (!valid) { echo("Invalid number '%s'", input); } } while (!valid); return E164PhoneNumber.valueOf(input); } /** * Prompt user for a SMS code * * @return Value entered by user */ private Integer promptSmsCode() { Integer code = null; do { String input = prompt("Enter the verification code to report the verification"); try { code = Integer.valueOf(input); } catch (NumberFormatException nfe) { echo("Invalid value '%s' (code should be numeric)", input); } } while (null == code); return code; } /** * Endless loop for user input until a valid string is entered or 'Q' to quit * * @param prompt Prompt to be used task user a value * @return The entered text from user */ private String prompt(String prompt) { String input = null; Scanner scanner = new Scanner(System.in); while (StringUtil.isEmpty(input)) { System.out.println(prompt + " ([Q] to quit): "); input = scanner.nextLine(); } if ("Q".equalsIgnoreCase(input)) { System.out.println("Quit application"); System.exit(0); } return input.trim(); } private void echo(String text, Object... args) { System.out.println(" " + String.format(text, args)); } } ``` -------------------------------- ### Install Flask Source: https://developers.sinch.com/docs/sms/tutorials/python-sdk/appointment-reminder/set-up.md Install the Flask web framework using pip. ```shell pip install flask ``` -------------------------------- ### Start Node.js Server Source: https://developers.sinch.com/docs/conversation/getting-started.md Execute this command in your terminal to start the Node.js web server. ```shell node index.js ``` -------------------------------- ### Get Message SDK Example Source: https://developers.sinch.com/docs/conversation/sdk/node/syntax-reference.md Example of invoking the 'get' method for messages using the Node.js SDK. Both message_id (path parameter) and messages_source (query parameter) are passed as arguments. ```javascript const response = await sinchClient.conversation.messages.get({ message_id:"YOUR_message_id" messages_source:"CONVERSATION_SOURCE" }); ``` -------------------------------- ### Node.js setup() function for startup and WebSockets Source: https://developers.sinch.com/docs/functions/functions/concepts/handlers.md Use the `setup()` function to perform one-time initialization tasks before server requests and to register WebSocket endpoints. The `SinchRuntime` provides `onStartup` and `onWebSocket` methods for these purposes. ```typescript import type { SinchRuntime, FunctionContext } from '@sinch/functions-runtime'; export function setup(runtime: SinchRuntime) { runtime.onStartup(async (context: FunctionContext) => { // Create tables, seed data, warm caches }); runtime.onWebSocket('/stream', (ws, req) => { ws.on('message', (data) => { // Handle binary audio frames }); }); } ``` -------------------------------- ### getMMSTemplates Failure Response Example Source: https://developers.sinch.com/docs/mms/xml-service/getmmstemplates.md This is an example of a failed response from the getMMSTemplates API, indicating an invalid start date. ```xml Failure E214 start-date is invalid ``` -------------------------------- ### Install Project Dependencies Source: https://developers.sinch.com/docs/functions/functions/your-first-function.md After initializing the project, navigate into the project directory and install the necessary Node.js dependencies using npm. ```bash cd my-first-function npm install ``` -------------------------------- ### getMMSTemplates Request Example Source: https://developers.sinch.com/docs/mms/xml-service/getmmstemplates.md This is an example of a request to the getMMSTemplates API, specifying a start date, page number, and items per page. ```xml getMMSTemplates qTFkykO9JTfahCOqJ0V2Wf5Cg1t8iWlZ 2014-03-31T11:30:00+00:00 1 3 ``` -------------------------------- ### SVAML with StartRecording Instruction Source: https://developers.sinch.com/docs/voice/api-reference/recording.md This example shows how to use StartRecording within SVAML to begin recording after a specific instruction, like a Say instruction. ```json { "instructions": [{ "name": "Say", "text": "Hello world, I don't want you to record this part", "locale": "en-US" }, { "name": "StartRecording", "options": [...] }, { "name": "Say", "text": "Hello world, this part will be recorded", "locale": "en-US" }], "action": { ... } } ``` -------------------------------- ### Install Sinch CLI Source: https://developers.sinch.com/docs/functions/cli/installation.md Installs the Sinch CLI globally using npm. This command handles PATH setup and shell completions automatically. ```bash npm install -g @sinch/cli ``` -------------------------------- ### Handle Chat Start Result Source: https://developers.sinch.com/docs/sinch-chat/getting-started/android/showing-chat.md Example of calling the start method and checking the result for potential failures. This code should be placed after checking chat availability. ```kotlin do { val result = SinchChatSDK.chat.start(this) if (result.isFailure) { // do some things. } ``` -------------------------------- ### CommonVerificationInitializationParameters Setup Source: https://developers.sinch.com/docs/verification/ios/ios-commonmodule.md Collects `Verification` instance properties and works with `VerificationInitData` to initialize the verification process. This is useful for setting up global configurations and listeners for verification. ```swift private var commonConfig: CommonVerificationInitializationParameters { return CommonVerificationInitializationParameters( globalConfig: self.globalConfig, verificationInitData: self.initData, initalizationListener: self, verificationListener: self ) } ``` -------------------------------- ### Conversation Start Callback Example Source: https://developers.sinch.com/docs/conversation/callbacks.md This JSON object represents a callback received when a new conversation is initiated in CONVERSATION mode. It contains details about the application, project, and the started conversation. ```json { "app_id": "01EB37HMH1M6SV18ASNS3G135H", "project_id": "c36f3d3d-1523-4edd-ae42-11995557ff61", "conversation_start_notification": { "conversation": { "id": "01EQ4174WMDB8008EFT4M30481", "app_id": "01EB37HMH1M6SF18ASNS3G135H", "contact_id": "01BQ8174TGGY5B1VPTPGHW19R0", "active_channel": "MESSENGER", "active": true, "metadata": "" } } } ``` -------------------------------- ### Install Flask and Requests Source: https://developers.sinch.com/docs/sms/getting-started/python/receive-sms-sdk.md Install the Flask web framework and the Requests library for making HTTP calls. These are necessary for handling callbacks. ```shell pip install Flask ``` ```shell pip install requests ``` -------------------------------- ### Product List Message Payload Example Source: https://developers.sinch.com/docs/conversation/message-types/list-message.md This JSON payload is a structural example for sending a product list message. Ensure you replace placeholders like {APP_ID}, {CHANNEL}, {IDENTITY}, and IDs with actual values from your setup. The details in this example should not be used in a live API call. ```json { "app_id": "{APP_ID}", "recipient": { "identified_by": { "channel_identities": [ { "channel": "{CHANNEL}", "identity": "{IDENTITY}" } ] } }, "message": { "list_message": { "title": "Title for the list message with products", "description": "Description (or subtitle) for list message with products", "sections": [ { "title": "Facebook product catalog item set name", "items": [ { "product": { "id": "product_1_id", "marketplace": "FACEBOOK" } }, { "product": { "id": "product_2_id", "marketplace": "FACEBOOK" } } ] } ], "message_properties": { "catalog_id": "id_of_catalog" } } } } ``` -------------------------------- ### Initialize Sinch Client and Web Server Source: https://developers.sinch.com/docs/sms/tutorials/node-sdk/user-consent/create-app.md Imports necessary SDK modules and web server framework. Initializes the Sinch client with project credentials and sets up the server port. ```javascript const { SinchClient, SmsRegion } = require("@sinch/sdk-core"); const fastify = require("fastify")(); const portAddr = 3000; const sinchClient = new SinchClient({ projectId: "YOUR_project_id", keyId: "YOUR_access_key", keySecret: "YOUR_access_secret", region: "us/eu", }); let group; let autoReply; ``` -------------------------------- ### Pseudocode Example for Callback Signing Source: https://developers.sinch.com/docs/verification/api-reference/authentication/callback-signed-request.md Illustrates the step-by-step generation of the MD5 hash, StringToSign, Signature, and the final Authorization header. ```shell ApplicationKey = 669E367E-6BBA-48AB-AF15-266871C28135 ApplicationSecret = BeIukql3pTKJ8RGL5zo0DA== Body { "id":"1234567890", "event":"VerificationResultEvent", "method": "sms", "identity": { "type": "number", "endpoint": "+11235551234" }, "status": "PENDING", "reason": "“Fraud”", "reference": "12345", "source": "intercept", "custom": "string" } Request-Body-Content-MD5 = Base64 ( MD5 ( [BODY] ) ) REWF+X220L4/Gw1spXOU7g== StringToSign POST REWF+X220L4/Gw1spXOU7g== application/json x-timestamp:2014-09-24T10:59:41Z /sinch/callback/result Signature = Base64 ( HMAC-SHA256 ( Base64-Decode( ApplicationSecret ), UTF8 ( StringToSign ) ) ) Tg6fMyo8mj9pYfWQ9ssbx3Tc1BNC87IEygAfLbJqZb4= HTTP Authorization Header Authorization: Application 669E367E-6BBA-48AB-AF15-266871C28135:Tg6fMyo8mj9pYfWQ9ssbx3Tc1BNC87IEygAfLbJqZb4= ``` -------------------------------- ### Get Channel Profile Request Source: https://developers.sinch.com/docs/conversation/api-reference/conversation/tag/Contact Example cURL request to get a user's channel profile. Ensure you replace placeholders like {APP_ID} and {project_id} with your actual values. Authentication is done via basic or OAuth2. ```curl curl -i -X POST \ -u : \ 'https://us.conversation.api.sinch.com/v1/projects/{project_id}/contacts:getChannelProfile' \ -H 'Content-Type: application/json' \ -d '{ "app_id": "{APP_ID}", "recipient": { "identified_by": { "channel_identities": [ { "channel": "WHATSAPP", "identity": "string" } ] } }, "channel": "MESSENGER" }' ``` -------------------------------- ### Create App Source: https://developers.sinch.com/docs/conversation/api-reference/conversation/tag/App This example demonstrates how to create a new app and configure channel credentials using a cURL request. It shows how to set up Messenger credentials with a static token and provide a display name for the app. ```APIDOC ## POST /v1/projects/{project_id}/apps ### Description Creates a new app within a specified project. This allows you to configure channels and settings for your conversational applications. ### Method POST ### Endpoint /v1/projects/{project_id}/apps ### Parameters #### Path Parameters - **project_id** (string) - Required - The ID of the project to create the app in. #### Request Body - **channel_credentials** (array) - Required - An array of channel credentials. Each object specifies the channel and its authentication details (e.g., static token). - **channel** (string) - Required - The messaging channel (e.g., "MESSENGER"). - **static_token** (object) - Required - Object containing the static token for the channel. - **token** (string) - Required - The token for the channel. - **display_name** (string) - Required - The display name for the app. ### Request Example ```json { "channel_credentials": [ { "channel": "MESSENGER", "static_token": { "token": "{Facebook_Token}" } } ], "display_name": "Demo Facebook App" } ``` ### Response #### Success Response (200) - **channel_credentials** (array) - Array of channel credentials configured for the app. - **conversation_metadata_report_view** (string) - Enum: NONE, FULL - Specifies whether to include metadata for conversations. Defaults to "NONE". - **display_name** (string) - The display name of the app. - **id** (string) - The unique ID of the created app. - **rate_limits** (object) - Object detailing rate limits for the app. - **retention_policy** (object) - Object defining the retention policy for messages and conversations. - **dispatch_retention_policy** (object) - Object defining the retention policy for messages in Dispatch Mode. - **processing_mode** (string) - Enum: CONVERSATION, DISPATCH - The processing mode for the app. Defaults to "DISPATCH". - **smart_conversation** (object) - Object for Smart Conversations features. - **queue_stats** (object) - Object containing queue statistics. - **callback_settings** (object) - Object with additional settings for callback processing. - **delivery_report_based_fallback** (object) - Object with settings for delivery report based fallback (paid functionality). - **message_retry_settings** (object) - Object with settings for message retry mechanism. #### Response Example ```json { "channel_credentials": [ { "channel": "MESSENGER", "static_token": { "token": "{Facebook_Token}" } } ], "conversation_metadata_report_view": "NONE", "display_name": "Demo Facebook App", "id": "{APP_ID}", "rate_limits": { "inbound": 0, "outbound": 0, "webhooks": 0 }, "retention_policy": { "retention_type": "MESSAGE_EXPIRE_POLICY", "ttl_days": 180 }, "dispatch_retention_policy": { "retention_type": "MESSAGE_EXPIRE_POLICY", "ttl_days": 0 }, "processing_mode": "CONVERSATION", "smart_conversation": { "enabled": false }, "queue_stats": { "outbound_size": 0, "outbound_limit": 0 }, "callback_settings": { "secret_for_overridden_callback_urls": "pa$$word" }, "delivery_report_based_fallback": { "enabled": false, "delivery_report_waiting_time": 10 }, "message_retry_settings": { "retry_duration": 3600 } } ``` ``` -------------------------------- ### Start Web Server with Maven Source: https://developers.sinch.com/docs/conversation/getting-started.md Use this command to start your Spring Boot application. Ensure your application.yaml is configured with Sinch credentials and region. ```shell mvn clean spring-boot:run ``` -------------------------------- ### Initialize Sinch Client and Load Environment Variables Source: https://developers.sinch.com/docs/sms/tutorials/node-sdk/appointment-reminder/create-app.md This code sets up the necessary modules, loads environment variables including Sinch credentials, and initializes the SinchClient for use in the application. ```javascript const express = require("express"); const router = express.Router(); const { DateTime } = require("luxon"); const sessionStorage = require("sessionstorage-for-nodejs"); const { SinchClient } = require("@sinch/sdk-core"); const dotenv = require("dotenv"); dotenv.config(); const sinchClient = new SinchClient({ projectId: process.env.PROJECT_ID, keyId: process.env.KEY_ID, keySecret: process.env.KEY_SECRET, region: process.env.SMS_REGION, }); ``` -------------------------------- ### GET /v1/projects/{projectId}/availableNumbers/{phoneNumber} Source: https://developers.sinch.com/docs/numbers/api-reference/numbers/available-number/numberservice_getavailablenumber.md Search for a specific phone number to check its availability, capability, setup costs, and monthly costs. ```APIDOC ## GET /v1/projects/{projectId}/availableNumbers/{phoneNumber} ### Description This endpoint allows you to enter a specific phone number to check if it's available for use. A 200 response will return the number's capability, setup costs, monthly costs and if supporting documentation is required. ### Method GET ### Endpoint /v1/projects/{projectId}/availableNumbers/{phoneNumber} ### Parameters #### Path Parameters - **projectId** (string) - Required - Found on your Sinch Customer Dashboard. Settings > Projects. Example: "YOUR_projectId" - **phoneNumber** (string) - Required - Output only. The phone number in E.164 format with leading +. Example: "+12025550134" ### Response #### Success Response (200) - **phoneNumber** (string) - The phone number in E.164 format with leading +. Example: "+12025550134" - **regionCode** (string) - ISO 3166-1 alpha-2 country code of the phone number. Example: "US" - **type** (string) - The number type. Enum: "MOBILE", "LOCAL", "TOLL_FREE" - **capability** (array) - The capability of the number. Enum: "SMS", "VOICE" - **setupPrice** (object) - An object giving details on currency code and the amount charged. - **setupPrice.currencyCode** (string) - The 3-letter currency code defined in ISO 4217. Example: "USD" - **setupPrice.amount** (string) - The amount in decimal form. Example: "2.00" - **monthlyPrice** (object) - An object giving details on currency code and the amount charged. - **paymentIntervalMonths** (integer) - How often the recurring price is charged in months. - **supportingDocumentationRequired** (boolean) - Whether or not supplementary documentation will be required to complete the number rental. #### Error Response (400) - **error** (object) - **error.code** (integer) - Enum: 400 - **error.message** (string) - **error.status** (string) - Enum: "INVALID_ARGUMENT" - **error.details** (array) - **error.details.type** (string) - Enum: "BadRequest" - **error.details.fieldViolations** (array) - **error.details.fieldViolations.field** (string) - **error.details.fieldViolations.description** (string) #### Error Response (404) - **error** (object) - **error.code** (integer) - Enum: 404 - **error.message** (string) - **error.status** (string) - Enum: "NOT_FOUND" - **error.details** (array) - **error.details.type** (string) - **error.details.resourceType** (string) - The type of the resource that was not found. - **error.details.resourceName** (string) - The name of the resource that was not found. - **error.details.owner** (string) - The owner of the resource that was not found. - **error.details.description** (string) - A description of the error. #### Error Response (500) - **error** (object) - **error.code** (integer) - Enum: 500 - **error.message** (string) - **error.status** (string) - Enum: "INTERNAL", "UNKNOWN" - **error.details** (array) ``` -------------------------------- ### Initialize Java Project with Gradle Source: https://developers.sinch.com/docs/sms/getting-started/java/send-sms.md Use this command to create a new Java project with Gradle. Select 'application' and accept default values. ```shell gradle init ``` -------------------------------- ### Custom HTTP Endpoints Source: https://developers.sinch.com/docs/functions/functions/runtimes/csharp.md Extend `SinchController` to create custom REST endpoints. This example shows GET and POST methods for status and user creation. ```APIDOC ## GET /api/status ### Description Retrieves the current status of the service. ### Method GET ### Endpoint /api/status ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The status of the service, e.g., "healthy" #### Response Example ```json { "status": "healthy" } ``` ## POST /api/users ### Description Creates a new user and stores their information in the cache for a specified duration. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **req** (CreateUserRequest) - Required - The user data to create. - **Id** (string) - Required - The unique identifier for the user. ### Request Example ```json { "Id": "user123" } ``` ### Response #### Success Response (200) - **req** (CreateUserRequest) - The created user object. - **Id** (string) - The unique identifier for the user. #### Response Example ```json { "Id": "user123" } ``` ``` -------------------------------- ### Get Channel Profile Response Source: https://developers.sinch.com/docs/conversation/api-reference/conversation/tag/Contact Example JSON response when successfully retrieving a user's channel profile. The response contains the profile name. ```json { "profile_name": "John Doe" } ``` -------------------------------- ### Create Project Directory Structure Source: https://developers.sinch.com/docs/sms/tutorials/node-sdk/appointment-reminder/set-up.md Sets up the basic folder and file structure for the appointment reminder application. ```shell sinch-appointment-reminder │ .env │ app.js │ routes.js │ ├───public │ └───css │ style.css │ └───views patient_details.html success.html ``` -------------------------------- ### Start Flask Web Server Source: https://developers.sinch.com/docs/sms/tutorials/python-sdk/user-consent/testing-app.md Execute this command in your project directory to start a Flask server on a specified port. Ensure ngrok is configured to use the same port. ```shell flask run -p ``` -------------------------------- ### Get Message Example Source: https://developers.sinch.com/docs/conversation/sdk/dotnet/syntax-reference.md Demonstrates how to retrieve a message using the .NET SDK, including the mapping of SDK parameters to REST API path and query parameters. ```APIDOC ## Get Message ### Description Retrieves a specific message from the conversation. ### Method GET ### Endpoint /v1/projects/{project_id}/messages/{messageId} ### Parameters #### Path Parameters - **messageId** (string) - Required - The unique identifier of the message. #### Query Parameters - **messagesSource** (string) - Required - Specifies the source of the messages. ### Request Example (SDK) ```csharp var response = await sinch.Conversation.Messages.Get( messageId = "YOUR_message_id", messagesSource = "CONVERSATION_SOURCE" ) ``` ### Request Example (REST API) ```json { "messages_source": "CONVERSATION_SOURCE" } ``` ### Response #### Success Response (200) - **[Response fields match API responses and are delivered as .NET objects]** ``` -------------------------------- ### Configure Sinch Client with HMS Push Source: https://developers.sinch.com/docs/in-app-calling/android/push-notifications.md Initialize and start the Sinch client with Huawei Mobile Services (HMS) push configuration. Ensure HMS is installed on the device. ```kotlin val sinchClient = SinchClient.builder().context(context) .pushConfiguration(hmsPushConfiguration) ... .build() ... sinchClient.start() ``` -------------------------------- ### Start and Complete SMS Verification in Node.js Source: https://developers.sinch.com/docs/sdks/node.md This class demonstrates the complete flow of an SMS verification process using the Sinch Node.js SDK. It includes starting the verification, prompting the user for the phone number and verification code, and reporting the code to complete the process. Ensure you have the '@sinch/sdk-core' and 'inquirer' packages installed. ```javascript // 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; } } } ``` -------------------------------- ### MMS MT Sent Notification (N101) Source: https://developers.sinch.com/docs/mms/api-reference/postback-notification-codes.md Example of a postback notification indicating an MMS MT message has been sent or processing has started. This payload includes basic transaction details. ```json { "origin": "MMS_MT", "code": "N101", "sent-as": "MMS", "status": "Sent", "status-details": "Message Sent", "to": "17745550001", "from": "18885551234", "timestamp": "2026-04-24T18:30:00Z", "tracking-id": "abc123xyz", "client-reference": "send-001" } ``` -------------------------------- ### Start Local Development Server Source: https://developers.sinch.com/docs/functions/functions/guides/add-a-custom-endpoint.md Starts the Sinch Functions development server to test custom endpoints locally. ```bash sinch functions dev ``` -------------------------------- ### Start SMS Verification using SDK Source: https://developers.sinch.com/docs/sdks/java.md Initiates an SMS verification process using the Sinch Java SDK. This example shows how to build the request object with the recipient's phone number and call the `startSms` method. ```java var identity = NumberIdentity.valueOf("YOUR_phone_number"); var response = client.verification().v1().verificationStart().startSms(VerificationStartRequestSms .builder() .setIdentity(identity) .build()); ``` -------------------------------- ### Create SinchClient Instance Source: https://developers.sinch.com/docs/in-app-calling/js/js-cloud-sinch-client.md Initialize the SinchClient with your application key, environment host, and user ID. Obtain the Application Key from the Sinch Developer Dashboard. The User ID must uniquely identify the user. ```javascript const sinchClient = Sinch.getSinchClientBuilder() .applicationKey("") .environmentHost("ocra.api.sinch.com") .userId("") .build(); ``` -------------------------------- ### Getting a Message Source: https://developers.sinch.com/docs/conversation/sdk/python/syntax-reference.md Example of retrieving a message using the Conversation API Python SDK. It shows how `message_id` is passed as an argument and `messages_source` is also included as an argument, corresponding to path and query parameters in the REST API respectively. ```APIDOC ## Get Message ### Description Retrieves a specific message using its ID and a source identifier. ### Method ```python sinch_client.conversation.messages.get( message_id="YOUR_message_id", messages_source="CONVERSATION_SOURCE" ) ``` ### Parameters #### Path Parameters - **message_id** (string) - Required - The unique identifier of the message. #### Query Parameters - **messages_source** (string) - Required - Specifies the source of the messages. ### Request Example ```json { "messages_source": "CONVERSATION_SOURCE" } ``` ### Response #### Success Response (200) - **message** (object) - The retrieved message object. #### Response Example ```json { "message": { "text_message": { "text": "Text message from Sinch Conversation API." } } } ``` ``` -------------------------------- ### Initialize Sinch Client with Credentials Source: https://developers.sinch.com/docs/number-lookup-api-v2/sdk/python/syntax-reference.md Initialize the main Sinch client class with your Sinch dashboard credentials. This is the first step to using the SDK. ```python from sinch import SinchClient sinch_client = SinchClient(key_id="key_id", key_secret="key_secret", project_id="YOUR_project_id") ``` -------------------------------- ### Get Available Numbers in US Source: https://developers.sinch.com/docs/numbers/api-reference/authentication/oauth.md This example demonstrates how to retrieve available phone numbers in the US using the Sinch Numbers API. Replace placeholders with your project ID and access token. Ensure your access token is correctly formatted in the Authorization header. ```shell curl -i -X GET \ 'https://numbers.api.sinch.com/v1/projects/{YOUR_projectId}/availableNumbers?regionCode=US&type=LOCAL' \ -H 'Authorization: Bearer {YOUR_access_token} ' \ -H 'Content-Type: application/json' \ ``` -------------------------------- ### Create WhatsApp Template (Marketing/Utility) Source: https://developers.sinch.com/docs/provisioning-api/api-reference/provisioning-api/tag/WhatsApp-Templates Example of creating a Marketing or Utility WhatsApp template. This snippet demonstrates the structure of the request body, including template name, language, category, and components. ```bash curl -X POST \ 'https://api.sinch.com/provisioning/v1/projects/{projectId}/whatsapp/templates' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \ -d '{ "name": "my_template_name", "language": "en", "category": "MARKETING", "components": [ { "type": "HEADER", "format": "TEXT", "text": "Welcome to our service!" }, { "type": "BODY", "text": "Your order {{1}} has been shipped. Track it here: {{2}}" }, { "type": "FOOTER", "text": "Thank you for your business." }, { "type": "BUTTONS", "buttons": [ { "type": "URL", "text": "Track Order", "url": "{{2}}" } ] } ] }' ``` -------------------------------- ### Get Verification Status by Identity using REST API Source: https://developers.sinch.com/docs/sdks/dotnet.md This example shows the equivalent REST API call to check verification status using the recipient's identity. It demonstrates how path parameters in the API correspond to arguments in the .NET SDK. ```csharp var request = client.GetAsync("https://verification.api.sinch.com/verification/v1/verifications/" + "YOUR_verification_method" + "/number/" + "YOUR_phone_number").Result; ```