Skip to content

Latest commit

 

History

History
3022 lines (2676 loc) · 94.7 KB

SNIPPETS.md

File metadata and controls

3022 lines (2676 loc) · 94.7 KB

Vonage Java SDK Code Snippets

Here are all the snippets in this repository. This file was generated by running AggregateSnippets.java from the root of the repository.

Contents

Initialize

Application Auth With Key Contents

VonageClient client = VonageClient.builder()
        .applicationId(VONAGE_APPLICATION_ID)
        .privateKeyContents(VONAGE_APPLICATION_PRIVATE_KEY)
        .build();

Full Auth

VonageClient client = VonageClient.builder()
        .apiKey(VONAGE_API_KEY)
        .apiSecret(VONAGE_API_SECRET)
        .applicationId(VONAGE_APPLICATION_ID)
        .privateKeyPath(VONAGE_APPLICATION_PRIVATE_KEY_PATH)
        .build();

Basic Auth

VonageClient client = VonageClient.builder().apiKey(VONAGE_API_KEY).apiSecret(VONAGE_API_SECRET).build();

Application Auth With Key Path

VonageClient client = VonageClient.builder()
        .applicationId(VONAGE_APPLICATION_ID)
        .privateKeyPath(VONAGE_APPLICATION_PRIVATE_KEY_PATH)
        .build();

Account

Create Secret

SecretResponse response = client.getAccountClient().createSecret(VONAGE_API_KEY, NEW_SECRET);
System.out.println(response.getId() + " created at " + response.getCreated());

Configure Account

SettingsResponse response = client.getAccountClient().updateSmsIncomingUrl(SMS_CALLBACK_URL);
System.out.println("SMS Callback URL is now " + response.getIncomingSmsUrl());

Revoke Secret

client.getAccountClient().revokeSecret(VONAGE_API_KEY, VONAGE_SECRET_ID);

Get Balance

BalanceResponse response = client.getAccountClient().getBalance();
System.out.printf("Balance: %s EUR\n", response.getValue());
System.out.printf("Auto-reload Enabled: %s\n", response.isAutoReload());

Get Secret

SecretResponse response = client.getAccountClient().getSecret(VONAGE_API_KEY, VONAGE_SECRET_ID);
System.out.println(response.getId() + " created at " + response.getCreated());

List Secrets

ListSecretsResponse response = client.getAccountClient().listSecrets(VONAGE_API_KEY);

for (SecretResponse secret : response.getSecrets()) {
    System.out.println(secret.getId() + " created at " + secret.getCreated());
}

Application

Delete Application

client.getApplicationClient().deleteApplication(VONAGE_APPLICATION_ID);

Create Application

Application application = client.getApplicationClient().createApplication(
    Application.builder()
        .name(APPLICATION_NAME)
        .addCapability(Messages.builder()
                .addWebhook(Webhook.Type.INBOUND,
                        new Webhook("https://example.com/webhooks/inbound", HttpMethod.POST))
                .addWebhook(Webhook.Type.STATUS,
                        new Webhook("https://example.com/webhooks/status", HttpMethod.POST))
                .build()
        )
        .build()
);

System.out.println("Application Created:");
System.out.println(application.toJson());

Get Application

Application application = client.getApplicationClient().getApplication(VONAGE_APPLICATION_ID);

System.out.println(application.toJson());

List Applications

ApplicationList applications = client.getApplicationClient().listApplications();

applications.getApplications().forEach(
        application -> System.out.println(application.toJson())
);

Update Application

ApplicationClient applicationClient = client.getApplicationClient();
Application existingApplication = applicationClient.getApplication(VONAGE_APPLICATION_ID);

Capability messages = Messages.builder()
        .addWebhook(Webhook.Type.INBOUND,
                new Webhook("https://example.com/webhooks/inbound", HttpMethod.POST))
        .addWebhook(Webhook.Type.STATUS,
                new Webhook("https://example.com/webhooks/status", HttpMethod.POST))
        .build();

Capability voice = Voice.builder()
        .addWebhook(Webhook.Type.ANSWER,
                new Webhook("https://example.com/webhooks/answer", HttpMethod.POST))
        .addWebhook(Webhook.Type.EVENT,
                new Webhook("https://example.com/webhooks/event", HttpMethod.POST))
        .build();

Capability rtc = Rtc.builder()
        .addWebhook(Webhook.Type.EVENT,
                new Webhook("https://example.com/webhooks/event", HttpMethod.POST))
        .build();

Capability vbc = Vbc.builder().build();

Application application = applicationClient.updateApplication(
        Application.builder(existingApplication)
                .name(APPLICATION_NAME)
                .addCapability(messages)
                .addCapability(voice)
                .addCapability(rtc)
                .addCapability(vbc)
                .build()
);

System.out.println("Application Updated:");
System.out.println("Old: " + existingApplication.toJson());
System.out.println("New: " + application.toJson());

Number Insight

Basic Insight

BasicInsightResponse response = client.getInsightClient().getBasicNumberInsight(INSIGHT_NUMBER);
System.out.println("International format: " + response.getInternationalFormatNumber());
System.out.println("National format: " + response.getNationalFormatNumber());
System.out.println("Country: " + response.getCountryName() +
        " (" + response.getCountryCodeIso3() + ", +" + response.getCountryPrefix() + ")"
);

Advanced Insight

AdvancedInsightResponse response = client.getInsightClient().getAdvancedNumberInsight(INSIGHT_NUMBER);

System.out.println("BASIC INFO:");
System.out.println("International format: " + response.getInternationalFormatNumber());
System.out.println("National format: " + response.getNationalFormatNumber());
System.out.println("Country: " + response.getCountryName() + " (" +
        response.getCountryCodeIso3() + ", +" + response.getCountryPrefix() + ")"
);
System.out.println();
System.out.println("STANDARD INFO:");
System.out.println("Current carrier: " + response.getCurrentCarrier().getName());
System.out.println("Original carrier: " + response.getOriginalCarrier().getName());

System.out.println();
System.out.println("ADVANCED INFO:");
System.out.println("Validity: " + response.getValidNumber());
System.out.println("Reachability: " + response.getReachability());
System.out.println("Ported status: " + response.getPorted());

RoamingDetails roaming = response.getRoaming();
if (roaming == null) {
    System.out.println("- No Roaming Info -");
}
else {
    System.out.println("Roaming status: " + roaming.getStatus());
    if (response.getRoaming().getStatus() == RoamingDetails.RoamingStatus.ROAMING) {
        System.out.print("    Currently roaming in: " + roaming.getRoamingCountryCode());
        System.out.println(" on the network " + roaming.getRoamingNetworkName());
    }
}

Standard Insight

StandardInsightResponse response = client.getInsightClient().getStandardNumberInsight(INSIGHT_NUMBER);

System.out.println("BASIC INFO:");
System.out.println("International format: " + response.getInternationalFormatNumber());
System.out.println("National format: " + response.getNationalFormatNumber());
System.out.println("Country: " + response.getCountryName() +
        " (" + response.getCountryCodeIso3() + ", +" + response.getCountryPrefix() + ")"
);

System.out.println();
System.out.println("CARRIER INFO:");
System.out.println("Current carrier: " + response.getCurrentCarrier().getName());
System.out.println("Original carrier: " + response.getOriginalCarrier().getName());

Advanced Insight Async

client.getInsightClient().getAdvancedNumberInsight(
        AdvancedInsightRequest.builder(INSIGHT_NUMBER)
            .async(true).callback(CALLBACK_URL).build()
);

Advanced Insight With CNAM

AdvancedInsightRequest request = AdvancedInsightRequest.builder(INSIGHT_NUMBER).cnam(true).build();

AdvancedInsightResponse response = client.getInsightClient().getAdvancedNumberInsight(request);

System.out.println(response);

System.out.println("BASIC INFO:");
System.out.println("International format: " + response.getInternationalFormatNumber());
System.out.println("National format: " + response.getNationalFormatNumber());
System.out.println("Country: " + response.getCountryName() + " (" + response.getCountryCodeIso3() + ", +"
        + response.getCountryPrefix() + ")");
System.out.println();
System.out.println("STANDARD INFO:");
System.out.println("Current carrier: " + response.getCurrentCarrier().getName());
System.out.println("Original carrier: " + response.getOriginalCarrier().getName());

System.out.println();
System.out.println("ADVANCED INFO:");
System.out.println("Validity: " + response.getValidNumber());
System.out.println("Reachability: " + response.getReachability());
System.out.println("Ported status: " + response.getPorted());

RoamingDetails roaming = response.getRoaming();
if (roaming == null) {
    System.out.println("- No Roaming Info -");
}
else {
    System.out.println("Roaming status: " + roaming.getStatus());
    if (response.getRoaming().getStatus() == RoamingDetails.RoamingStatus.ROAMING) {
        System.out.print("    Currently roaming in: " + roaming.getRoamingCountryCode());
        System.out.println(" on the network " + roaming.getRoamingNetworkName());
    }
}

System.out.println("CNAM INFORMATION:");
System.out.println("Name: " + response.getCallerIdentity().getName());
System.out.println("Type: " + response.getCallerIdentity().getType());

Async Insight Trigger

port(3000);
Spark.post("/webhooks/insight", (req, res) -> {
    AdvancedInsightResponse response = AdvancedInsightResponse.fromJson(req.body());
    System.out.println("Country: " + response.getCountryName());

    res.status(204);
    return "";
});

JWT

Validate Inbound JWT

final String signatureSecret = envVar("VONAGE_SIGNATURE_SECRET");

Route validateJwt = (req, res) -> {
    String token = req.headers("Authorization").substring(7);

    if (Jwt.verifySignature(token, signatureSecret)) {
        res.status(204);
    }
    else {
        res.status(401);
    }

    return "";
};
Spark.port(5000);
Spark.post("/webhooks/validatejwt", validateJwt);

Generate JWT

String token = Jwt.builder()
    .applicationId("aaaaaaaa-bbbb-cccc-dddd-0123456789ab")
    .privateKeyPath(Paths.get(envVar("VONAGE_PRIVATE_KEY_PATH")))
    .subject("alice")
    .issuedAt(ZonedDateTime.now())
    .expiresAt(ZonedDateTime.now().plusMinutes(20))
    .addClaim("acl", Map.of(
        "paths", Map.of(
            "/*/users/**", Map.of(),
            "/*/conversations/**", Map.of(),
            "/*/sessions/**", Map.of(),
            "/*/devices/**", Map.of(),
            "/*/image/**", Map.of(),
            "/*/media/**", Map.of(),
            "/*/applications/**", Map.of(),
            "/*/push/**", Map.of(),
            "/*/knocking/**", Map.of(),
            "/*/legs/**", Map.of()
        )
    ))
    .build()
    .generate();

Meetings

Delete Theme

client.getMeetingsClient().deleteTheme(THEME_ID, true);
System.out.println("Deleted theme "+THEME_ID);

List Themes

List<Theme> themes = client.getMeetingsClient().listThemes();
themes.forEach(theme -> System.out.println(theme.getThemeName() + " ("+theme.getThemeId()+")"));

List Dial In Numbers

List<DialInNumber> dialInNumbers = client.getMeetingsClient().listDialNumbers();
dialInNumbers.forEach(din -> System.out.println(din.getDisplayName()+": "+din.getNumber()));

Delete Recording

client.getMeetingsClient().deleteRecording(RECORDING_ID);
System.out.println("Deleted recording "+RECORDING_ID);

Get Room

MeetingRoom room = client.getMeetingsClient().getRoom(ROOM_ID);
System.out.println(room.getDisplayName() + " ("+room.getId()+")");

Upload Logo

client.getMeetingsClient().updateThemeLogo(THEME_ID, LOGO_TYPE, LOGO_FILEPATH);
System.out.println("Updated '"+LOGO_TYPE+"' logo for theme "+THEME_ID);

Create Long Term Room

MeetingRoom room = MeetingRoom.builder(DISPLAY_NAME)
        .type(RoomType.LONG_TERM)
        .expiresAt(EXPIRATION_DATE)
        .build();
client.getMeetingsClient().createRoom(room);
System.out.println("Created room "+room.getId());

Update Room

UpdateRoomRequest request = UpdateRoomRequest.builder().themeId(THEME_ID).build();
MeetingRoom room = client.getMeetingsClient().updateRoom(ROOM_ID, request);
System.out.println("Updated room '"+room.getDisplayName()+"' ("+room.getId()+")");

List Recordings

List<Recording> recordings = client.getMeetingsClient().listRecordings(SESSION_ID);
recordings.forEach(recording -> System.out.println(recording.getId()));

Update Application

UpdateApplicationRequest request = UpdateApplicationRequest.builder()
        .defaultThemeId(THEME_ID).build();
Application application = client.getMeetingsClient().updateApplication(request);
System.out.println("Updated application "+application.getApplicationId());

List Rooms By Theme

List<MeetingRoom> rooms = client.getMeetingsClient().searchRoomsByTheme(THEME_ID);
rooms.forEach(room -> System.out.println(room.getDisplayName() + " ("+room.getId()+")"));

Update Theme

Theme theme = Theme.builder().mainColor(MAIN_COLOR).brandText(BRAND_TEXT).build();
client.getMeetingsClient().updateTheme(THEME_ID, theme);
System.out.println("Updated theme '"+theme.getThemeName()+"' ("+theme.getThemeId()+")");

Create Instant Room

MeetingRoom room = MeetingRoom.builder(DISPLAY_NAME).type(RoomType.INSTANT).build();
client.getMeetingsClient().createRoom(room);
System.out.println("Created room "+room.getId());

Get Recording

Recording recording = client.getMeetingsClient().getRecording(RECORDING_ID);
System.out.println(recording.getId());

List Rooms

List<MeetingRoom> rooms = client.getMeetingsClient().listRooms();
rooms.forEach(room -> System.out.println(room.getDisplayName() + " ("+room.getId()+")"));

Get Theme

Theme theme = client.getMeetingsClient().getTheme(THEME_ID);
System.out.println(theme.getThemeName());

Create Theme

Theme theme = Theme.builder().mainColor(MAIN_COLOR).brandText(BRAND_TEXT).build();
client.getMeetingsClient().createTheme(theme);
System.out.println("Updated theme '"+theme.getThemeName()+"' ("+theme.getThemeId()+")");

Messages

SMS

Send SMS Text

var response = client.getMessagesClient().sendMessage(
        SmsTextRequest.builder()
            .from(VONAGE_BRAND_NAME).to(TO_NUMBER)
            .text("This is an SMS text message sent using the Messages API")
            .build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

RCS

Send RCS Text

var response = client.getMessagesClient().sendMessage(
        RcsTextRequest.builder()
            .from(RCS_SENDER_ID).to(TO_NUMBER)
            .text("This is an RCS message sent via the Vonage Messages API")
            .build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Image

var response = client.getMessagesClient().sendMessage(
    RcsImageRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .url(IMAGE_URL)
        .build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Rich Card

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "richCard", Map.of("standaloneCard", Map.of(
                    "thumbnailImageAlignment", "RIGHT",
                    "cardOrientation", "VERTICAL",
                    "cardContent", Map.of(
                        "title", "Quick question",
                        "description", "Do you like this picture?",
                        "media", Map.of(
                            "height", "TALL",
                            "contentInfo", Map.of(
                                "fileUrl", IMAGE_URL,
                                "forceRefresh", "false"
                            )
                        ),
                        "suggestions", List.of(
                            Map.of(
                                "reply", Map.of(
                                    "text", "Yes",
                                    "postbackData", "suggestion_1"
                                )
                            ),
                            Map.of(
                                "reply", Map.of(
                                    "text", "I love it!",
                                    "postbackData", "suggestion_2"
                                )
                            )
                        )
                    )
                ))
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Suggested View Location

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "text", "Drop by our office!",
                "suggestions", List.of(
                    Map.of(
                        "action", Map.of(
                            "text", "View map",
                            "postbackData", "postback_data_1234",
                            "fallbackUrl", "https://www.google.com/maps/place/Vonage/@51.5230371,-0.0852492,15z",
                            "viewLocationAction" , Map.of(
                                "latLong", Map.of(
                                    "latitude", 51.5230371,
                                    "longitude", -0.0852492
                                ),
                                "label", "Vonage London Office"
                            )
                        )
                    )
                )
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Revoke Message

client.getMessagesClient().revokeOutboundMessage(MESSAGE_UUID, ApiRegion.API_EU);

Send RCS Suggested Reply

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "text", "What do you think of Vonage APIs?",
                "suggestions", List.of(
                    Map.of(
                        "reply", Map.of(
                            "text", "They're great!",
                            "postbackData", "suggestion_1"
                        )
                    ),
                    Map.of(
                        "reply", Map.of(
                            "text", "They're awesome!",
                            "postbackData", "suggestion_2"
                        )
                    )
                )
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Rich Card Carousel

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "carouselCard", Map.of(
                    "cardWidth", "MEDIUM",
                    "cardContents", List.of(
                        Map.of(
                            "title", "Option 1: Photo",
                            "description", "Do you prefer this photo?",
                            "suggestions", List.of(
                                Map.of(
                                    "reply", Map.of(
                                        "text", "Option 1",
                                        "postbackData", "card_1"
                                    )
                                )
                            ),
                            "media", Map.of(
                                "height", "MEDIUM",
                                "contentInfo", Map.of(
                                    "fileUrl", IMAGE_URL,
                                    "forceRefresh", "false"
                                )
                            )
                        ),
                        Map.of(
                            "title", "Option 2: Video",
                            "description", "Or this video?",
                            "suggestions", List.of(
                                Map.of(
                                    "reply", Map.of(
                                        "text", "Option 2",
                                        "postbackData", "card_2"
                                    )
                                )
                            ),
                            "media", Map.of(
                                "height", "MEDIUM",
                                "contentInfo", Map.of(
                                    "fileUrl", VIDEO_URL,
                                    "forceRefresh", "false"
                                )
                            )
                        )
                    )
                )
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Video

var response = client.getMessagesClient().sendMessage(
    RcsVideoRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .url(VIDEO_URL)
        .build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Suggested Calendar Event

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "text", "Product Launch: Save the date!",
                "suggestions", List.of(
                    Map.of(
                        "action", Map.of(
                            "text", "Save to calendar",
                            "postbackData", "postback_data_1234",
                            "fallbackUrl", "https://www.google.com/calendar",
                            "createCalendarEventAction", Map.of(
                                "startTime", Instant.ofEpochSecond(1719604800),
                                "endTime", Instant.ofEpochSecond(1719601200),
                                "title", "Vonage API Product Launch",
                                "description", "Event to demo Vonage's new and exciting API product"
                            )
                        )
                    )
                )
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS File

var response = client.getMessagesClient().sendMessage(
    RcsFileRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .url(FILE_URL)
        .build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Suggested Open URL

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "text", "Check out our latest offers!",
                "suggestions", List.of(
                    Map.of(
                        "action", Map.of(
                            "text", "Open product page",
                            "postbackData", "postback_data_1234",
                            "openUrlAction" , Map.of(
                                "url", "https://example.com/product"
                            )
                        )
                    )
                )
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Suggested Multiple Actions

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "text", "Need some help? Call us now or visit our website for more information.",
                "suggestions", List.of(
                    Map.of(
                        "action", Map.of(
                            "text", "Call us",
                            "postbackData", "postback_data_1234",
                            "fallbackUrl", "https://www.example.com/contact/",
                            "dialAction", Map.of(
                                "phoneNumber", "+447900000000"
                            )
                        )
                    ),
                    Map.of(
                        "action", Map.of(
                            "text", "Visit site",
                            "postbackData", "postback_data_1234",
                            "openUrlAction", Map.of(
                                "url", "http://example.com/"
                            )
                        )
                    )
                )
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Suggested Dial Number

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "text", "Call us to claim your free gift!",
                "suggestions", List.of(
                    Map.of(
                        "action", Map.of(
                            "text", "Call now!",
                            "postbackData", "postback_data_1234",
                            "fallbackUrl", "https://www.example.com/contact/",
                            "dialAction" , Map.of(
                                "phoneNumber", "+447900000000"
                            )
                        )
                    )
                )
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

Send RCS Suggested Share Location

var response = client.getMessagesClient().sendMessage(
    RcsCustomRequest.builder()
        .from(RCS_SENDER_ID).to(TO_NUMBER)
        .custom(Map.of("contentMessage", Map.of(
                "text", "Your driver will come and meet you at your specified location.",
                "suggestions", List.of(
                    Map.of(
                        "action", Map.of(
                            "text", "Share a location",
                            "postbackData", "postback_data_1234",
                            "shareLocationAction", Map.of()
                        )
                    )
                )
            ))
        ).build()
);
System.out.println("Message sent successfully. ID: " + response.getMessageUuid());

MMS

Send MMS Video

var response = client.getMessagesClient().sendMessage(
        MmsVideoRequest.builder()
                .from(FROM_NUMBER).to(TO_NUMBER)
                .url(VIDEO_URL)
                .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send MMS Vcard

var response = client.getMessagesClient().sendMessage(
        MmsVcardRequest.builder()
            .from(FROM_NUMBER).to(TO_NUMBER)
            .url(VCARD_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send MMS Image

var response = client.getMessagesClient().sendMessage(
        MmsImageRequest.builder()
            .from(FROM_NUMBER).to(TO_NUMBER)
            .url(IMAGE_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send MMS Audio

var response = client.getMessagesClient().sendMessage(
        MmsAudioRequest.builder()
                .from(FROM_NUMBER).to(TO_NUMBER)
                .url(AUDIO_URL)
                .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Messenger

Send Messenger Text

var response = client.getMessagesClient().sendMessage(
        MessengerTextRequest.builder()
            .from(VONAGE_FB_SENDER_ID).to(FB_RECIPIENT_ID)
            .text("This is a Facebook Messenger Message sent from the Messages API")
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send Messenger Image

var response = client.getMessagesClient().sendMessage(
        MessengerImageRequest.builder()
            .from(VONAGE_FB_SENDER_ID)
            .to(FB_RECIPIENT_ID)
            .url(IMAGE_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send Messenger Audio

var response = client.getMessagesClient().sendMessage(
        MessengerAudioRequest.builder()
                .from(VONAGE_FB_SENDER_ID)
                .to(FB_RECIPIENT_ID)
                .url(AUDIO_URL)
                .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send Messenger Video

var response = client.getMessagesClient().sendMessage(
        MessengerVideoRequest.builder()
            .from(VONAGE_FB_SENDER_ID)
            .to(FB_RECIPIENT_ID)
            .url(VIDEO_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send Messenger File

var response = client.getMessagesClient().sendMessage(
        MessengerFileRequest.builder()
            .from(VONAGE_FB_SENDER_ID)
            .to(FB_RECIPIENT_ID)
            .url(FILE_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Incoming Message

configureLogging();

Route inboundRoute = (request, response) -> {
    InboundMessage messageDetails = InboundMessage.fromJson(request.body());
    System.out.println(
            "Message ID "+messageDetails.getMessageUuid()+" of type " +
            messageDetails.getMessageType()+" was sent from " +
            messageDetails.getFrom()+" to "+messageDetails.getTo()+" via "+
            messageDetails.getChannel()+" at "+messageDetails.getTimestamp()
    );
    return "OK";
};

Spark.port(3000);
Spark.post("/webhooks/inbound-message", inboundRoute);

Viber

Send Viber Video

var response = client.getMessagesClient().sendMessage(
        ViberVideoRequest.builder()
            .to(TO_NUMBER)
            .from(VONAGE_VIBER_SERVICE_MESSAGE_ID)
            .url("https://example.com/video.mp4")
            .thumbUrl("https://example.com/image.jpg")
            .category(Category.TRANSACTION)
            .fileSize(42).duration(35).ttl(86400)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send Viber Image

var response = client.getMessagesClient().sendMessage(
        ViberImageRequest.builder()
            .from(VIBER_SERVICE_MESSAGE_ID)
            .to(TO_NUMBER)
            .url(IMAGE_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send Viber File

var response = client.getMessagesClient().sendMessage(
        ViberFileRequest.builder()
            .from(VIBER_SERVICE_MESSAGE_ID)
            .to(TO_NUMBER)
            .url(FILE_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send Viber Text

var response = client.getMessagesClient().sendMessage(
        ViberTextRequest.builder()
            .from(FROM_ID).to(TO_NUMBER)
            .text("Don't miss out on our latest offers!")
            .category(Category.PROMOTION)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Sandbox

Messenger

Send Messenger Text
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(MessengerTextRequest.builder()
                .from(envVar("MESSAGES_SANDBOX_FB_ID"))
                .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_FB_RECIPIENT_ID"))
                .text("Don't miss out on our latest offers!")
                .build()
        ).getMessageUuid()
);
Send Messenger Video
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(MessengerVideoRequest.builder()
                .from(envVar("MESSAGES_SANDBOX_FB_ID"))
                .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_FB_RECIPIENT_ID"))
                .url("https://file-examples.com/storage/fee788409562ada83b58ed5/2017/04/file_example_MP4_640_3MG.mp4")
                .build()
        ).getMessageUuid()
);

Viber

Send Viber Video
System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient().useSandboxEndpoint()
        .sendMessage(ViberVideoRequest.builder()
                .from(envVar("MESSAGES_SANDBOX_VIBER_SERVICE_ID"))
                .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
                .category(Category.PROMOTION)
                .duration(Integer.parseInt(envVar("VIDEO_DURATION")))
                .fileSize(Integer.parseInt(envVar("VIDEO_SIZE")))
                .thumbUrl(envVar("THUMB_URL"))
                .url(envVar("VIDEO_URL"))
                .caption("Check out this video!").build()
        ).getMessageUuid()
);
Send Viber Text
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(ViberTextRequest.builder()
                .from(envVar("MESSAGES_SANDBOX_VIBER_SERVICE_ID"))
                .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
                .text("Don't miss out on our latest offers!")
                .category(Category.PROMOTION)
                .build()
        ).getMessageUuid()
);

WhatsApp

Send WhatsApp Location
System.out.println(VonageClient.builder()
        .apiKey(envVar("VONAGE_API_KEY"))
        .apiSecret(envVar("VONAGE_API_SECRET"))
        .build()
        .getMessagesClient()
        .sendMessage(WhatsappLocationRequest.builder()
                .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
                .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
                .longitude(-122.1503115)
                .latitude(37.4843538)
                .name("Facebook HQ")
                .address("1 Hacker Way, Menlo Park, CA 94025")
            .build()
        ).getMessageUuid()
);
Send WhatsApp Text
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappTextRequest.builder()
            .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
            .text("Hello from Vonage, "+System.getenv("NAME"))
            .build()
        ).getMessageUuid()
);
Send WhatsApp Unreaction
System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappReactionRequest.builder()
            .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
            .contextMessageId(envVar("MESSAGE_UUID"))
            .unreact().build()
        ).getMessageUuid()
);
Send WhatsApp Contact
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappCustomRequest.builder()
            .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
            .custom(Map.of(
                "type", "contacts",
                "contacts", List.of(Map.of(
                    "addresses", List.of(
                        Map.of(
                            "city", "Menlo Park",
                            "country", "United States",
                            "state", "CA",
                            "country_code", "us",
                            "street", "1 Hacker Way",
                            "type", "HOME",
                            "zip", "94025"
                        ),
                        Map.of(
                            "city", "Menlo Park",
                            "country", "United States",
                            "state", "CA",
                            "country_code", "us",
                            "street", "200 Jefferson Dr",
                            "type", "WORK",
                            "zip", "94025"
                        )
                    ),
                    "birthday", "2012-08-18",
                    "emails", List.of(
                        Map.of(
                            "email", "test@fb.com",
                            "type", "WORK"
                        ),
                        Map.of(
                            "email", "test@whatsapp.com",
                            "type", "WORK"
                        )
                    ),
                    Map.of("name", Map.of(
                        "first_name", "Jayden",
                        "last_name", "Smith",
                        "formatted_name", "J. Smith"
                    )),
                    Map.of("org", Map.of(
                        "company", "WhatsApp",
                        "department", "Design",
                        "title", "Manager"
                    )),
                    Map.of("phones", List.of(
                        Map.of(
                            "phone", "+1 (940) 555-1234",
                            "type", "HOME"
                        ),
                        Map.of(
                            "phone", "+1 (650) 555-1234",
                            "type", "WORK",
                            "wa_id", "16505551234"
                        )
                    )),
                    Map.of("urls", List.of(
                        Map.of(
                            "url", "https://www.facebook.com",
                            "type", "WORK"
                        )
                    ))
                ))
        ))
        .build()
    ).getMessageUuid()
);
Send WhatsApp Sticker
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappStickerRequest.builder()
            .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
            .url("https://file-examples.com/storage/fe0b804ac5640668798b8d0/2020/03/file_example_WEBP_250kB.webp")
            .build()
        ).getMessageUuid()
);
Send WhatsApp Audio
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappAudioRequest.builder()
            .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
            .url("https://file-examples.com/storage/fee788409562ada83b58ed5/2017/11/file_example_MP3_1MG.mp3")
            .build()
        ).getMessageUuid()
);
Send WhatsApp File
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappFileRequest.builder()
            .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
            .url("https://file-examples.com/storage/fee788409562ada83b58ed5/2017/10/file-sample_150kB.pdf")
            .caption("Accompanying message (optional)")
            .build()
        ).getMessageUuid()
);
Send WhatsApp Image
configureLogging();

System.out.println(VonageClient.builder()
        .apiKey(envVar("VONAGE_API_KEY"))
        .apiSecret(envVar("VONAGE_API_SECRET"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappImageRequest.builder()
                .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
                .url("https://lastfm.freetls.fastly.net/i/u/770x0/a21ed806c65618ea1e7a6c8b4abf0402.jpg")
                .caption("Fluttershy")
                .build()
        ).getMessageUuid()
);
Send WhatsApp Reaction
System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappReactionRequest.builder()
            .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
            .contextMessageId(envVar("MESSAGE_UUID"))
            .reaction(envVar("EMOJI"))
            .build()
        ).getMessageUuid()
);
Send WhatsApp Video
configureLogging();

System.out.println(VonageClient.builder()
        .applicationId(envVar("VONAGE_APPLICATION_ID"))
        .privateKeyPath(envVar("VONAGE_PRIVATE_KEY_PATH"))
        .build()
        .getMessagesClient()
        .useSandboxEndpoint()
        .sendMessage(WhatsappVideoRequest.builder()
            .from(envVar("MESSAGES_SANDBOX_WHATSAPP_NUMBER"))
            .to(envVar("MESSAGES_SANDBOX_ALLOW_LISTED_TO_NUMBER"))
            .url("https://file-examples.com/storage/fee788409562ada83b58ed5/2017/04/file_example_MP4_640_3MG.mp4")
            .build()
        ).getMessageUuid()
);

Message Status Webhook

configureLogging();

Route inboundRoute = (request, response) -> {
    MessageStatus messageDetails = MessageStatus.fromJson(request.body());
    System.out.println(
            "Message ID "+messageDetails.getMessageUuid()+" (status  " + messageDetails.getStatus()+
            ") was sent at "+messageDetails.getTimestamp()+" from " +
            messageDetails.getFrom()+" to "+messageDetails.getTo()+" via "+
            messageDetails.getChannel()+" using "+messageDetails.getChannel()
    );
    return "OK";
};

Spark.port(3000);
Spark.post("/webhooks/message-status", inboundRoute);

WhatsApp

Send WhatsApp Location

var response = client.getMessagesClient().sendMessage(
        WhatsappLocationRequest.builder()
            .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
            .name("Facebook HQ")
            .address("1 Hacker Way, Menlo Park, CA 94025")
            .longitude(-122.1503115).latitude(37.4843538)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Sticker URL

var response = client.getMessagesClient().sendMessage(
        WhatsappStickerRequest.builder()
            .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
            .url(STICKER_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Text

var response = client.getMessagesClient().sendMessage(
        WhatsappTextRequest.builder()
            .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
            .text("This is a WhatsApp Message text message sent using the Messages API")
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Multi Product

var response = client.getMessagesClient().sendMessage(
        WhatsappMultiProductRequest.builder()
            .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
            .catalogId("1166260820787549")
            .headerText("Our top products")
            .bodyText("Check out these great products")
            .addProductsSection("Cool products", Arrays.asList("ch76nhzdeq", "r07qei73l7"))
            .addProductsSection("Awesome product", "unepvzvsfp")
            .footerText("Sale now on!")
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Sticker ID

var response = client.getMessagesClient().sendMessage(
        WhatsappStickerRequest.builder()
            .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
            .id(STICKER_ID)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsAppOT P

Map<String, Object> custom = new LinkedHashMap<>(4);
custom.put("type", "template");
Map<String, Object> template = new LinkedHashMap<>();
template.put("name", WHATSAPP_TEMPLATE_NAME);
custom.put("template", template);
Map<String, Object> language = new LinkedHashMap<>(2);
language.put("code", "en_US");
language.put("policy", "deterministic");
custom.put("language", language);
List<Map<String, Object>> components = new ArrayList<>(2);
Map<String, Object> component1 = new LinkedHashMap<>(2);
component1.put("type", "body");
List<Map<String, Object>> comp1Parameters = new ArrayList<>(1);
Map<String, Object> comp1param1 = new LinkedHashMap<>(2);
comp1param1.put("type", "text");
comp1param1.put("text", "123456");
comp1Parameters.add(comp1param1);
component1.put("parameters", comp1Parameters);
components.add(component1);
Map<String, Object> component2 = new LinkedHashMap<>(4);
component2.put("type", "button");
component2.put("sub_type", "url");
component2.put("index", "0");
component2.put("parameters", comp1Parameters);
components.add(component2);
custom.put("components", components);

WhatsappCustomRequest message = WhatsappCustomRequest.builder()
        .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
        .custom(custom).build();

client.getMessagesClient().sendMessage(message);

Send WhatsApp Quick Reply Button

var response = client.getMessagesClient().sendMessage(
    WhatsappCustomRequest.builder()
        .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
        .custom(Map.of(
                "type", MessageType.TEMPLATE,
                "template", Map.of(
                    "namespace", WHATSAPP_TEMPLATE_NAMESPACE,
                    "name", WHATSAPP_TEMPLATE_NAME,
                    "language", Map.of(
                        "code", Locale.ENGLISH,
                        "policy", Policy.DETERMINISTIC
                    ),
                    "components", List.of(
                        Map.of(
                            "type", "header",
                            "parameters", List.of(
                                Map.of(
                                    "type", MessageType.TEXT,
                                    "text", "12/26"
                                )
                            )
                        ),
                        Map.of(
                            "type", "body",
                            "parameters", List.of(
                                Map.of(
                                    "type", MessageType.TEXT,
                                    "text", "*Ski Trip*"
                                ),
                                Map.of(
                                    "type", MessageType.TEXT,
                                    "text", "2019-12-26"
                                ),
                                Map.of(
                                    "type", MessageType.TEXT,
                                    "text", "*Squaw Valley Ski Resort, Tahoe*"
                                )
                            )
                        ),
                        Map.of(
                            "type", MessageType.BUTTON,
                            "sub_type", "quick_reply",
                            "index", 0,
                            "parameters", List.of(
                                Map.of(
                                    "type", "payload",
                                    "payload", "Yes-Button-Payload"
                                )
                            )
                        ),
                        Map.of(
                            "type", MessageType.BUTTON,
                            "sub_type", "quick_reply",
                            "index", 1,
                            "parameters", List.of(
                                Map.of(
                                    "type", "payload",
                                    "payload", "No-Button-Payload"
                                )
                            )
                        )
                    )
                )
        )).build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Media Template

var response = client.getMessagesClient().sendMessage(
    WhatsappCustomRequest.builder()
        .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
        .custom(Map.of(
                "type", MessageType.TEMPLATE,
                "template", Map.of(
                    "name", WHATSAPP_TEMPLATE_NAME,
                    "language", Map.of(
                        "policy", Policy.DETERMINISTIC,
                        "code", Locale.ENGLISH
                    ),
                    "components", List.of(
                        Map.of(
                            "type", "header",
                            "parameters", List.of(
                                Map.of(
                                    "type", MessageType.IMAGE,
                                    "image", Map.of(
                                        "link", IMAGE_URL
                                    )
                                )
                            )
                        ),
                        Map.of(
                            "type", "body",
                            "parameters", List.of(
                                Map.of(
                                    "type", MessageType.TEXT,
                                    "text", WHATSAPP_TEMPLATE_REPLACEMENT_TEXT
                                )
                            )
                        )
                    )
                )
        )).build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Unreaction

var response = client.getMessagesClient().sendMessage(
    WhatsappReactionRequest.builder()
        .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
        .contextMessageId(MESSAGE_UUID)
        .unreact().build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Mark As Read

client.getMessagesClient().ackInboundMessage(MESSAGE_UUID, ApiRegion.API_EU);

Send WhatsApp Contact

var response = client.getMessagesClient().sendMessage(
        WhatsappCustomRequest.builder()
            .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
            .custom(Map.of(
                "type", "contacts",
                "contacts", List.of(Map.of(
                    "addresses", List.of(
                        Map.of(
                            "city", "Menlo Park",
                            "country", "United States",
                            "state", "CA",
                            "country_code", "us",
                            "street", "1 Hacker Way",
                            "type", "HOME",
                            "zip", "94025"
                        ),
                        Map.of(
                            "city", "Menlo Park",
                            "country", "United States",
                            "state", "CA",
                            "country_code", "us",
                            "street", "200 Jefferson Dr",
                            "type", "WORK",
                            "zip", "94025"
                        )
                    ),
                    "birthday", "2012-08-18",
                    "emails", List.of(
                        Map.of(
                            "email", "test@fb.com",
                            "type", "WORK"
                        ),
                        Map.of(
                            "email", "test@whatsapp.com",
                            "type", "WORK"
                        )
                    ),
                    Map.of("name", Map.of(
                        "first_name", "Jayden",
                        "last_name", "Smith",
                        "formatted_name", "J. Smith"
                    )),
                    Map.of("org", Map.of(
                        "company", "WhatsApp",
                        "department", "Design",
                        "title", "Manager"
                    )),
                    Map.of("phones", List.of(
                        Map.of(
                            "phone", "+1 (940) 555-1234",
                            "type", "HOME"
                        ),
                        Map.of(
                            "phone", "+1 (650) 555-1234",
                            "type", "WORK",
                            "wa_id", "16505551234"
                        )
                    )),
                    Map.of("urls", List.of(
                        Map.of(
                            "url", "https://www.facebook.com",
                            "type", "WORK"
                        )
                    ))
                ))
            ))
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Template

var response = client.getMessagesClient().sendMessage(
        WhatsappTemplateRequest.builder()
            .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
            .policy(Policy.DETERMINISTIC).locale(Locale.ENGLISH_UK)
            .name(WHATSAPP_TEMPLATE_NAMESPACE+':'+WHATSAPP_TEMPLATE_NAME)
            .parameters(List.of(
                    "Vonage Verification",
                    "64873",
                    "10"
            ))
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Single Product

var response = client.getMessagesClient().sendMessage(
        WhatsappSingleProductRequest.builder()
            .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
            .catalogId(CATALOG_ID)
            .productRetailerId(PRODUCT_ID)
            .bodyText("Check out this cool product")
            .footerText("Sale now on!")
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Audio

var response = client.getMessagesClient().sendMessage(
        WhatsappAudioRequest.builder()
            .to(TO_NUMBER)
            .from(VONAGE_WHATSAPP_NUMBER)
            .url(AUDIO_URL)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp File

var response = client.getMessagesClient().sendMessage(
        WhatsappFileRequest.builder()
            .to(TO_NUMBER).from(VONAGE_WHATSAPP_NUMBER)
            .url(FILE_URL).caption(FILE_CAPTION)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Image

var response = client.getMessagesClient().sendMessage(
        WhatsappImageRequest.builder()
            .to(TO_NUMBER).from(VONAGE_WHATSAPP_NUMBER)
            .url(IMAGE_URL).caption(IMAGE_CAPTION)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Link Button

var response = client.getMessagesClient().sendMessage(
    WhatsappCustomRequest.builder()
        .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
        .custom(Map.of(
            "type", "template",
            "template", Map.of(
                "namespace", WHATSAPP_TEMPLATE_NAMESPACE,
                "name", WHATSAPP_TEMPLATE_NAME,
                "language", Map.of(
                    "code", Locale.ENGLISH,
                    "policy", Policy.DETERMINISTIC
                ),
                "components", List.of(
                    Map.of(
                        "type", "header",
                        "parameters", List.of(
                            Map.of(
                                "type", "image",
                                "image", Map.of(
                                    "link", HEADER_IMAGE_URL
                                )
                            )
                        )
                    ),
                    Map.of(
                        "type", "body",
                        "parameters", List.of(
                            Map.of(
                                "type", "text",
                                "text", "Anand"
                            ),
                            Map.of(
                                "type", "text",
                                "text", "Quest"
                            ),
                            Map.of(
                                "type", "text",
                                "text", "113-0921387"
                            ),
                            Map.of(
                                "type", "text",
                                "text", "23rd Nov 2019"
                            )
                        )
                    ),
                    Map.of(
                        "type", "button",
                        "index", "0",
                        "sub_type", "url",
                        "parameters", List.of(
                            Map.of(
                                "type", "text",
                                "text", "1Z999AA10123456784"
                            )
                        )
                    )
                )
            )
        ))
        .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Reaction

var response = client.getMessagesClient().sendMessage(
    WhatsappReactionRequest.builder()
        .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
        .contextMessageId(MESSAGE_UUID)
        .reaction(EMOJI).build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Video

var response = client.getMessagesClient().sendMessage(
        WhatsappVideoRequest.builder()
            .to(TO_NUMBER).from(VONAGE_WHATSAPP_NUMBER)
            .url(VIDEO_URL).caption(VIDEO_CAPTION)
            .build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Send WhatsApp Authentication Template

var response = client.getMessagesClient().sendMessage(
    WhatsappCustomRequest.builder()
        .from(VONAGE_WHATSAPP_NUMBER).to(TO_NUMBER)
        .custom(Map.of(
                "type", MessageType.TEMPLATE,
                "template", Map.of(
                    "name", WHATSAPP_AUTH_TEMPLATE_NAME,
                    "language", Map.of(
                        "policy", Policy.DETERMINISTIC,
                        "code", Locale.ENGLISH
                    ),
                    "components", List.of(
                        Map.of(
                            "type", "body",
                            "parameters", List.of(
                                Map.of(
                                    "type", MessageType.TEXT,
                                    "text", OTP
                                )
                            )
                        ),
                        Map.of(
                            "type", MessageType.BUTTON,
                            "sub_type", "url",
                            "index", 0,
                            "parameters", List.of(
                                Map.of(
                                    "type", MessageType.TEXT,
                                    "text", OTP
                                )
                            )
                        )
                    )
                )
        )).build()
);
System.out.println("Message sent successfully. ID: "+response.getMessageUuid());

Fraud Detection

Fraud Score

var response = client.getNumberInsight2Client().fraudCheck(INSIGHT_NUMBER, Insight.FRAUD_SCORE);
var fraudScore = response.getFraudScore();
System.out.println(fraudScore);

SIM Swap

var response = client.getNumberInsight2Client().fraudCheck(INSIGHT_NUMBER, Insight.SIM_SWAP);
var simSwap = response.getSimSwap();
System.out.println(simSwap);

Numbers

Cancel Number

client.getNumbersClient().cancelNumber(COUNTRY_CODE, VONAGE_NUMBER);

Buy Number

client.getNumbersClient().buyNumber(COUNTRY_CODE, VONAGE_NUMBER);

Search Numbers

SearchNumbersResponse response = client.getNumbersClient().searchNumbers(
        SearchNumbersFilter.builder()
            .country(COUNTRY_CODE)
            .type(VONAGE_NUMBER_TYPE)
            .features(VONAGE_NUMBER_FEATURES)
            .pattern(NUMBER_SEARCH_PATTERN, NUMBER_SEARCH_CRITERIA)
            .build()
);

System.out.println("Here are "
        + response.getNumbers().length
        + " of the " + response.getCount()
        + " matching numbers available for purchase."
);

for (AvailableNumber number : response.getNumbers()) {
    System.out.println("Tel: " + number.getMsisdn());
    System.out.println("Cost: " + number.getCost());
}

Update Number

client.getNumbersClient().updateNumber(
        UpdateNumberRequest.builder(VONAGE_NUMBER, COUNTRY_CODE)
            .moHttpUrl(SMS_CALLBACK_URL)
            .voiceCallback(VOICE_CALLBACK_TYPE, VOICE_CALLBACK_VALUE)
            .voiceStatusCallback(VOICE_STATUS_URL)
            .build()
);

List Numbers

ListNumbersResponse response = client.getNumbersClient().listNumbers(
        ListNumbersFilter.builder()
                .pattern(NUMBER_SEARCH_PATTERN, NUMBER_SEARCH_CRITERIA)
                .build()
);

for (OwnedNumber number : response.getNumbers()) {
    System.out.println("Tel: " + number.getMsisdn());
    System.out.println("Type: " + number.getType());
    System.out.println("Country: " + number.getCountry());
}

Redact

RedactA Transaction

client.getRedactClient().redactTransaction(VONAGE_REDACT_ID, VONAGE_REDACT_PRODUCT);

SIM Swap

Retrieve SIM Swap Date

Instant lastSwapDate = client.getSimSwapClient().retrieveSimSwapDate(TO_NUMBER);
System.out.println(lastSwapDate);

SIM Swapped

boolean swapped = client.getSimSwapClient().checkSimSwap(TO_NUMBER, 960);
System.out.println("SIM for "+TO_NUMBER +
        " has "+(swapped ? "" : "not ") + "been swapped in the past 960 hours."
);

SMS

Receive Signed SMS

/*
 * Route to handle incoming SMS GET request.
 */
Route inboundSmsAsGet = (req, res) -> {
    String signatureSecret = envVar("VONAGE_SIGNATURE_SECRET");
    System.out.println(signatureSecret);
    if (RequestSigning.verifyRequestSignature(
            req.raw().getInputStream(),
            req.contentType(),
            req.queryMap().toMap(),
            signatureSecret
    )) {
        System.out.println("msisdn: " + req.queryParams("msisdn"));
        System.out.println("messageId: " + req.queryParams("messageId"));
        System.out.println("text: " + req.queryParams("text"));
        System.out.println("type: " + req.queryParams("type"));
        System.out.println("keyword: " + req.queryParams("keyword"));
        System.out.println("messageTimestamp: " + req.queryParams("message-timestamp"));

        res.status(204);
    }
    else {
        System.out.println("Bad signature");
        res.status(401);
    }

    return "";
};

Spark.port(5000);
Spark.get("/webhooks/inbound-sms", inboundSmsAsGet);

ReceiveDL R

Util.configureLogging();

port(3000);

get("/webhooks/delivery-receipt", (req, res) -> {
    for (String param : req.queryParams()) {
        System.out.printf("%s: %s\n", param, req.queryParams(param));
    }
    res.status(204);
    return "";
});

post("/webhooks/delivery-receipt", (req, res) -> {
    // The body will be form-encoded or a JSON object:
    if (req.contentType().startsWith("application/x-www-form-urlencoded")) {
        for (String param : req.queryParams()) {
            System.out.printf("%s: %s\n", param, req.queryParams(param));
        }
    } else {
        System.out.println(req.body());
    }

    res.status(204);
    return "";
});

ReceiveSM S

/*
 * Route to handle incoming SMS GET request.
 */
Route inboundSmsAsGet = (req, res) -> {
    System.out.println("msisdn: " + req.queryParams("msisdn"));
    System.out.println("messageId: " + req.queryParams("messageId"));
    System.out.println("text: " + req.queryParams("text"));
    System.out.println("type: " + req.queryParams("type"));
    System.out.println("keyword: " + req.queryParams("keyword"));
    System.out.println("messageTimestamp: " + req.queryParams("message-timestamp"));

    res.status(204);
    return "";
};

/*
 * Route to handle incoming SMS with POST form-encoded or JSON body.
 */
Route inboundSmsAsPost = (req, res) -> {
    // The body will be form-encoded or a JSON object:
    if (req.contentType().startsWith("application/x-www-form-urlencoded")) {
        System.out.println("msisdn: " + req.queryParams("msisdn"));
        System.out.println("messageId: " + req.queryParams("messageId"));
        System.out.println("text: " + req.queryParams("text"));
        System.out.println("type: " + req.queryParams("type"));
        System.out.println("keyword: " + req.queryParams("keyword"));
        System.out.println("messageTimestamp: " + req.queryParams("message-timestamp"));
    } else {
        MessageEvent event = MessageEvent.fromJson(req.body());

        System.out.println("msisdn: " + event.getMsisdn());
        System.out.println("messageId: " + event.getMessageId());
        System.out.println("text: " + event.getText());
        System.out.println("type: " + event.getType());
        System.out.println("keyword: " + event.getKeyword());
        System.out.println("messageTimestamp: " + event.getMessageTimestamp());
    }

    res.status(204);
    return "";
};

Spark.port(8080);
Spark.get("/webhooks/inbound-sms", inboundSmsAsGet);
Spark.post("/webhooks/inbound-sms", inboundSmsAsPost);

Send Unicode Message

TextMessage message = new TextMessage(VONAGE_BRAND_NAME, TO_NUMBER, "Blue Öyster Cult \uD83E\uDD18", true);

SmsSubmissionResponse responses = client.getSmsClient().submitMessage(message);

for (SmsSubmissionResponseMessage responseMessage : responses.getMessages()) {
    System.out.println(message);
}

Send Message

TextMessage message = new TextMessage(VONAGE_BRAND_NAME,
        TO_NUMBER,
        "A text message sent using the Vonage SMS API"
);

SmsSubmissionResponse response = client.getSmsClient().submitMessage(message);

if (response.getMessages().get(0).getStatus() == MessageStatus.OK) {
    System.out.println("Message sent successfully.");
} else {
    System.out.println("Message failed with error: " + response.getMessages().get(0).getErrorText());
}

Send Signed SMS

right 2024 Vonage
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.vonage.quickstart.sms;

import com.vonage.client.VonageClient;
import com.vonage.client.sms.MessageStatus;
import com.vonage.client.sms.SmsSubmissionResponse;
import com.vonage.client.sms.messages.TextMessage;
import com.vonage.client.auth.hashutils.HashUtil;

import static com.vonage.quickstart.Util.configureLogging;
import static com.vonage.quickstart.Util.envVar;

public class SendSignedSms {

    public static void main(String[] args) throws Exception {
        configureLogging();

        String VONAGE_API_KEY = envVar("VONAGE_API_KEY");
        String VONAGE_SIGNATURE_SECRET = envVar("VONAGE_SIGNATURE_SECRET");
        String TO_NUMBER = envVar("TO_NUMBER");
        String VONAGE_BRAND_NAME = envVar("VONAGE_BRAND_NAME");

        VonageClient client = VonageClient.builder()
            .apiKey(VONAGE_API_KEY)
            .signatureSecret(VONAGE_SIGNATURE_SECRET)
            .hashType(HashUtil.HashType.MD5).build();

        TextMessage message = new TextMessage(VONAGE_BRAND_NAME,
                TO_NUMBER,
                "A text message sent using the Vonage SMS API"
        );

        SmsSubmissionResponse response = client.getSmsClient().submitMessage(message);

        if (response.getMessages().get(0).getStatus() == MessageStatus.OK) {
            System.out.println("Message sent successfully.");
        } else {
            System.out.println("Message failed with error: " + response.getMessages().get(0).getErrorText());
        }

Subaccounts

Transfer Credit

MoneyTransfer receipt = client.getSubaccountsClient().transferCredit(
        MoneyTransfer.builder()
            .from(VONAGE_API_KEY).to(SUBACCOUNT_KEY)
            .amount(AMOUNT).build()
);
System.out.println("Transfer successful: "+receipt.getId());

Transfer Balance

MoneyTransfer receipt = client.getSubaccountsClient().transferBalance(
        MoneyTransfer.builder()
            .from(VONAGE_API_KEY).to(SUBACCOUNT_KEY)
            .amount(AMOUNT).build()
);
System.out.println("Transfer successful: "+receipt.getId());

List Balance Transfers

List<MoneyTransfer> transfers = client.getSubaccountsClient().listBalanceTransfers();

List Subaccounts

ListSubaccountsResponse response = client.getSubaccountsClient().listSubaccounts();

Get Subaccount

Account subaccount = client.getSubaccountsClient().getSubaccount(SUBACCOUNT_KEY);

Deactivate Subaccount

Account subaccount = client.getSubaccountsClient().updateSubaccount(
        UpdateSubaccountRequest.builder(SUBACCOUNT_KEY).suspended(true).build()
);

Rename Subaccount

Account subaccount = client.getSubaccountsClient().updateSubaccount(
        UpdateSubaccountRequest.builder(SUBACCOUNT_KEY)
                .name(NEW_SUBACCOUNT_NAME).build()
);

Create Subaccount

Account subaccount = client.getSubaccountsClient().createSubaccount(
        CreateSubaccountRequest.builder()
            .name(NEW_SUBACCOUNT_NAME)
            .secret(NEW_SUBACCOUNT_SECRET)
            .build()
);

Transfer Number

NumberTransfer transfer = NumberTransfer.builder()
        .from(VONAGE_API_KEY).to(SUBACCOUNT_KEY)
        .number(NUMBER).build();

client.getSubaccountsClient().transferNumber(transfer);

Reactivate Subaccount

Account subaccount = client.getSubaccountsClient().updateSubaccount(
        UpdateSubaccountRequest.builder(SUBACCOUNT_KEY).suspended(false).build()
);

List Credit Transfers

List<MoneyTransfer> transfers = client.getSubaccountsClient().listCreditTransfers();

Users

Update User

User user = client.getUsersClient().updateUser(
    USER_ID, User.builder()
        .name(USER_NEW_NAME)
        .displayName(USER_NEW_DISPLAY_NAME)
        .build()
);

Get User

User user = client.getUsersClient().getUser(USER_ID);

Delete User

client.getUsersClient().deleteUser(USER_ID);

Create User

User user = client.getUsersClient().createUser(
    User.builder()
        .name(USER_NAME)
        .displayName(USER_DISPLAY_NAME)
        .imageUrl("https://example.com/profile.jpg")
        .channels(
            new Pstn("448001234567"),
            new Sms("447700900000"),
            new Viber("447700900000"),
            new Whatsapp("447700900000"),
            new Viber("447700900000"),
            new Messenger("12345abcd"),
            new Vbc(123),
            new Sip("sip:4442138907@sip.example.com;transport=tls", "myUserName", "P@ssw0rd"),
            new Websocket("wss://example.com/socket")
        )
        .build()
);

List Users

List<BaseUser> users = client.getUsersClient().listUsers();

Verify

Cancel Verification

ControlResponse response = client.getVerifyClient().cancelVerification(REQUEST_ID);

String errorText = response.getErrorText();
if (errorText != null) {
    System.out.println("Cancellation failed: " + errorText);
}
else {
    System.out.println("Verification cancelled.");
}

Advance Verification

ControlResponse response = client.getVerifyClient().advanceVerification(REQUEST_ID);

String errorText = response.getErrorText();
if (errorText != null) {
    System.out.println("Couldn't advance workflow: " + errorText);
}
else {
    System.out.println("Verification advanced to next stage!");
}

Start Verification With Workflow

VerifyResponse response = client.getVerifyClient().verify(
        RECIPIENT_NUMBER,BRAND_NAME, VerifyRequest.Workflow.TTS_TTS
);

if (response.getStatus() == VerifyStatus.OK) {
    System.out.printf("RequestID: %s", response.getRequestId());
}
else {
    System.out.printf("ERROR! %s: %s", response.getStatus(), response.getErrorText());
}

Search Verification

SearchVerifyResponse response = client.getVerifyClient().search(REQUEST_ID);
if (response.getStatus() == VerifyStatus.OK) {
    response.getVerificationRequests().forEach(it -> {
        System.out.println(it.getRequestId() + " " + it.getStatus());
    });
}

Check Verification

CheckResponse response = client.getVerifyClient().check(REQUEST_ID, CODE);

if (response.getStatus() == VerifyStatus.OK) {
    System.out.println("Verification Successful");
}
else {
    System.out.println("Verification failed: " + response.getErrorText());
}

Start Verification

VerifyResponse response = client.getVerifyClient().verify(RECIPIENT_NUMBER, BRAND_NAME);

if (response.getStatus() == VerifyStatus.OK) {
    System.out.printf("RequestID: %s", response.getRequestId());
}
else {
    System.out.printf("ERROR! %s: %s", response.getStatus(), response.getErrorText());
}

Start PSD2 Verification With Workflow

VerifyResponse response = client.getVerifyClient().psd2Verify(
        RECIPIENT_NUMBER, AMOUNT, PAYEE_NAME, Psd2Request.Workflow.SMS_SMS
);

if (response.getStatus() == VerifyStatus.OK) {
    System.out.printf("Request ID: %s", response.getRequestId());
}
else {
    System.out.printf("Error: %s: %s", response.getStatus(), response.getErrorText());
}

Start PSD2 Verification

VerifyResponse response = client.getVerifyClient().psd2Verify(RECIPIENT_NUMBER, AMOUNT, PAYEE_NAME);

if (response.getStatus() == VerifyStatus.OK) {
    System.out.printf("Request ID: %s", response.getRequestId());
}
else {
    System.out.printf("Error: %s: %s", response.getStatus(), response.getErrorText());
}

Verify v2

Send Request WhatsApp

VerificationResponse response = client.getVerify2Client().sendVerification(
        VerificationRequest.builder()
            .addWorkflow(new WhatsappWorkflow(TO_NUMBER, WHATSAPP_BUSINESS_NUMBER))
            .brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());

Delete Template

client.getVerify2Client().deleteTemplate(TEMPLATE_ID);

Send Request All Channels

var request = VerificationRequest.builder()
        .workflows(List.of(
                new SilentAuthWorkflow(TO_NUMBER),
                new WhatsappCodelessWorkflow(TO_NUMBER, WHATSAPP_BUSINESS_NUMBER),
                new EmailWorkflow(TO_EMAIL),
                new WhatsappWorkflow(TO_NUMBER, WHATSAPP_BUSINESS_NUMBER),
                new SmsWorkflow(TO_NUMBER),
                new VoiceWorkflow(TO_NUMBER)
        ))
        .codeLength(7)
        .brand(BRAND_NAME)
        .locale("en-gb")
        .channelTimeout(120)
        .build();

var requestId = client.getVerify2Client().sendVerification(request).getRequestId();
System.out.println("Verification sent: "+requestId);

Send Request Email

VerificationResponse response = client.getVerify2Client().sendVerification(
        VerificationRequest.builder()
            .addWorkflow(new EmailWorkflow(TO_EMAIL))
            .brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());

Send Request Voice

VerificationResponse response = client.getVerify2Client().sendVerification(
        VerificationRequest.builder()
                .addWorkflow(new VoiceWorkflow(TO_NUMBER))
                .brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());

Send Request SMS

VerificationResponse response = client.getVerify2Client().sendVerification(
        VerificationRequest.builder()
            .addWorkflow(new SmsWorkflow(TO_NUMBER))
            .brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());

Send Request With Fallback

VerificationResponse response = client.getVerify2Client().sendVerification(
        VerificationRequest.builder()
            .addWorkflow(new SilentAuthWorkflow(TO_NUMBER))
            .addWorkflow(new EmailWorkflow(TO_EMAIL))
            .brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());

Check Verification Code

try {
    client.getVerify2Client().checkVerificationCode(REQUEST_ID, CODE);
    System.out.println("SUCCESS - code matches!");
}
catch (VerifyResponseException ex) {
    switch (ex.getStatusCode()) {
        case 400: // Code does not match
        case 404: // Already verified or not found
        case 409: // Workflow does not support code
        case 410: // Incorrect code provided too many times
        case 429: // Rate limit exceeded
        default:  // Unknown or internal server error (500)
            ex.printStackTrace();
    }
}

Get Template

var template = client.getVerify2Client().getTemplate(TEMPLATE_ID);
System.out.println(template);

List Templates

var templates = client.getVerify2Client().listTemplates();
templates.forEach(t -> System.out.println(t.getId()));

Send Request Silent Auth

VerificationResponse response = client.getVerify2Client().sendVerification(
        VerificationRequest.builder()
            .addWorkflow(new SilentAuthWorkflow(TO_NUMBER))
            .brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());

List Template Fragments

var fragments = client.getVerify2Client().listTemplateFragments(TEMPLATE_ID);
fragments.forEach(f -> System.out.println(f.getFragmentId()));

Create Template

var template = client.getVerify2Client().createTemplate("My_template");
System.out.println(template.getId());

Update Template Fragment

var updated = client.getVerify2Client().updateTemplateFragment(
        TEMPLATE_ID, TEMPLATE_FRAGMENT_ID,
        "The authentication code for your ${brand} is: ${code}"
);
System.out.println(updated);

Create Template Fragment

var fragment = client.getVerify2Client().createTemplateFragment(
        TEMPLATE_ID, new TemplateFragment(
                FragmentChannel.SMS, "en-us",
                "The authentication code for your ${brand} is: ${code}"
        )
);
System.out.println(fragment);

Update Template

var updated = client.getVerify2Client().updateTemplate(TEMPLATE_ID, "My_renamed_template", false);
System.out.println(updated);

Send Request WhatsApp Interactive

VerificationResponse response = client.getVerify2Client().sendVerification(
        VerificationRequest.builder()
            .addWorkflow(new WhatsappCodelessWorkflow(TO_NUMBER, WHATSAPP_BUSINESS_NUMBER))
            .brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());

Cancel Request

client.getVerify2Client().cancelVerification(REQUEST_ID);

Get Template Fragment

var fragment = client.getVerify2Client().getTemplateFragment(TEMPLATE_ID, TEMPLATE_FRAGMENT_ID);
System.out.println(fragment);

Delete Template Fragment

client.getVerify2Client().deleteTemplateFragment(TEMPLATE_ID, TEMPLATE_FRAGMENT_ID);

Voice

Retrieve Call Info

CallInfo details = client.getVoiceClient().getCallDetails(CALL_UUID);
System.out.println(details);

Record Message

/*
 * Route to answer and connect incoming calls with recording.
 */
Route answerRoute = (req, res) -> {
    String recordingUrl = String.format("%s://%s/webhooks/recordings", req.scheme(), req.host());

    TalkAction intro = TalkAction.builder(
            "Please leave a message after the tone, then press #. We will get back to you as soon as we can.").build();

    RecordAction record = RecordAction.builder()
            .eventUrl(recordingUrl)
            .endOnSilence(3)
            .endOnKey('#')
            .beepStart(true)
            .build();

    TalkAction outro = TalkAction.builder("Thank you for your message. Goodbye").build();

    res.type("application/json");

    return new Ncco(intro, record, outro).toJson();
};

/*
 * Route which prints out the recording URL it is given to stdout.
 */
Route recordingRoute = (req, res) -> {
    EventWebhook recordEvent = EventWebhook.fromJson(req.body());
    System.out.println(recordEvent.getRecordingUrl());

    res.status(204);
    return "";
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/recordings", recordingRoute);

Outbound Text To Speech With Event URL

Call call = Call.builder()
        .from(VONAGE_NUMBER).to(new PhoneEndpoint(TO_NUMBER))
        .answerUrl(ANSWER_URL).eventUrl(EVENT_URL).build();

var response = client.getVoiceClient().createCall(call);
System.out.println(response);

Track NCCO Progress

port(3000);

/*
 * Answer Route
 */
get("/webhooks/answer", (req, res) -> {
    String notifyUrl = String.format("%s://%s/webhooks/notification", req.scheme(), req.host());

    TalkAction intro = TalkAction.builder("Thanks for calling the notification line.")
            .build();

    Map<String, String> payload = new HashMap<>();
    payload.put("foo", "bar");

    NotifyAction notify = NotifyAction.builder(payload)
            .eventUrl(notifyUrl)
            .build();

    TalkAction unheard = TalkAction.builder("You will never hear me as the notification URL will return an NCCO")
            .build();

    res.type("application/json");
    return new Ncco(intro, notify, unheard).toJson();
});

/*
 * Notification Route
 */
post("/webhooks/notification", (req, res) -> {
    res.type("application/json");
    return new Ncco(
            TalkAction.builder("Your notification has been received, loud and clear.")
                    .build()
    ).toJson();
});

Transfer Call NCCO

TalkAction talkAction = TalkAction.builder("This is a transfer action using an inline NCCO.").build();
client.getVoiceClient().transferCall(CALL_UUID, new Ncco(talkAction));

Mute Call

client.getVoiceClient().muteCall(CALL_UUID);
Thread.sleep(3000);
client.getVoiceClient().unmuteCall(CALL_UUID);

End Call

client.getVoiceClient().terminateCall(CALL_UUID);

Transfer Call

final String NCCO_URL = "https://nexmo-community.github.io/ncco-examples/talk.json";

client.getVoiceClient().transferCall(CALL_UUID, NCCO_URL);

Record Conversation

final String CONF_NAME = "conf-name";

/*
 * Route to answer and connect incoming calls with recording.
 */
Route answerRoute = (req, res) -> {
    String recordingUrl = String.format("%s://%s/webhooks/recordings", req.scheme(), req.host());

    ConversationAction conversation = ConversationAction.builder(CONF_NAME)
            .record(true)
            .eventMethod(EventMethod.POST)
            .eventUrl(recordingUrl)
            .build();

    res.type("application/json");

    return new Ncco(conversation).toJson();
};

/*
 * Route which prints out the recording URL it is given to stdout.
 */
Route recordingWebhookRoute = (req, res) -> {
    System.out.println(EventWebhook.fromJson(req.body()).getRecordingUrl());

    res.status(204);
    return "";
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/recordings", recordingWebhookRoute);

Download Recording

/*
 * A recording webhook endpoint which automatically downloads the specified recording to a file in the
 * current working directory, called "downloaded_recording.mp3"
 */
Route downloadRoute = (req, res) -> {
    EventWebhook event = EventWebhook.fromJson(req.body());
    String recordingUrl = event.getRecordingUrl().toString();
    Path recordingFile = Paths.get("downloaded_recording.mp3");
    System.out.println("Downloading from " + recordingUrl);
    client.getVoiceClient().saveRecording(recordingUrl, recordingFile);
    return "OK";
};

Spark.port(3000);
Spark.post("/recording", downloadRoute);

Earmuff Call

client.getVoiceClient().earmuffCall(CALL_UUID);
Thread.sleep(3000);
client.getVoiceClient().unearmuffCall(CALL_UUID);

Conference Call

final String CONF_NAME = "my-conference";

/*
 * Route to answer incoming calls with an NCCO response.
 */
Route answerRoute = (req, res) -> {
    TalkAction intro = TalkAction.builder("Please wait while we connect you to the conference.").build();
    ConversationAction conversation = ConversationAction.builder(CONF_NAME).build();

    res.type("application/json");

    return new Ncco(intro, conversation).toJson();
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/answer", answerRoute);

Record Call

final String TO_NUMBER = envVar("TO_NUMBER");
final String VONAGE_NUMBER = envVar("VONAGE_NUMBER");

/*
 * Route to answer and connect incoming calls with recording.
 */
Route answerRoute = (req, res) -> {
    String recordingUrl = String.format("%s://%s/webhooks/recordings", req.scheme(), req.host());

    RecordAction record = RecordAction.builder().eventUrl(recordingUrl).build();

    ConnectAction connect = ConnectAction.builder(PhoneEndpoint.builder(TO_NUMBER).build())
            .from(VONAGE_NUMBER)
            .build();

    res.type("application/json");

    return new Ncco(record, connect).toJson();
};

/*
 * Route which prints out the recording URL it is given to stdout.
 */
Route recordingRoute = (req, res) -> {
    System.out.println(EventWebhook.fromJson(req.body()).getRecordingUrl());

    res.status(204);
    return "";
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/recordings", recordingRoute);

Stream Audio To Call

final String URL = "https://nexmo-community.github.io/ncco-examples/assets/voice_api_audio_streaming.mp3";

var response = client.getVoiceClient().startStream(CALL_UUID, URL, 0);
Thread.sleep(5000);
response = client.getVoiceClient().stopStream(CALL_UUID);

Inbound Call

/*
 * Route to answer incoming call.
 */
Route answerRoute = (req, res) -> {
    String from = req.queryParams("from").replace("", " ");
    TalkAction message = TalkAction
            .builder(String.format("Thank you for calling from %s", from))
            .build();

    res.type("application/json");

    return new Ncco(message).toJson();
};

/*
 * Route to print out call event info.
 */
Route eventRoute = (req, res) -> {
    System.out.println(req.body());
    return "";
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/events", eventRoute);

Retrieve Info For All Calls

Date yesterday = new Date(Instant.now().minus(Duration.ofDays(1)).toEpochMilli());
Date now = new Date();

CallsFilter filter = CallsFilter.builder()
        .dateStart(yesterday)
        .dateEnd(now)
        .build();

CallInfoPage calls = client.getVoiceClient().listCalls(filter);
System.out.println(calls.toJson());

Record Call Split Audio

final String TO_NUMBER = envVar("TO_NUMBER");
final String VONAGE_NUMBER = envVar("VONAGE_NUMBER");

/*
 * Route to answer and connect incoming calls with recording.
 */
Route answerRoute = (req, res) -> {
    String recordingUrl = String.format("%s://%s/webhooks/recordings", req.scheme(), req.host());

    RecordAction record = RecordAction.builder()
            .eventUrl(recordingUrl)
            .channels(2)
            .split(SplitRecording.CONVERSATION)
            .build();

    ConnectAction connect = ConnectAction.builder(PhoneEndpoint.builder(TO_NUMBER).build())
            .from(VONAGE_NUMBER)
            .build();

    res.type("application/json");

    return new Ncco(record, connect);
};

/*
 * Route which prints out the recording URL it is given to stdout.
 */
Route recordingRoute = (req, res) -> {
    System.out.println(EventWebhook.fromJson(req.body()).getRecordingUrl());

    res.status(204);
    return "";
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/recordings", recordingRoute);

DTMF Input

/*
 * Route to answer incoming calls.
 */
Route answerRoute = (req, res) -> {
    TalkAction intro = TalkAction
            .builder("Hello. Please press any key to continue.")
            .build();

    DtmfSettings dtmfSettings = new DtmfSettings();
    dtmfSettings.setMaxDigits(1);

    InputAction input = InputAction.builder()
            .type(Collections.singletonList("dtmf"))
            .eventUrl(String.format("%s://%s/webhooks/dtmf", req.scheme(), req.host()))
            .dtmf(dtmfSettings)
            .build();


    res.type("application/json");

    return new Ncco(intro, input).toJson();
};

/*
 * Route which returns NCCO saying which DTMF code was received.
 */
Route inputRoute = (req, res) -> {
    EventWebhook event = EventWebhook.fromJson(req.body());

    TalkAction response = TalkAction.builder(String.format("You pressed %s, Goodbye.",
            event.getDtmf().getDigits()
    )).build();

    res.type("application/json");

    return new Ncco(response).toJson();
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/dtmf", inputRoute);

Send DTMF To Call

var response = client.getVoiceClient().sendDtmf(CALL_UUID, "332393");
System.out.println(response);

Connect Inbound Call

final String YOUR_SECOND_NUMBER = envVar("YOUR_SECOND_NUMBER");
final String VONAGE_NUMBER = envVar("VONAGE_NUMBER");

/*
 * Route to answer incoming calls with an NCCO response.
 */
Route answerRoute = (req, res) -> {
    ConnectAction connect = ConnectAction.builder()
            .endpoint(PhoneEndpoint.builder(YOUR_SECOND_NUMBER).build())
            .from(VONAGE_NUMBER)
            .build();

    res.type("application/json");

    return new Ncco(connect).toJson();
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerRoute);
Spark.post("/webhooks/answer", answerRoute);

Send Talk To Call

final String TEXT = "Hello World! Would you like to know more? I bet you would.";
var payload = TalkPayload.builder(TEXT).language(TextToSpeechLanguage.AMERICAN_ENGLISH).build();
client.getVoiceClient().startTalk(CALL_UUID, payload);

Outbound Text To Speech

final String VONAGE_NUMBER = envVar("VONAGE_NUMBER");
final String TO_NUMBER = envVar("TO_NUMBER");
final String ANSWER_URL = "https://nexmo-community.github.io/ncco-examples/talk.json";

client.getVoiceClient().createCall(new Call(TO_NUMBER, VONAGE_NUMBER, ANSWER_URL));

ASR Input

/*
 * Route to answer incoming calls.
 */
Route answerCallRoute = (req, res) -> {
    TalkAction intro = TalkAction
            .builder("Please say something")
            .build();

    SpeechSettings speechSettings = SpeechSettings.builder()
            .language(SpeechSettings.Language.ENGLISH_UNITED_STATES).build();

    InputAction input = InputAction.builder()
            .type(Collections.singletonList("speech"))
            .eventUrl(String.format("%s://%s/webhooks/asr", req.scheme(), req.host()))
            .speech(speechSettings)
            .build();


    res.type("application/json");

    return new Ncco(intro, input).toJson();
};

/*
 * Route which returns NCCO saying which word was recognized.
 */
Route speechInputRoute = (req, res) -> {
    EventWebhook event = EventWebhook.fromJson(req.body());

    TalkAction response = TalkAction.builder(String.format("You said %s, Goodbye.",
            event.getSpeech().getResults().get(0).getText()
    )).build();
    res.type("application/json");

    return new Ncco(response).toJson();
};

Spark.port(3000);
Spark.get("/webhooks/answer", answerCallRoute);
Spark.post("/webhooks/asr", speechInputRoute);

Outbound Text To Speech With NCCO

final String VONAGE_NUMBER = envVar("VONAGE_NUMBER");
final String TO_NUMBER = envVar("TO_NUMBER");

Ncco ncco = new Ncco(TalkAction.builder("This is a text to speech call from Vonage").build());

client.getVoiceClient().createCall(new Call(TO_NUMBER, VONAGE_NUMBER, ncco.getActions()));