Here are all the snippets in this repository. This file was generated by running AggregateSnippets.java from the root of the repository.
- Initialize
- Account
- Application
- Number Insight
- JWT
- Meetings
- Messages
- Fraud Detection
- Numbers
- Redact
- SIM Swap
- SMS
- Subaccounts
- Users
- Verify
- Verify v2
- Voice
VonageClient client = VonageClient.builder()
.applicationId(VONAGE_APPLICATION_ID)
.privateKeyContents(VONAGE_APPLICATION_PRIVATE_KEY)
.build();
VonageClient client = VonageClient.builder()
.apiKey(VONAGE_API_KEY)
.apiSecret(VONAGE_API_SECRET)
.applicationId(VONAGE_APPLICATION_ID)
.privateKeyPath(VONAGE_APPLICATION_PRIVATE_KEY_PATH)
.build();
VonageClient client = VonageClient.builder().apiKey(VONAGE_API_KEY).apiSecret(VONAGE_API_SECRET).build();
VonageClient client = VonageClient.builder()
.applicationId(VONAGE_APPLICATION_ID)
.privateKeyPath(VONAGE_APPLICATION_PRIVATE_KEY_PATH)
.build();
SecretResponse response = client.getAccountClient().createSecret(VONAGE_API_KEY, NEW_SECRET);
System.out.println(response.getId() + " created at " + response.getCreated());
SettingsResponse response = client.getAccountClient().updateSmsIncomingUrl(SMS_CALLBACK_URL);
System.out.println("SMS Callback URL is now " + response.getIncomingSmsUrl());
client.getAccountClient().revokeSecret(VONAGE_API_KEY, VONAGE_SECRET_ID);
BalanceResponse response = client.getAccountClient().getBalance();
System.out.printf("Balance: %s EUR\n", response.getValue());
System.out.printf("Auto-reload Enabled: %s\n", response.isAutoReload());
SecretResponse response = client.getAccountClient().getSecret(VONAGE_API_KEY, VONAGE_SECRET_ID);
System.out.println(response.getId() + " created at " + response.getCreated());
ListSecretsResponse response = client.getAccountClient().listSecrets(VONAGE_API_KEY);
for (SecretResponse secret : response.getSecrets()) {
System.out.println(secret.getId() + " created at " + secret.getCreated());
}
client.getApplicationClient().deleteApplication(VONAGE_APPLICATION_ID);
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());
Application application = client.getApplicationClient().getApplication(VONAGE_APPLICATION_ID);
System.out.println(application.toJson());
ApplicationList applications = client.getApplicationClient().listApplications();
applications.getApplications().forEach(
application -> System.out.println(application.toJson())
);
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());
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() + ")"
);
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());
}
}
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());
client.getInsightClient().getAdvancedNumberInsight(
AdvancedInsightRequest.builder(INSIGHT_NUMBER)
.async(true).callback(CALLBACK_URL).build()
);
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());
port(3000);
Spark.post("/webhooks/insight", (req, res) -> {
AdvancedInsightResponse response = AdvancedInsightResponse.fromJson(req.body());
System.out.println("Country: " + response.getCountryName());
res.status(204);
return "";
});
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);
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();
client.getMeetingsClient().deleteTheme(THEME_ID, true);
System.out.println("Deleted theme "+THEME_ID);
List<Theme> themes = client.getMeetingsClient().listThemes();
themes.forEach(theme -> System.out.println(theme.getThemeName() + " ("+theme.getThemeId()+")"));
List<DialInNumber> dialInNumbers = client.getMeetingsClient().listDialNumbers();
dialInNumbers.forEach(din -> System.out.println(din.getDisplayName()+": "+din.getNumber()));
client.getMeetingsClient().deleteRecording(RECORDING_ID);
System.out.println("Deleted recording "+RECORDING_ID);
MeetingRoom room = client.getMeetingsClient().getRoom(ROOM_ID);
System.out.println(room.getDisplayName() + " ("+room.getId()+")");
client.getMeetingsClient().updateThemeLogo(THEME_ID, LOGO_TYPE, LOGO_FILEPATH);
System.out.println("Updated '"+LOGO_TYPE+"' logo for theme "+THEME_ID);
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());
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<Recording> recordings = client.getMeetingsClient().listRecordings(SESSION_ID);
recordings.forEach(recording -> System.out.println(recording.getId()));
UpdateApplicationRequest request = UpdateApplicationRequest.builder()
.defaultThemeId(THEME_ID).build();
Application application = client.getMeetingsClient().updateApplication(request);
System.out.println("Updated application "+application.getApplicationId());
List<MeetingRoom> rooms = client.getMeetingsClient().searchRoomsByTheme(THEME_ID);
rooms.forEach(room -> System.out.println(room.getDisplayName() + " ("+room.getId()+")"));
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()+")");
MeetingRoom room = MeetingRoom.builder(DISPLAY_NAME).type(RoomType.INSTANT).build();
client.getMeetingsClient().createRoom(room);
System.out.println("Created room "+room.getId());
Recording recording = client.getMeetingsClient().getRecording(RECORDING_ID);
System.out.println(recording.getId());
List<MeetingRoom> rooms = client.getMeetingsClient().listRooms();
rooms.forEach(room -> System.out.println(room.getDisplayName() + " ("+room.getId()+")"));
Theme theme = client.getMeetingsClient().getTheme(THEME_ID);
System.out.println(theme.getThemeName());
Theme theme = Theme.builder().mainColor(MAIN_COLOR).brandText(BRAND_TEXT).build();
client.getMeetingsClient().createTheme(theme);
System.out.println("Updated theme '"+theme.getThemeName()+"' ("+theme.getThemeId()+")");
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());
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());
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());
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());
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());
client.getMessagesClient().revokeOutboundMessage(MESSAGE_UUID, ApiRegion.API_EU);
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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);
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());
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());
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());
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());
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()
);
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()
);
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()
);
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()
);
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()
);
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()
);
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()
);
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", "[email protected]",
"type", "WORK"
),
Map.of(
"email", "[email protected]",
"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()
);
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()
);
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()
);
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()
);
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()
);
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()
);
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()
);
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);
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());
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());
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());
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());
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());
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);
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());
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());
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());
client.getMessagesClient().ackInboundMessage(MESSAGE_UUID, ApiRegion.API_EU);
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", "[email protected]",
"type", "WORK"
),
Map.of(
"email", "[email protected]",
"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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
var response = client.getNumberInsight2Client().fraudCheck(INSIGHT_NUMBER, Insight.FRAUD_SCORE);
var fraudScore = response.getFraudScore();
System.out.println(fraudScore);
var response = client.getNumberInsight2Client().fraudCheck(INSIGHT_NUMBER, Insight.SIM_SWAP);
var simSwap = response.getSimSwap();
System.out.println(simSwap);
client.getNumbersClient().cancelNumber(COUNTRY_CODE, VONAGE_NUMBER);
client.getNumbersClient().buyNumber(COUNTRY_CODE, VONAGE_NUMBER);
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());
}
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()
);
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());
}
client.getRedactClient().redactTransaction(VONAGE_REDACT_ID, VONAGE_REDACT_PRODUCT);
Instant lastSwapDate = client.getSimSwapClient().retrieveSimSwapDate(TO_NUMBER);
System.out.println(lastSwapDate);
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."
);
/*
* 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);
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 "";
});
/*
* 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);
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);
}
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());
}
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());
}
MoneyTransfer receipt = client.getSubaccountsClient().transferCredit(
MoneyTransfer.builder()
.from(VONAGE_API_KEY).to(SUBACCOUNT_KEY)
.amount(AMOUNT).build()
);
System.out.println("Transfer successful: "+receipt.getId());
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<MoneyTransfer> transfers = client.getSubaccountsClient().listBalanceTransfers();
ListSubaccountsResponse response = client.getSubaccountsClient().listSubaccounts();
Account subaccount = client.getSubaccountsClient().getSubaccount(SUBACCOUNT_KEY);
Account subaccount = client.getSubaccountsClient().updateSubaccount(
UpdateSubaccountRequest.builder(SUBACCOUNT_KEY).suspended(true).build()
);
Account subaccount = client.getSubaccountsClient().updateSubaccount(
UpdateSubaccountRequest.builder(SUBACCOUNT_KEY)
.name(NEW_SUBACCOUNT_NAME).build()
);
Account subaccount = client.getSubaccountsClient().createSubaccount(
CreateSubaccountRequest.builder()
.name(NEW_SUBACCOUNT_NAME)
.secret(NEW_SUBACCOUNT_SECRET)
.build()
);
NumberTransfer transfer = NumberTransfer.builder()
.from(VONAGE_API_KEY).to(SUBACCOUNT_KEY)
.number(NUMBER).build();
client.getSubaccountsClient().transferNumber(transfer);
Account subaccount = client.getSubaccountsClient().updateSubaccount(
UpdateSubaccountRequest.builder(SUBACCOUNT_KEY).suspended(false).build()
);
List<MoneyTransfer> transfers = client.getSubaccountsClient().listCreditTransfers();
User user = client.getUsersClient().updateUser(
USER_ID, User.builder()
.name(USER_NEW_NAME)
.displayName(USER_NEW_DISPLAY_NAME)
.build()
);
User user = client.getUsersClient().getUser(USER_ID);
client.getUsersClient().deleteUser(USER_ID);
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:[email protected];transport=tls", "myUserName", "P@ssw0rd"),
new Websocket("wss://example.com/socket")
)
.build()
);
List<BaseUser> users = client.getUsersClient().listUsers();
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.");
}
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!");
}
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());
}
SearchVerifyResponse response = client.getVerifyClient().search(REQUEST_ID);
if (response.getStatus() == VerifyStatus.OK) {
response.getVerificationRequests().forEach(it -> {
System.out.println(it.getRequestId() + " " + it.getStatus());
});
}
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());
}
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());
}
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());
}
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());
}
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());
client.getVerify2Client().deleteTemplate(TEMPLATE_ID);
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);
VerificationResponse response = client.getVerify2Client().sendVerification(
VerificationRequest.builder()
.addWorkflow(new EmailWorkflow(TO_EMAIL))
.brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());
VerificationResponse response = client.getVerify2Client().sendVerification(
VerificationRequest.builder()
.addWorkflow(new VoiceWorkflow(TO_NUMBER))
.brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());
VerificationResponse response = client.getVerify2Client().sendVerification(
VerificationRequest.builder()
.addWorkflow(new SmsWorkflow(TO_NUMBER))
.brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());
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());
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();
}
}
var template = client.getVerify2Client().getTemplate(TEMPLATE_ID);
System.out.println(template);
var templates = client.getVerify2Client().listTemplates();
templates.forEach(t -> System.out.println(t.getId()));
VerificationResponse response = client.getVerify2Client().sendVerification(
VerificationRequest.builder()
.addWorkflow(new SilentAuthWorkflow(TO_NUMBER))
.brand(BRAND_NAME).build()
);
System.out.println("Verification sent: " + response.getRequestId());
var fragments = client.getVerify2Client().listTemplateFragments(TEMPLATE_ID);
fragments.forEach(f -> System.out.println(f.getFragmentId()));
var template = client.getVerify2Client().createTemplate("My_template");
System.out.println(template.getId());
var updated = client.getVerify2Client().updateTemplateFragment(
TEMPLATE_ID, TEMPLATE_FRAGMENT_ID,
"The authentication code for your ${brand} is: ${code}"
);
System.out.println(updated);
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);
var updated = client.getVerify2Client().updateTemplate(TEMPLATE_ID, "My_renamed_template", false);
System.out.println(updated);
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());
client.getVerify2Client().cancelVerification(REQUEST_ID);
var fragment = client.getVerify2Client().getTemplateFragment(TEMPLATE_ID, TEMPLATE_FRAGMENT_ID);
System.out.println(fragment);
client.getVerify2Client().deleteTemplateFragment(TEMPLATE_ID, TEMPLATE_FRAGMENT_ID);
CallInfo details = client.getVoiceClient().getCallDetails(CALL_UUID);
System.out.println(details);
/*
* 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);
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);
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();
});
TalkAction talkAction = TalkAction.builder("This is a transfer action using an inline NCCO.").build();
client.getVoiceClient().transferCall(CALL_UUID, new Ncco(talkAction));
client.getVoiceClient().muteCall(CALL_UUID);
Thread.sleep(3000);
client.getVoiceClient().unmuteCall(CALL_UUID);
client.getVoiceClient().terminateCall(CALL_UUID);
final String NCCO_URL = "https://nexmo-community.github.io/ncco-examples/talk.json";
client.getVoiceClient().transferCall(CALL_UUID, NCCO_URL);
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);
/*
* 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);
client.getVoiceClient().earmuffCall(CALL_UUID);
Thread.sleep(3000);
client.getVoiceClient().unearmuffCall(CALL_UUID);
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);
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);
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);
/*
* 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);
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());
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);
/*
* 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);
var response = client.getVoiceClient().sendDtmf(CALL_UUID, "332393");
System.out.println(response);
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);
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);
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));
/*
* 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);
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()));