SMS の受信

SMS を受信する要件は以下のとおりです。

Prerequisites

Add the following to build.gradle:

implementation 'com.vonage:server-sdk-kotlin:2.1.1'
implementation 'io.ktor:ktor-server-netty'
implementation 'io.ktor:ktor-serialization-jackson'

Write the code

Add the following to the main method of the ReceiveMessage class:

embeddedServer(Netty, port = 8000) {
    routing {
        route("/webhooks/inbound-sms") {
            handle {
                if (call.request.contentType().equals("application/x-www-form-urlencoded")) {
                    println("msisdn: ${call.request.queryParameters["msisdn"]}")
                    println("messageId: ${call.request.queryParameters["messageId"]}")
                    println("text: ${call.request.queryParameters["text"]}")
                    println("type: ${call.request.queryParameters["type"]}")
                    println("keyword: ${call.request.queryParameters["keyword"]}")
                    println("messageTimestamp: ${call.request.queryParameters["messageTimestamp"]}")
                }
                else {
                    val messageEvent = MessageEvent.fromJson(call.receive())
                    println(messageEvent.toJson())
                }
                call.respond(204)
            }
        }
    }
}.start(wait = true)

View full source

Run your code

We can use the application plugin for Gradle to simplify the running of our application. Update your build.gradle with the following:

apply plugin: 'application'
mainClassName = project.hasProperty('main') ? project.getProperty('main') : ''

Run the following gradle command to execute your application, replacing com.vonage.quickstart.kt.sms with the package containing ReceiveMessage:

gradle run -Pmain=com.vonage.quickstart.kt.sms.ReceiveMessage

Nexmo Dashboard で Web フックエンドポイントを設定します

Nexmo が Web フックにアクセスできるようにするには、Nexmo アカウントでアクセス方法を設定する必要があります。

Web フックはコードスニペットの /webhooks/inbound-sms にあります。Ngrok を使用している場合、Nexmo Dashboard の API 設定ページで設定が必要な Web フックは「https://demo.ngrok.io/webhooks/inbound-sms」フォームを取ります。「demo」部分を Ngrok から提供されるサブドメインに置き換えて、 着信メッセージ用 Web フックの URL というラベルが付いたフィールドにエンドポイントを入力します。

試行手順

上記準備を完了して Nexmo の番号を SMS に送信すると、その番号はコンソールに記録されるようになります。メッセージオブジェクトには次のプロパティが含まれます。

{
  "msisdn": "447700900001",
  "to": "447700900000",
  "messageId": "0A0000000123ABCD1",
  "text": "Hello world",
  "type": "text",
  "keyword": "Hello",
  "message-timestamp": "2020-01-01T12:00:00.000+00:00",
  "timestamp": "1578787200",
  "nonce": "aaaaaaaa-bbbb-cccc-dddd-0123456789ab",
  "concat": "true",
  "concat-ref": "1",
  "concat-total": "3",
  "concat-part": "2",
  "data": "abc123",
  "udh": "abc123"
}