Sinch Java SDK for Verification

The Sinch Verification Java SDK allows you to quickly interact with the Verification API from inside your Java applications. The fastest way to get started with the SDK is to check out our getting started guides. There you'll find all the instructions necessary to download, install, set up, and start using the SDK.

Note:
You can also view the generated JavaDocs for the Java SDK here.

Syntax

When using the Java SDK, the code representing requests and queries sent to and responses received from the Verification API are structured similarly to those that are sent and received using the Verification API itself.

Note:

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 on the side of this page is an example of how to use the Java SDK to intiate an SMS PIN Verification. The code is also displayed below, along with a Verification API call that accomplishes the same task, for reference:

REST APISDK
Copy
Copied
package app;

import java.io.IOException;
import java.net.*;
import java.net.http.*;
import java.util.*;

public class App {
    
    private static final String applicationKey = "<REPLACE_WITH_VERIF_APP_KEY>";
    private static final String applicationSecret = "<REPLACE_WITH_VERIF_APP_SECRET>";
    private static final String toNumber = "<REPLACE_WITH_TO_NUMBER>";
    private static final String SINCH_URL = "https://verification.api.sinch.com/verification/v1/verifications";
    public static final String JSON_CONTENT_TYPE = "application/json; charset=utf-8";
    
    public static void main(String[] args) throws Exception {
        
        HttpResponse<String> response = sendSMSPinWithBasicAuth();

        System.out.println(response.body());
    }

    private static HttpResponse<String> sendSMSPinWithBasicAuth() throws IOException, InterruptedException {
        var httpClient = HttpClient.newBuilder().build();

        var payload = getSMSVerificationRequestBody();

        var request = HttpRequest.newBuilder()
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .uri(URI.create(SINCH_URL))
                .header("Content-Type", JSON_CONTENT_TYPE)
                .header("Authorization", "Basic " + Base64.getEncoder().encodeToString((applicationKey + ":" + applicationSecret).getBytes()))
                .build();

        return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
    }

    private static String getSMSVerificationRequestBody() {
        return """
            {
                "identity": {
                    "type": "number",
                    "endpoint": "%s"
                },
                "method": "sms"
            }
            """.formatted(toNumber);
    }
}
Copy
Copied
package verification;

import com.sinch.sdk.domains.verification.api.v1.VerificationService;
import com.sinch.sdk.domains.verification.api.v1.VerificationStartService;
import com.sinch.sdk.domains.verification.models.v1.NumberIdentity;
import com.sinch.sdk.domains.verification.models.v1.start.request.VerificationStartRequestSms;
import com.sinch.sdk.domains.verification.models.v1.start.response.VerificationStartResponseSms;
import java.util.logging.Logger;

public class Snippet {

  private static final Logger LOGGER = Logger.getLogger(Snippet.class.getName());

  static void execute(VerificationService verificationService) {

    // REMINDER: verification Service require to have set application key/secret
    // onto Sinch Client init
    VerificationStartService startService = verificationService.verificationStart();

    String phoneNumber = "YOUR_phone_number";

    LOGGER.info(String.format("Sending a SMS verification to '%s'", phoneNumber));

    VerificationStartResponseSms response =
        startService.startSms(
            VerificationStartRequestSms.builder()
                .setIdentity(NumberIdentity.valueOf(phoneNumber))
                .build());

    LOGGER.info("Response: " + response);
  }
}

This example highlights the following required to successfully make a Verification API call using the Sinch Java SDK:

Client

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

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 Verification app. You can find all of the credentials you need on your Sinch dashboard.

Copy
Copied
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());
    }
}
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.

Verification domain

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()].

Endpoint categories

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:

Copy
Copied
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.

verification().v1().verificationStart() endpoint category

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 operationSDK methodJavaDocs entry
Start an SMS PIN verification requeststartSms()startSms
Start a Flash Call verification requeststartFlashCall()startFlashCall
Start a Phone Call verification requeststartPhoneCall()startPhoneCall
Start a Data verification requeststartData()startData

verification().v1().verificationReport() endpoint category

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 operationSDK methodJavaDocs entry
Report an SMS PIN verification code by the identity of the recipientreportSmsByIdentity()reportSmsByIdentity
Report an SMS PIN verification code by the ID of the verification requestreportSmsById()reportSmsById
Report a Phone Call verification code by the identity of the recipientreportPhoneCallByIdentity()reportPhoneCallByIdentity
Report a Phone Call verification code by the ID of the verification requestreportPhoneCallById()reportPhoneCallById
Report a FlashCall verification code by the identity of the recipientreportFlashCallByIdentity()reportFlashCallByIdentity
Report a FlashCall verification code by the ID of the verification requestreportFlashCallById()reportFlashCallById

verification().v1().verificationStatus() endpoint category

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 operationSDK methodJavaDocs entry
Get the status of a verification by the ID of the verification requestgetById()getById
Get the status of a verification by the identity of the recipientgetByIdentity()getByIdentity
Get the status of a verification by a reference valuegetByReference()getByReference

verification().v1().webhooks() endpoint category

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 callbackSDK methodJavaDocs entry
Validates if the authentication of the verification request matchesvalidateAuthenticatedRequest()validateAuthenticationHeader
Serializes a verification response into a JSON stringserializeResponse()serializeResponse
Deserializes a JSON response into the corresponding Verification event classparseEvent()parseEvent

Request and query parameters

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:

SDKJSON
Copy
Copied
VerificationStartRequestSms
Copy
Copied
"method": "sms"

Many fields in the Java SDK are rendered as enums in data models.

Nested objects

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:

SDKJSON
Copy
Copied
VerificationStartRequestSms.builder()
                                .setIdentity(NumberIdentity.builder()
                                    .setEndpoint("YOUR_phone_number")
                                    .build())
                                .build()
Copy
Copied
{
  "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.

Responses

Response fields match the API responses. They are delivered as Java objects.

We'd love to hear from you!
Rate this content:
Still have a question?
 
Ask the community.