The Sinch Java SDK allows you to quickly interact with the suite of Sinch APIs from inside your Java applications. When using the Java SDK, the code representing requests and queries sent to and responses received from the suite of Sinch APIs are structured similarly to those that are sent and received using the suite of Sinch APIs.
The following links are available for your reference:
When using the Sinch Java SDK, you initialize communication with the Sinch backend by initializing the Java SDK's main client class. This client allows you to access the functionality of the Sinch Java SDK.
Initialization of the Java SDK client class can be done in two ways, depending on which product you are using.
To successfully initialize the Sinch client class, you must provide a valid access key ID and access key secret combination. You must also provide your Project ID. For example:
package numbers.sdk;
import com.sinch.sdk.SinchClient;
public class App {
public static String access_key = "YOUR_access_key";
public static String access_secret = "YOUR_access_secret";
public static String project_id = "YOUR_project_id"
public static void main(String[] args) {
SinchClient client = new SinchClient(Configuration.builder()
.setKeyId(access_key)
.setKeySecret(access_secret)
.setProjectId(project_id)
.build());
}
To start using the SDK, you need to initialize the main client class and create a configuration object to connect to your Sinch account and Voice app. You can find all of the credentials you need on your Sinch dashboard.
import com.sinch.sdk.SinchClient;
import com.sinch.sdk.models.Configuration;
public class App {
public static void main(String[] args) {
SinchClient client = new SinchClient(Configuration.builder()
.setApplicationKey("YOUR_application_key")
.setApplicationSecret("YOUR_application_secret")
.build());
}
}
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.
The Java SDK currently supports the following products:
This guide describes the syntactical structure of the Java 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.
This code sample is an example of how to use the Java SDK to list the available numbers of a given type and region. We've also provided an example that accomplishes the same task using the REST API.
// This code returns a list of all the available numbers for a given set of search criteria.
package numbers;
import com.sinch.sdk.domains.numbers.api.v1.NumbersService;
import com.sinch.sdk.domains.numbers.models.v1.NumberType;
import com.sinch.sdk.domains.numbers.models.v1.request.AvailableNumberListRequest;
import com.sinch.sdk.domains.numbers.models.v1.response.AvailableNumberListResponse;
import java.util.logging.Logger;
public class Snippet {
private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName());
static void execute(NumbersService numbersService) {
String regionCode = "US";
NumberType type = NumberType.LOCAL;
AvailableNumberListRequest parameters =
AvailableNumberListRequest.builder().setRegionCode(regionCode).setType(type).build();
LOGGER.info(
String.format("Listing available number type '%s' for region '%s'", type, regionCode));
AvailableNumberListResponse response = numbersService.searchForAvailableNumbers(parameters);
response
.iterator()
.forEachRemaining(
number -> LOGGER.info(String.format("Available number details: %s", number)));
}
}
The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.numbers().v1().[endpoint_category()].[method()]
.
In the Sinch Java SDK, Numbers API endpoints are accessible through the client:
numbers().v1()
numbers().v1().regions()
numbers().v1().callbackConfiguration()
numbers().v1().webhooks()
For example:
var numbers = client.numbers().v1().list(AvailableNumberListRequest.builder()
.setType(NumberType.LOCAL)
.setRegionCode("US")
.build());
The field mappings are described in the sections below.
The numbers().v1()
category of the Java SDK has methods that correspond to the available and active endpoints. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:
API operation | SDK method | JavaDocs |
---|---|---|
Activate a new phone number | rent() | rent |
Search for available phone numbers | searchForAvailableNumbers() | searchForAvailableNumbers |
Check availability of a specific number | checkAvailability() | checkAvailability |
Rent any available number | rentAny() | rentAny |
List active numbers for a project | list() | list |
Update active number | update() | update |
Retrieve active number | get() | get |
Release active number | release() | release |
The numbers().v1().regions()
category of the Java SDK corresponds to the availableRegions endpoint. The mapping between the API operation and corresponding Java method are described below, as well as links to the JavaDocs page:
API operation | SDK method | JavaDocs |
---|---|---|
List available regions | list() | list |
The numbers().v1().callbackConfiguration()
category of the Java SDK corresponds to the callbackConfiguration endpoint. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:
API operation | SDK method | JavaDocs |
---|---|---|
Get callbacks configuration | get() | get |
Update callback configuration | update() | update |
The numbers().v1().webhooks()
category of the Java SDK corresponds to the Event notification operation. The mapping between the API operation and corresponding Java method are described below, as well as links to the JavaDocs page:
API operation | SDK method | JavaDocs |
---|---|---|
Event notification | parseEvent() | parseEvent |
Requests and queries made using the Java SDK are similar to those made using the SMS API. Many of the fields are named and structured similarly. For example, consider the representations of an SMS API message type. One field is represented in JSON, and the other is using our Java SDK:
NumberType.MOBILE
Many fields in the Java SDK are rendered as enums in data models.
When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Java SDK, we use Java data models instead of nested JSON objects. For example, consider the SMS configuration objects below. One is represented in JSON, the other as a Java object:
AvailableNumberListRequest.builder()
.setType(NumberType.LOCAL)
.setRegionCode("US")
.build()
{
"type": "LOCAL",
"regionCode": "US"
}
Note that in the Java SDK you would use a builder()
method to construct the appropriate data model in the correct structure.
Response fields match the API responses. They are delivered as Java objects.
This guide describes the syntactical structure of the Java 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 API Reference.
The code sample below is an example of how to use the Java SDK to send an SMS message. We've also provided an example that accomplishes the same task using the REST API.
//Use this code to send an SMS message.
package sms;
import com.sinch.sdk.domains.sms.api.v1.BatchesService;
import com.sinch.sdk.domains.sms.api.v1.SMSService;
import com.sinch.sdk.domains.sms.models.v1.batches.request.TextRequest;
import com.sinch.sdk.domains.sms.models.v1.batches.response.BatchResponse;
import java.util.Collections;
import java.util.logging.Logger;
public class Snippet {
private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName());
static void execute(SMSService smsService) {
BatchesService batchesService = smsService.batches();
String from = "YOUR_sinch_phone_number";
String recipient = "YOUR_recipient_phone_number";
String body = "This is a test SMS message using the Sinch Java SDK.";
LOGGER.info(String.format("Submitting batch to send SMS to '%s'", recipient));
BatchResponse value =
batchesService.send(
TextRequest.builder()
.setTo(Collections.singletonList(recipient))
.setBody(body)
.setFrom(from)
.build());
LOGGER.info("Response: " + value);
}
}
Note that the REST API uses the Service Plan ID and and API token instead of Project ID and access keys.
The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.sms.[endpoint_category()].[method()]
.
In the Sinch Java SDK, SMS API endpoints are accessible through the client. The naming convention of the endpoints in the SDK resembles the API:
groups()
batches()
inbounds()
deliveryReports()
For example:
var batches = client.sms().batches().list(BatchesListRequestParameters.builder()
.setPage(1)
.setPageSize(10)
.setFrom("YOUR_from_number")
.setStartDate("2023-11-01T00:00:00.00")
.setEndDate("2023-11-30T00:00:00.00")
.setClientReference("YOUR_reference")
.build());
The field mappings are described in the sections below.
The sms().batches()
category of the Java SDK corresponds to the batches endpoint. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:
API operation | SDK method | JavaDocs |
---|---|---|
Send | send() | send |
List batches | list() | list |
Dry run | dryRun() | dryRun |
Get a batch message | get() | get |
Update a batch message | update() | update |
Replace a batch | replace() | replace |
Cancel a batch message | cancel() | cancel |
Send delivery feedback for a message | sendDeliveryFeedback() | sendDeliveryFeedback |
The sms().deliveryReports()
category of the Java SDK corresponds to the delivery_report and delivery_reports endpoints. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:
API operation | SDK method | JavaDocs |
---|---|---|
Retrieve a delivery report | get() | get |
Retrieve a recipient delivery report | getForNumber() | getForNumber |
Retrieve a list of delivery reports | list() | list |
The sms().groups()
category of the Java SDK corresponds to the groups endpoint. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:
API operation | SDK method | JavaDocs |
---|---|---|
List groups | list() | list |
Create a group | create() | create |
Retrieve a group | get() | get |
Update a group | update() | update |
Replace a group | replace() | replace |
Delete a group | delete() | delete |
List group member phone numbers | listMembers() | listMembers |
The sms().inbounds()
category of the Java SDK corresponds to the inbounds endpoint. The mapping between the API operations and corresponding Java methods are described below, as well as links to the JavaDocs page:
API operation | SDK method | JavaDocs |
---|---|---|
List incoming messages | list() | list |
Retrieve inbound message | get() | get |
Requests and queries made using the Java SDK are similar to those made using the SMS API. Many of the fields are named and structured similarly. For example, consider the representations of an SMS API message type. One field is represented in JSON, and the other is using our Java SDK:
DeliveryReportType.FULL
Many fields in the Java SDK are rendered as enums in data models.
When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Java SDK, we use Java data models instead of nested JSON objects. For example, consider the SMS configuration objects below. One is represented in JSON, the other as a Java object:
SendSmsBatchTextRequest.builder()
.setTo(Collections.singletonList("YOUR_recipient_phone_number"))
.setBody("Test message using Java SDK")
.setFrom("YOUR_sinch_phone_number")
.setDeliveryReport(DeliveryReportType.NONE)
.build()
Note that in the Java SDK you would use a builder()
method to construct the appropriate data model in the correct structure. Note also that while in the raw JSON request body you can specify the message type, the Java SDK has a specific Batch request object for each message type.
Response fields match the API responses. They are delivered as Java objects.
This guide describes the syntactical structure of the Java 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 Java 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.
package conversation;
import com.sinch.sdk.domains.conversation.api.v1.ConversationService;
import com.sinch.sdk.domains.conversation.api.v1.MessagesService;
import com.sinch.sdk.domains.conversation.models.v1.*;
import com.sinch.sdk.domains.conversation.models.v1.messages.*;
import com.sinch.sdk.domains.conversation.models.v1.messages.request.*;
import com.sinch.sdk.domains.conversation.models.v1.messages.response.SendMessageResponse;
import com.sinch.sdk.domains.conversation.models.v1.messages.types.text.*;
import java.util.*;
import java.util.Collections;
import java.util.logging.Logger;
public class Snippet {
private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName());
static void execute(ConversationService conversationService) {
MessagesService messagesService = conversationService.messages();
String appId = "YOUR_app_id";
String from = "YOUR_sms_sender";
String to = "RECIPIENT_number";
String body = "This is a test Conversation message using the Sinch Java SDK.";
String smsSender = "SMS_SENDER";
ChannelRecipientIdentities recipients =
ChannelRecipientIdentities.of(
ChannelRecipientIdentity.builder()
.setChannel(ConversationChannel.SMS)
.setIdentity(to)
.build());
AppMessage<TextMessage> message =
AppMessage.<TextMessage>builder()
.setBody(TextMessage.builder().setText(body).build())
.build();
SendMessageRequest<TextMessage> request =
SendMessageRequest.<TextMessage>builder()
.setAppId(appId)
.setRecipient(recipients)
.setMessage(message)
.setChannelProperties(Collections.singletonMap(smsSender, from))
.build();
LOGGER.info("Sending SMS Text using Conversation API");
SendMessageResponse value = messagesService.sendMessage(request);
LOGGER.info("Response: " + value);
}
}
The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.conversation().v1().[endpoint_category()].[method()]
or client.conversation().templates().[templates_version()].[method()]
.
In the Sinch Java 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:
v1().messages()
v1().app()
v1().contact()
v1().events()
v1().transcoding()
v1().capability()
templates.v1().templates()
templates.v2().templates()
v1().webhooks()
v1().conversation()
For example:
SendMessageResponse response =
client.conversation().v1().messages().sendMessage(SendMessageRequest.<TextMessage>builder()
.setAppId("YOUR_app_id")
.setRecipient(ChannelRecipientIdentities.of(ChannelRecipientIdentity.builder().setChannel(ConversationChannel.SMS).setIdentity("RECIPIENT_number").build()))
.setMessage(AppMessage.<TextMessage>builder().setBody(TextMessage.builder().setText("This is a test Conversation message using the Sinch Java SDK.").build()).build())
.setChannelProperties(Collections.singletonMap("SMS_SENDER", "YOUR_sms_sender"))
.build());
The messages
category of the Java 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 | sendMessage, 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 Java 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 |
This class will help you define channel credentials when creating or updating an app. Each channel is represented by a corresponding method, and invoking that method will allows you to more easily determine the information that is required to create the credentials.
The contact
category of the Java SDK corresponds to the contacts endpoint. The mapping between the API operations and corresponding methods are described below:
The conversations
category of the Java SDK corresponds to the conversations endpoint. The mapping between the API operations and corresponding methods are described below:
The events
category of the Java 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 |
Get an event | get |
Delete an event | delete |
List events | list |
The transcoding
category of the Java 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 Java 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 Java 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 |
No corresponding operation. You can use this function to authenticate information received from payloads. This function takes the secret parameter, which is the Secret token to be used to validate the received request. | validateAuthenticationHeader |
No corresponding operation. You can use this function to deserialize payloads received from callbacks. This function takes the jsonPayload parameter, which is the received payload. | parseEvent |
The templates
(version 1) category of the Java 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 templates
(version 2) category of the Java SDK corresponds to the Templates-V2 endpoint. The mapping between the API operations and corresponding methods are described below:
Requests and queries made using the Java SDK are similar to those made using the Conversation API. Many of the fields are named and structured similarly. For example, consider the representation of a Conversation API channel. One field is represented in our Java SDK, and the other is using the REST API:
ConversationChannel.SMS
Note that the fields have similar names, and many fields in the Java SDK are rendered as enums in data models.
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 messages
is invoked:
var response = client.conversation().v1().messages().get("YOUR_message_id", "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 Java SDK, both parameters are included as arguments in the get
method.
Response fields match the API responses. They are delivered as Java objects.
This guide describes the syntactical structure of the Java 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 Java SDK to make a text to speech phone call to phone number using the Java SDK and the Voice API. We've also provided an example that accomplishes the same task using the REST API.
package voice;
import com.sinch.sdk.domains.voice.api.v1.CalloutsService;
import com.sinch.sdk.domains.voice.api.v1.VoiceService;
import com.sinch.sdk.domains.voice.models.v1.callouts.request.CalloutRequestTTS;
import com.sinch.sdk.domains.voice.models.v1.destination.DestinationPstn;
import java.util.logging.Logger;
public class Snippet {
private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName());
public static String execute(VoiceService voiceService) {
CalloutsService calloutsService = voiceService.callouts();
String phoneNumber = "YOUR_phone_number";
String message = "Hello, this is a call from Sinch. Congratulations! You made your first call.";
LOGGER.info("Calling '" + phoneNumber + '"');
CalloutRequestTTS parameters =
CalloutRequestTTS.builder()
.setDestination(DestinationPstn.from(phoneNumber))
.setText(message)
.build();
String callId = calloutsService.textToSpeech(parameters);
LOGGER.info("Call started with id: '" + callId + '"');
return callId;
}
}
The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.voice().[endpoint_category()].[method()]
.
In the Sinch Java 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:
var response = client.voice()
.callouts()
.textToSpeech(CalloutRequestParametersTTS
.builder()
.setDestination(DestinationNumber.valueOf("YOUR_phone_number"))
.setText("Thank you for calling Sinch. This call will now end.")
.build());
The voice().callouts()
category of the Java SDK corresponds corresponds to the callouts endpoint. The mapping between the API operations and corresponding Java methods are described below:
API operation | SDK method | JavaDocs entry |
---|---|---|
Makes a Text-to-speech callout | textToSpeech() | textToSpeech |
Makes a Conference callout | conference() | conference |
Makes a Custom callout | Custom() | custom |
The voice().calls()
category of the Java SDK corresponds corresponds to the calls endpoint. The mapping between the API operations and corresponding Java methods are described below:
API operation | SDK method | JavaDocs entry |
---|---|---|
Get information about a call | get() | get |
Manage call with callLeg | manageWithCallLeg() | manageWithCallLeg |
Updates a call in progress | update() | update |
The voice().conferences()
category of the Java SDK corresponds corresponds to the conferences endpoint. The mapping between the API operations and corresponding Java methods are described below:
API operation | SDK method | JavaDocs entry |
---|---|---|
Makes a conference callout | call() | call |
Get information about a conference | get() | get |
Manage a conference participant | manageParticipant() | manageParticipant |
Remove a participant from a conference | kickParticipant() | kickParticipant |
Remove all participants from a conference | kickAll() | kickAll |
The voice().applications()
category of the Java SDK corresponds corresponds to the configuration endpoint. The mapping between the API operations and corresponding Java methods are described below:
API operation | SDK method | JavaDocs entry |
---|---|---|
Return all the numbers assigned to an application | listNumbers() | listNumbers |
Assign a number or list of numbers to an application | assignNumbers() | assignNumbers |
Unassign a number from an application | unassignNumber() | unassignNumber |
Return the callback URLs for an application | getCallbackUrls() | getCallbackUrls |
Update the callback URL for an application | updateCallbackUrls() | updateCallbackUrls |
Returns information about a number | queryNumber() | queryNumber |
The voice().webhooks()
category of the Java SDK are helper methods designed to assist in serializing/deserializing requests from and responses to the Sinch servers, as well as validate that the requests coming from the Sinch servers are authentic.
SDK method | Description | JavaDocs entry |
---|---|---|
validateAuthenticatedRequest() | Validates if the request is authentic. It is a best practice to evaluate if a request is authentic before performing any business logic on it. | validateAuthenticatedRequest |
serializeVerificationResponse() | Serializes a SVAMLControl response into a JSON string. You must serialize the response before returning it because the Sinch servers expect a JSON response. | serializeWebhooksResponse |
unserializeVerificationEvent() | Deserializes a JSON response into a Voice event class. You can use this method to handle different event types and write logic for different events. | unserializeWebhooksEvent |
Requests and queries made using the Java SDK are similar to those made using the Voice API. Many of the fields are named and structured similarly.
Many fields in the Java SDK are rendered as enums in data models.
When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Java SDK, we use Java data models instead of nested JSON objects. For example, consider the Voice configuration objects below. One is represented in JSON, the other as a Java object:
CalloutRequestParametersTTS.builder()
.setDestination(DestinationNumber.valueOf("YOUR_phone_number"))
.setText("Thank you for calling Sinch. This call will now end.")
.build()
Note that in the Java SDK you would use a specific helper class for the type of Voice call you want to make and a builder()
method to construct the appropriate data model in the correct structure.
Response fields match the API responses. They are delivered as Java objects.
This guide describes the syntactical structure of the Java 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 Java SDK to initiate an SMS PIN Verification. We've also provided an example that accomplishes the same task using the REST API.
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(
VerificationStartService 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 service
* @param code Code received by SMS
* @param id Verification ID related to the verification
*/
private void reportSmsVerification(VerificationReportService 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));
}
}
The Sinch Java SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, client.verification().v1().[endpoint_category()].[method()]
.
In the Sinch Java SDK, Verification API endpoints are accessible through the client. The naming convention of the endpoints represented in the SDK matches the API:
verification().v1().verificationStart()
verification().v1().verificationReport()
verification().v1().verificationStatus()
verification().v1().webhooks()
For example:
var identity = NumberIdentity.valueOf("YOUR_phone_number");
var response = client.verification().v1().verificationStart().startSms(VerificationStartRequestSms
.builder()
.setIdentity(identity)
.build());
The field mappings are described in the sections below.
The verification().v1().verificationStart()
category of the Java SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Java methods are described below:
API operation | SDK method | JavaDocs entry |
---|---|---|
Start an SMS PIN verification request | startSms() | startSms |
Start a Flash Call verification request | startFlashCall() | startFlashCall |
Start a Phone Call verification request | startPhoneCall() | startPhoneCall |
Start a Data verification request | startData() | startData |
The verification().v1().verificationReport()
category of the Java SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Java methods are described below:
API operation | SDK method | JavaDocs entry |
---|---|---|
Report an SMS PIN verification code by the identity of the recipient | reportSmsByIdentity() | reportSmsByIdentity |
Report an SMS PIN verification code by the ID of the verification request | reportSmsById() | reportSmsById |
Report a Phone Call verification code by the identity of the recipient | reportPhoneCallByIdentity() | reportPhoneCallByIdentity |
Report a Phone Call verification code by the ID of the verification request | reportPhoneCallById() | reportPhoneCallById |
Report a FlashCall verification code by the identity of the recipient | reportFlashCallByIdentity() | reportFlashCallByIdentity |
Report a FlashCall verification code by the ID of the verification request | reportFlashCallById() | reportFlashCallById |
The verification().v1().verificationStatus()
category of the Java SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Java methods are described below:
API operation | SDK method | JavaDocs entry |
---|---|---|
Get the status of a verification by the ID of the verification request | getById() | getById |
Get the status of a verification by the identity of the recipient | getByIdentity() | getByIdentity |
Get the status of a verification by a reference value | getByReference() | getByReference |
The verification().v1().webhooks()
category of the Java SDK corresponds to the callbacks section. The mapping between the API operations and corresponding Java methods are described below:
API callback | SDK method | JavaDocs entry |
---|---|---|
Validates if the authentication of the verification request matches | validateAuthenticatedRequest() | validateAuthenticationHeader |
Serializes a verification response into a JSON string | serializeResponse() | serializeResponse |
Deserializes a JSON response into the corresponding Verification event class | parseEvent() | parseEvent |
Requests and queries made using the Java SDK are similar to those made using the SMS API. Many of the fields are named and structured similarly. For example, consider the representations of a Verification method type. One field is represented in JSON, and the other is using our Java SDK:
VerificationStartRequestSms
Many fields in the Java SDK are rendered as enums in data models.
When making calls directly to the API, we use JSON objects, including (in some cases) nested JSON objects. When using the Java SDK, we use Java data models instead of nested JSON objects. For example, consider the Verification configuration objects below. One is represented in JSON, the other as a Java object:
VerificationStartRequestSms.builder()
.setIdentity(NumberIdentity.builder()
.setEndpoint("YOUR_phone_number")
.build())
.build()
{
"method": "sms",
"identity": {
"type": "number",
"endpoint": "YOUR_phone_number"
}
}
Note that in the Java SDK you would use a specific helper class for the type of Verification you want to send and a builder()
method to construct the appropriate data model in the correct structure.
Response fields match the API responses. They are delivered as Java objects.