Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs (Voice): Add 'handle incoming call' tutorial #77

Merged
merged 7 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/compile.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/bin/sh

(cd tutorials/sms/auto-subscribe-app && mvn clean package)
(cd tutorials/voice/handle-incoming-call && mvn clean package)
76 changes: 76 additions & 0 deletions examples/tutorials/voice/handle-incoming-call/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Handle Inconing Call webhook application sample
JPPortier marked this conversation as resolved.
Show resolved Hide resolved

This directory contains sample related to Java SDK tutorial: [Handle incoming call](https://developers.sinch.com/docs/voice/getting-started/java/incoming-call)

## Requirements

- JDK 21 or later
- [Maven](https://maven.apache.org/)
- [ngrok](https://ngrok.com/docs)
- [Sinch account](https://dashboard.sinch.com)

## Usage

### Configure application settings

Application settings is using the SpringBoot configuration file: [`application.yaml`](src/main/resources/application.yaml) file and set:

#### Sinch credentials
Located in `credentials` section (*you can find Voice application credentials you need on your [Sinch dashboard](https://dashboard.sinch.com/voice/apps)*):
- `api-id`: YOUR_Voice_Application_Id
- `api-secret`: YOUR_Voice_Application_Secret

#### Webhook controller path
Located in `voice` section you can modify:
- `controller-path`: path the server will respond to. <em>Default: /voice</em>

#### Server port
Located in `server` section:
- port: The port to be used to listen incoming request. <em>Default: 8090</em>
JPPortier marked this conversation as resolved.
Show resolved Hide resolved

### Starting server locally

Compile and run the application as server onto you localhost.
JPPortier marked this conversation as resolved.
Show resolved Hide resolved
```bash
mvn spring-boot:run
```

### Use ngrok to forward request to local server

Forwarding request to same `8090` port used above:

*Note: The `8090` value is coming from default config and can be changed (see [Server port](#Server port) configuration section)*

```bash
ngrok http 8090
```

ngrok output will contains output like:
JPPortier marked this conversation as resolved.
Show resolved Hide resolved
```
ngrok (Ctrl+C to quit)

...
Forwarding https://0e64-78-117-86-140.ngrok-free.app -> http://localhost:8090

```
The line
```
Forwarding https://0e64-78-117-86-140.ngrok-free.app -> http://localhost:8090
```
Contains `https://0e64-78-117-86-140.ngrok-free.app` value.

## Configure Voice application callback

You have now a local web server responding to `/voice` path and `ngrok` instance running providing a bridge from `https://0e64-78-117-86-140.ngrok-free.app` onto local webserver.

Last step is now to configure your dashboard to set Voice application callback to point your local webserver.
JPPortier marked this conversation as resolved.
Show resolved Hide resolved

The callback to be called by sinch will be in form of: `<bridge host>`/`<web server controller path>`

e.g. According to previous sample values: https://0e64-78-117-86-140.ngrok-free.app/voice

1. Go to your Voice application configuration: [Sinch Voice Apps dashboard](https://dashboard.sinch.com/voice/apps/)
2. Edit the application setting related to the Application ID set from config file (see [Sinch credentials](#configure-application-settings))
3. Fill `Callback URL` field with *https://0e64-78-117-86-140.ngrok-free.app/voice*

alex-sberna marked this conversation as resolved.
Show resolved Hide resolved
You can now perform a to your number, the webhook will be called and serve response to callee.
JPPortier marked this conversation as resolved.
Show resolved Hide resolved
52 changes: 52 additions & 0 deletions examples/tutorials/voice/handle-incoming-call/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<groupId>com.sinch.sdk</groupId>
<artifactId>sinch-sdk-java-sample-webhooks-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Sinch Java SDK Handle Incoming Call Sample Application</name>
<description>Demo Project</description>

<properties>
<sinch.sdk.java.version>[1.0.0,)</sinch.sdk.java.version>
<java.version>21</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.sinch.sdk</groupId>
<artifactId>sinch-sdk-java</artifactId>
<version>${sinch.sdk.java.version}</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.mycompany.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.mycompany.app;

import com.sinch.sdk.SinchClient;
import com.sinch.sdk.domains.voice.VoiceService;
import com.sinch.sdk.models.Configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

@org.springframework.context.annotation.Configuration
public class Config {

@Value("${credentials.application.api-key}")
String applicationApiKey;

@Value("${credentials.application.api-secret}")
String applicationApiSecret;

@Value("${voice.controller-path}")
private String controllerPath;

@Bean
public VoiceService voiceService() {

var configuration =
Configuration.builder()
.setApplicationKey(applicationApiKey)
asein-sinch marked this conversation as resolved.
Show resolved Hide resolved
.setApplicationSecret(applicationApiSecret)
.build();

return new SinchClient(configuration).voice();
}

@Bean
String controllerPath() {
return controllerPath;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.mycompany.app;

import com.sinch.sdk.domains.voice.VoiceService;
import com.sinch.sdk.domains.voice.models.webhooks.IncomingCallEvent;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

@RestController
public class WebhookController {

private final VoiceService voiceService;
private final WebhookService webhookService;
private final String controllerPath;

@Autowired
public WebhookController(
VoiceService voiceService, WebhookService webhookService, String controllerPath) {
this.voiceService = voiceService;
this.webhookService = webhookService;
this.controllerPath = controllerPath;
}

@PostMapping(
value = "#{controllerPath}",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public String voiceEvent(@RequestHeader Map<String, String> headers, @RequestBody String body) {

// ensure valid authentication before handling request
var validAuth =
voiceService
.webhooks()
.validateAuthenticatedRequest(
// The HTTP verb this controller is managing
"POST",
// The URI this path is managing
controllerPath,
// request headers
headers,
// request payload body
body);

// token validation failed
if (!validAuth) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
}

// decode the payload request
var event = voiceService.webhooks().unserializeWebhooksEvent(body);

if (!(event instanceof IncomingCallEvent)) {
return "";
}

// let business layer process the request
var response = webhookService.answered((IncomingCallEvent) event);

return voiceService.webhooks().serializeWebhooksResponse(response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.mycompany.app;

import com.sinch.sdk.domains.voice.models.svaml.ActionHangUp;
import com.sinch.sdk.domains.voice.models.svaml.InstructionSay;
import com.sinch.sdk.domains.voice.models.svaml.SVAMLControl;
import com.sinch.sdk.domains.voice.models.webhooks.IncomingCallEvent;
import java.util.Collections;
import java.util.logging.Logger;
import org.springframework.stereotype.Component;

@Component
public class WebhookService {

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

public SVAMLControl answered(IncomingCallEvent event) {

LOGGER.info(
"Incoming call from '%s' received for '%s' :".formatted(event.getCli(), event.getTo()));

var hangupAction = ActionHangUp.builder().build();

var sayInstruction =
InstructionSay.builder()
.setText("Thank you for calling Sinch. This call will now end.")
.build();

return SVAMLControl.builder()
.setInstructions(Collections.singletonList(sayInstruction))
.setAction(hangupAction)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# springboot related config file

logging:
level:
com: INFO

server:
port: 8090

credentials:
application:
api-key:
api-secret:

voice:
controller-path: /voice
Loading