Skip to content
Last updated

The Sinch Java SDK allows you to quickly interact with the Verification API from inside your Java applications. 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.

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

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

VerificationsSample.js
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));
  }
}

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.

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

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:

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:

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:

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:

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.