クイック返信ボタンの送信

このコードでは、WhatsApp でクイック返信ボタンを送信する方法を説明します。Vonageの カスタムオブジェクト 機能をご利用ください。WhatsApp開発者向けドキュメントをご参照ください。 メッセージ形式.

メッセージの受信者がクイック返信ボタンをクリックすると、Vonageは次のようにします。 POST 関連するデータをインバウンドメッセージのウェブフックURLに送信します。

各コード・スニペットで使用されているすべての変数の説明を以下に示します:

キー説明
VONAGE_APPLICATION_ID

The Vonage Application ID.

VONAGE_APPLICATION_PRIVATE_KEY_PATH

Private key path.

BASE_URL

For production use the base URL is https://api.nexmo.com/. For sandbox testing the base URL is https://messages-sandbox.nexmo.com/.

MESSAGES_API_URL

There are two versions of the API, each with their own endpoints. For production the previous Messages API endpoint was https://api.nexmo.com/v0.1/messages, the new one is https://api.nexmo.com/v1/messages. For sandbox testing the Messages API endpoint is https://messages-sandbox.nexmo.com/v0.1/messages or https://messages-sandbox.nexmo.com/v1/messages, depending on which version you have set in the sandbox dashboard.

WHATSAPP_NUMBER

The WhatsApp number that has been allocated to you by Vonage. For sandbox testing the number is 14157386102.

VONAGE_WHATSAPP_NUMBER

Refer to WHATSAPP_NUMBER above.

VONAGE_NUMBER

Refer to WHATSAPP_NUMBER above.

TO_NUMBER

Replace with the number you are sending to. E.g. 447700900001

WHATSAPP_TEMPLATE_NAMESPACE

The namespace ID found in your WhatsApp Business Account. Only templates created in your own namespace will work. Using an template with a namespace outside of your own results in an error code 1022 being returned.

WHATSAPP_TEMPLATE_NAME

The name of the template created in your WhatsApp Business Account.

注: 先頭の + または 00 電話番号を入力する場合は、447700900000のように国番号から入力してください。

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

コードを書く

send-button-quick-reply.sh に以下を追加する:

curl -X POST "${MESSAGES_API_URL}" \
  -H "Authorization: Bearer "$JWT\
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -d $'{
    "to": "'${MESSAGES_TO_NUMBER}'",
    "from": "'${WHATSAPP_SENDER_ID}'",
    "channel": "whatsapp",
    "message_type": "custom",
    "custom": {
      "type": "template",
      "template": {
        "name": "'${WHATSAPP_TEMPLATE_NAME}'",
        "language": {
          "policy": "deterministic",
          "code": "en"
        },
        "components": [
          {
            "type": "header",
            "parameters": [
              {
                "type": "image",
                "image": {
                  "link": "'${MESSAGES_IMAGE_URL}'"
                }
              }
            ]
          },
          {
            "type": "body",
            "parameters": [
              {
                "type": "text",
                "parameter_name": "customer_name",
                "text": "Joe Bloggs"
              },
              {
                "type": "text",
                "parameter_name": "dentist_name",
                "text": "Mr Smith"
              },
              {
                "type": "text",
                "parameter_name": "appointment_date",
                "text": "2025-02-26"
              },
              {
                "type": "text",
                "parameter_name": "appointment_location",
                "text": "ACME Dental Practice"
              }
            ]
          },
          {
            "type": "button",
            "sub_type": "quick_reply",
            "index": 0,
            "parameters": [
              {
                "type": "payload",
                "payload": "Yes-Button-Payload"
              }
            ]
          },
          {
            "type": "button",
            "sub_type": "quick_reply",
            "index": 1,
            "parameters": [
              {
                "type": "payload",
                "payload": "No-Button-Payload"
              }
            ]
          }
        ]
      }
    }
  }'

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

bash send-button-quick-reply.sh

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

npm install @vonage/server-sdk @vonage/messages

send-button-quick-reply.js という名前のファイルを作成し、以下のコードを追加する:

const { Vonage } = require('@vonage/server-sdk');
const { Channels } = require('@vonage/messages');

/**
 * It is best to send messages using JWT instead of basic auth. If you leave out
 * apiKey and apiSecret, the messages SDK will send requests using JWT tokens
 *
 * @link https://developer.vonage.com/en/messages/technical-details#authentication
 */
const vonage = new Vonage(
  {
    applicationId: VONAGE_APPLICATION_ID,
    privateKey: VONAGE_PRIVATE_KEY,
  },
  {
    ...(MESSAGES_API_URL ? {apiHost: MESSAGES_API_URL} : {}),
  },
);

全文を見る

コードを書く

send-button-quick-reply.js に以下を追加する:

vonage.messages.send({
  to: MESSAGES_TO_NUMBER,
  from: WHATSAPP_SENDER_ID,
  channel: Channels.WHATSAPP,
  messageType: 'custom',
  custom: {
    type: 'template',
    template: {
      name: WHATSAPP_TEMPLATE_NAME,
      language: {
        policy: 'deterministic',
        code: 'en',
      },
      components: [
        {
          type: 'header',
          parameters: [
            {
              type: 'image',
              image: {
                link: MESSAGES_IMAGE_URL,
              },
            },
          ],
        },
        {
          type: 'body',
          parameters: [
            {
              type: 'text',
              parameter_name: 'customer_name',
              text: 'Joe Bloggs',
            },
            {
              type: 'text',
              parameter_name: 'dentist_name',
              text: 'Mr Smith',
            },
            {
              type: 'text',
              parameter_name: 'appointment_date',
              text: '2025-02-26',
            },
            {
              type: 'text',
              parameter_name: 'appointment_location',
              text: 'ACME Dental Practice',
            },
          ],
        },
        {
          type: 'button',
          sub_type: 'quick_reply',
          index: 0,
          parameters: [
            {
              type: 'payload',
              payload: 'Yes-Button-Payload',
            },
          ],
        },
        {
          type: 'button',
          sub_type: 'quick_reply',
          index: 1,
          parameters: [
            {
              type: 'payload',
              payload: 'No-Button-Payload',
            },
          ],
        },
      ],
    },
  },
})
  .then((resp) => console.log(resp.messageUUID))
  .catch((error) => console.error(error));

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

node send-button-quick-reply.js

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

build.gradle に以下を追加する:

implementation 'com.vonage:server-sdk-kotlin:2.1.1'

SendWhatsappQuickReplyButton という名前のファイルを作成し、main メソッドに以下のコードを追加する:

val client = Vonage {
    applicationId(VONAGE_APPLICATION_ID)
    privateKeyPath(VONAGE_PRIVATE_KEY_PATH)
}

全文を見る

コードを書く

SendWhatsappQuickReplyButton ファイルのmain メソッドに以下を追加する:

val messageId = client.messages.send(
    whatsappCustom {
        to(MESSAGES_TO_NUMBER)
        from(WHATSAPP_SENDER_ID)
        custom(mapOf(
            "type" to MessageType.TEMPLATE,
            "template" to mapOf(
                "namespace" to WHATSAPP_TEMPLATE_NAMESPACE,
                "name" to WHATSAPP_TEMPLATE_NAME,
                "language" to mapOf(
                    "code" to Locale.ENGLISH,
                    "policy" to Policy.DETERMINISTIC
                ),
                "components" to listOf(
                    mapOf(
                        "type" to "header",
                        "parameters" to listOf(
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "12/26"
                            )
                        )
                    ),
                    mapOf(
                        "type" to "body",
                        "parameters" to listOf(
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "*Ski Trip*"
                            ),
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "2019-12-26"
                            ),
                            mapOf(
                                "type" to MessageType.TEXT,
                                "text" to "*Squaw Valley Ski Resort, Tahoe*"
                            )
                        )
                    ),
                    mapOf(
                        "type" to MessageType.BUTTON,
                        "sub_type" to "quick_reply",
                        "index" to 0,
                        "parameters" to listOf(
                            mapOf(
                                "type" to "payload",
                                "payload" to "Yes-Button-Payload"
                            )
                        )
                    ),
                    mapOf(
                        "type" to MessageType.BUTTON,
                        "sub_type" to "quick_reply",
                        "index" to 1,
                        "parameters" to listOf(
                            mapOf(
                                "type" to "payload",
                                "payload" to "No-Button-Payload"
                            )
                        )
                    )
                )
            )
        ))
    }
)

全文を見る

コードを実行する

Gradle用のアプリケーション プラグインを使うことで、アプリケーションの実行を簡単にすることができます。build.gradle を以下のように更新する:

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

以下のgradle コマンドを実行し、com.vonage.quickstart.kt.messages.whatsappSendWhatsappQuickReplyButton を含むパッケージに置き換えてアプリケーションを実行する:

gradle run -Pmain=com.vonage.quickstart.kt.messages.whatsapp.SendWhatsappQuickReplyButton

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

build.gradle に以下を追加する:

implementation 'com.vonage:server-sdk:9.3.1'

SendWhatsappQuickReplyButton という名前のファイルを作成し、main メソッドに以下のコードを追加する:

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

全文を見る

コードを書く

SendWhatsappQuickReplyButton ファイルのmain メソッドに以下を追加する:

var response = client.getMessagesClient().sendMessage(
	WhatsappCustomRequest.builder()
		.from(WHATSAPP_SENDER_ID).to(MESSAGES_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());

全文を見る

コードを実行する

Gradle用のアプリケーション プラグインを使うことで、アプリケーションの実行を簡単にすることができます。build.gradle を以下のように更新する:

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

以下のgradle コマンドを実行し、com.vonage.quickstart.messages.whatsappSendWhatsappQuickReplyButton を含むパッケージに置き換えてアプリケーションを実行する:

gradle run -Pmain=com.vonage.quickstart.messages.whatsapp.SendWhatsappQuickReplyButton

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

Install-Package Vonage

コードを書く

SendWhatsAppQuickReplyButton.cs に以下を追加する:

var credentials = Credentials.FromAppIdAndPrivateKeyPath(VONAGE_APPLICATION_ID, VONAGE_PRIVATE_KEY_PATH);
var vonageClient = new VonageClient(credentials);
var request = new WhatsAppCustomRequest
{
    To = MESSAGES_TO_NUMBER,
    From = WHATSAPP_SENDER_ID,
    Custom = new
    {
        type = "template",
        template = new
        {
            name = WHATSAPP_TEMPLATE_NAME,
            language = new
            {
                code = "en",
                policy = "deterministic"
            },
            components = new object[]
            {
                new
                {
                    type = "header",
                    parameters = new[]
                    {
                        new
                        {
                            type = "text",
                            text = "12/26"
                        }
                    }
                },
                new
                {
                    type = "body",
                    parameters = new[]
                    {
                        new
                        {
                            type = "text",
                            text = "*Ski Trip*"
                        },
                        new
                        {
                            type = "text",
                            text = "2019-12-26"
                        },
                        new
                        {
                            type = "text",
                            text = "*Squaw Valley Ski Resort, Tahoe*"
                        }
                    }
                },
                new
                {
                    type = "button",
                    sub_type = "quick_reply",
                    index = 0,
                    parameters = new[]
                    {
                        new
                        {
                            type = "payload",
                            text = "Yes-Button-Payload"
                        }
                    }
                },
                new
                {
                    type = "button",
                    sub_type = "quick_reply",
                    index = 1,
                    parameters = new[]
                    {
                        new
                        {
                            type = "payload",
                            text = "No-Button-Payload"
                        }
                    }
                }
            }
        }
    }
};
var response = await vonageClient.MessagesClient.SendAsync(request);

全文を見る

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

composer require vonage/client

send-button-quick-reply.php という名前のファイルを作成し、以下のコードを追加する:

$keypair = new \Vonage\Client\Credentials\Keypair(
    file_get_contents(VONAGE_APPLICATION_PRIVATE_KEY_PATH),
    VONAGE_APPLICATION_ID
);

$client = new \Vonage\Client($keypair);

全文を見る

コードを書く

send-button-quick-reply.php に以下を追加する:

$custom = [
    "type" => "template",
    "template" => [
        "namespace" => WHATSAPP_TEMPLATE_NAMESPACE,
        "name" => WHATSAPP_TEMPLATE_NAME,
        "language" => ["code" => "en", "policy" => "deterministic"],
        "components" => [
            [
                "type" => "header",
                "parameters" => [["type" => "text", "text" => "12/26"]],
            ],
            [
                "type" => "body",
                "parameters" => [
                    ["type" => "text", "text" => "*Ski Trip*"],
                    ["type" => "text", "text" => "2019-12-26"],
                    [
                        "type" => "text",
                        "text" => "*Squaw Valley Ski Resort, Tahoe*",
                    ],
                ],
            ],
            [
                "type" => "button",
                "sub_type" => "quick_reply",
                "index" => 0,
                "parameters" => [
                    ["type" => "payload", "payload" => "Yes-Button-Payload"],
                ],
            ],
            [
                "type" => "button",
                "sub_type" => "quick_reply",
                "index" => 1,
                "parameters" => [
                    ["type" => "payload", "payload" => "No-Button-Payload"],
                ],
            ],
        ],
    ],
];

$whatsApp = new \Vonage\Messages\Channel\WhatsApp\WhatsAppCustom(
    TO_NUMBER,
    FROM_NUMBER,
    $custom
);

$client->messages()->send($whatsApp);

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

php send-button-quick-reply.php

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

pip install vonage python-dotenv

コードを書く

send-button-quick-reply.py に以下を追加する:

from vonage import Auth, Vonage
from vonage_messages import WhatsappCustom

client = Vonage(
    Auth(
        application_id=VONAGE_APPLICATION_ID,
        private_key=VONAGE_PRIVATE_KEY,
    )
)

message = WhatsappCustom(
    to=MESSAGES_TO_NUMBER,
    from_=WHATSAPP_SENDER_ID,
    custom={
        "type": "template",
        "template": {
            "name": WHATSAPP_TEMPLATE_NAME,
            "language": {"policy": "deterministic", "code": "en"},
            "components": [
                {
                    "type": "header",
                    "parameters": [
                        {
                            "type": "image",
                            "image": {
                                "link": MESSAGES_IMAGE_URL,
                            },
                        },
                    ],
                },
                {
                    "type": "body",
                    "parameters": [
                        {
                            "type": "text",
                            "parameter_name": "customer_name",
                            "text": "Joe Bloggs",
                        },
                        {
                            "type": "text",
                            "parameter_name": "dentist_name",
                            "text": "Mr Smith",
                        },
                        {
                            "type": "text",
                            "parameter_name": "appointment_date",
                            "text": "2025-02-26",
                        },
                        {
                            "type": "text",
                            "parameter_name": "appointment_location",
                            "text": "ACME Dental Practice",
                        },
                    ],
                },
                {
                    "type": "button",
                    "sub_type": "quick_reply",
                    "index": 0,
                    "parameters": [{"type": "payload", "payload": "Yes-Button-Payload"}],
                },
                {
                    "type": "button",
                    "sub_type": "quick_reply",
                    "index": 1,
                    "parameters": [{"type": "payload", "payload": "No-Button-Payload"}],
                },
            ],
        },
    },
)

response = client.messages.send(message)
print(response)

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

python messages/whatsapp/send-button-quick-reply.py

前提条件

申込書をお持ちでない場合は、ひとつ作るウェブフックの設定 もご確認ください。

gem install vonage

send-button-quick-reply.rb という名前のファイルを作成し、以下のコードを追加する:

client = Vonage::Client.new(
  application_id: VONAGE_APPLICATION_ID,
  private_key: VONAGE_PRIVATE_KEY
)

全文を見る

コードを書く

send-button-quick-reply.rb に以下を追加する:

message = client.messaging.whatsapp(
  type: 'custom',
  message: {
    type: "template",
    template: {
      name: WHATSAPP_TEMPLATE_NAME,
      language: {
        policy: "deterministic",
        code: "en"
      },
      components: [
        {
          type: "header",
          parameters: [
            {
              type: "image",
              image: {
                link: MESSAGES_IMAGE_URL
              }
            }
          ]
        },
        {
          type: "body",
          parameters: [
            {
              type: "text",
              parameter_name: "customer_name",
              text: "Joe Bloggs"
            },
            {
              type: "text",
              parameter_name: "dentist_name",
              text: "Mr Smith"
            },
            {
              type: "text",
              parameter_name: "appointment_date",
              text: "2025-02-26"
            },
            {
              type: "text",
              parameter_name: "appointment_location",
              text: "ACME Dental Practice"
            }
          ]
        },
        {
          type: "button",
          sub_type: "quick_reply",
          index: "0",
          parameters: [
            {
              type: "payload",
              payload: "Yes-Button-Payload"
            }
          ]
        },
        {
          type: "button",
          sub_type: "quick_reply",
          index: "1",
          parameters: [
            {
              type: "payload",
              payload: "No-Button-Payload"
            }
          ]
        }
      ]
    }
  }
)

client.messaging.send(
  from: WHATSAPP_SENDER_ID,
  to: MESSAGES_TO_NUMBER,
  **message
)

全文を見る

コードを実行する

このファイルをあなたのマシンに保存し、実行する:

ruby send-button-quick-reply.rb

試してみる

コードを実行すると、WhatsAppリマインダーメッセージが相手先電話番号に送信されます。メッセージには2つのクイック返信ボタンがあり、イベントに行くか行かないかを選択できます。ボタンが押されると以下のようなデータが受信用ウェブフックURLに送信されます:

{
    "message_uuid": "28ee5a1c-c4cc-48ec-922c-01520d4d396b",
    "to": {
        "number": "447700000000",
        "type": "whatsapp"
    },
    "from": {
        "number": "447700000001",
        "type": "whatsapp"
    },
    "timestamp": "2019-12-03T12:45:57.929Z",
    "direction": "inbound",
    "message": {
        "content": {
            "type": "button",
            "button": {
                "payload": "Yes-Button-Payload",
                "text": "Yes"
            }
        }
    }
}

この例では、受信者は「はい」ボタンをクリックした。

詳細情報