Enviar un mensaje de acción sugerida RCS (acciones múltiples)

En este fragmento de código aprenderá a enviar un mensaje RCS Suggested Action utilizando el comando text tipo de mensaje del canal Messages API RCS. Este mensaje contendrá múltiples acciones posibles para que el destinatario las seleccione.

Ejemplo

A continuación encontrará la descripción de todas las variables utilizadas en cada fragmento de código:

ClaveDescripción
VONAGE_APPLICATION_ID

The Vonage Application ID.

VONAGE_PRIVATE_KEY_PATH

Private key path.

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.

JWT

Used to authenticate your request. See Authentication for more information, including how to generate a JWT.

TO_NUMBER

The number you are sending the RCS message to in E.164 format. For example 447700900000.

RCS_SENDER_ID

The sender ID for the RCS message.

NOTA: No utilice un + o 00 al introducir un número de teléfono para el to (es decir, el número al que debe enviarse el mensaje RCS), empiece por el prefijo del país, por ejemplo 447700900000.

Para el valor de phoneNumber en el dialAction, sin embargo, un + debe utilizarse para anteponer el código de país, p. ej. +447900000000.

Requisitos previos

Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.

Escriba el código

Añada lo siguiente a send-suggested-action-multiple.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": "'${RCS_SENDER_ID}'",
    "channel": "rcs",
    "message_type": "text",
    "text": "Need some help? Call us now or visit our website for more information.",
    "suggestions": [
      {
        "type": "dial",
        "text": "Call us",
        "postback_data": "postback_data_1234",
        "phone_number": "+447900000000",
        "fallback_url": "https://www.example.com/contact/"
      },
      {
        "type": "open_url",
        "text": "Visit site",
        "postback_data": "postback_data_1234",
        "url": "http://example.com/",
        "description": "A URL for the Example website"
      }
    ]
  }'

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

bash send-suggested-action-multiple.sh

Requisitos previos

Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.

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

Crea un archivo llamado send-suggested-action-multiple.js y añade el siguiente código:

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} : {}),
  },
);

Ver fuente completa

Escriba el código

Añada lo siguiente a send-suggested-action-multiple.js:

vonage.messages.send({
  messageType: 'custom',
  channel: Channels.RCS,
  custom: {
    contentMessage: {
      text: 'Need some help? Call us now or visit our website for more information.',
      suggestions: [
        {
          action: {
            text: 'Call us',
            postbackData: 'postback_data_1234',
            fallbackUrl: 'https://www.example.com/contact/',
            dialAction: {
              phoneNumber: '+447900000000',
            },
          },
        },
        {
          action: {
            text: 'Visit site',
            postbackData: 'postback_data_1234',
            openUrlAction: {
              url: 'http://example.com/',
            },
          },
        },
      ],
    },
  },
  to: MESSAGES_TO_NUMBER,
  from: RCS_SENDER_ID,
})
  .then(({ messageUUID }) => console.log(messageUUID))
  .catch((error) => console.error(error));

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

node send-suggested-action-multiple.js

Requisitos previos

Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.

Añada lo siguiente a build.gradle:

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

Crea un archivo llamado SendRcsSuggestedMultipleActions y añade el siguiente código al método main:

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

Ver fuente completa

Escriba el código

Añada lo siguiente al método main del archivo SendRcsSuggestedMultipleActions:

val messageId = client.messages.send(
    rcsCustom {
        to(MESSAGES_TO_NUMBER)
        from(RCS_SENDER_ID)
        custom(mapOf(
            "contentMessage" to mapOf(
                "text" to "Need some help? Call us now or visit our website for more information.",
                "suggestions" to listOf(
                    mapOf(
                        "action" to mapOf(
                            "text" to "Call us",
                            "postbackData" to "postback_data_1234",
                            "fallbackUrl" to "https://www.example.com/contact/",
                            "dialAction" to mapOf(
                                "phoneNumber" to "+447900000000"
                            )
                        )
                    ),
                    mapOf(
                        "action" to mapOf(
                            "text" to "Visit site",
                            "postbackData" to "postback_data_1234",
                            "openUrlAction" to mapOf(
                                "url" to "http://example.com/"
                            )
                        )
                    )
                )
            )
        ))
    }
)

Ver fuente completa

Ejecute su código

Podemos utilizar el plugin aplicación para Gradle para simplificar la ejecución de nuestra aplicación. Actualiza tu build.gradle con lo siguiente:

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

Ejecute el siguiente comando gradle para ejecutar su aplicación, sustituyendo com.vonage.quickstart.kt.messages.rcs por el paquete que contiene SendRcsSuggestedMultipleActions:

gradle run -Pmain=com.vonage.quickstart.kt.messages.rcs.SendRcsSuggestedMultipleActions

Requisitos previos

Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.

Añada lo siguiente a build.gradle:

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

Crea un archivo llamado SendRcsSuggestedMultipleActions y añade el siguiente código al método main:

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

Ver fuente completa

Escriba el código

Añada lo siguiente al método main del archivo SendRcsSuggestedMultipleActions:

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

Ver fuente completa

Ejecute su código

Podemos utilizar el plugin aplicación para Gradle para simplificar la ejecución de nuestra aplicación. Actualiza tu build.gradle con lo siguiente:

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

Ejecute el siguiente comando gradle para ejecutar su aplicación, sustituyendo com.vonage.quickstart.messages.rcs por el paquete que contiene SendRcsSuggestedMultipleActions:

gradle run -Pmain=com.vonage.quickstart.messages.rcs.SendRcsSuggestedMultipleActions

Requisitos previos

Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.

Install-Package Vonage

Escriba el código

Añada lo siguiente a SendRcsSuggestedActionMultipleMessage.cs:

var request = new RcsTextRequest
{
    To = MESSAGES_TO_NUMBER,
    From = RCS_SENDER_ID,
    Text = "Need some help? Call us now or visit our website for more information.",
    Suggestions = 
    [
        new DialSuggestion(
            "Call now!", 
            "postback_data_1234", 
            "+447900000000"),
        new OpenUrlSuggestion(
            "Visit site", 
            "postback_data_1234",
            new Uri("http://example.com/"), 
            "A URL for the Example website"),
    ]
};
var response = await vonageClient.MessagesClient.SendAsync(request);

Ver fuente completa

Requisitos previos

Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.

composer require vonage/client

Crea un archivo llamado send-suggested-action-multiple.php y añade el siguiente código:

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

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

Ver fuente completa

Escriba el código

Añada lo siguiente a send-suggested-action-multiple.php:

$rcsCard = new Vonage\Messages\Channel\RCS\RcsCustom(
    '07778887777',
    '09997485156',
    [
        "contentMessage" => [
            "text" =>
                "Need some help? Call us now or visit our website for more information.",
            "suggestions" => [
                [
                    "action" => [
                        "text" => "Call us",
                        "postbackData" => "postback_data_1234",
                        "fallbackUrl" => "https://www.example.com/contact/",
                        "dialAction" => ["phoneNumber" => "+447900000000"],
                    ],
                ],
                [
                    "action" => [
                        "text" => "Visit site",
                        "postbackData" => "postback_data_1234",
                        "openUrlAction" => ["url" => "http://example.com/"],
                    ],
                ],
            ],
        ],
    ]
);

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

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

php send-suggested-action-multiple.php

Requisitos previos

Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.

pip install vonage python-dotenv

Escriba el código

Añada lo siguiente a send-suggested-action-multiple.py:

from vonage import Auth, Vonage
from vonage_messages import RcsCustom

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

custom_dict = {
    "contentMessage": {
        "text": "Need some help? Call us now or visit our website for more information.",
        "suggestions": [
            {
                "action": {
                    "text": "Call us",
                    "postbackData": "postback_data_1234",
                    "fallbackUrl": "https://www.example.com/contact/",
                    "dialAction": {"phoneNumber": "+447900000000"},
                }
            },
            {
                "action": {
                    "text": "Visit site",
                    "postbackData": "postback_data_1234",
                    "openUrlAction": {"url": "http://example.com/"},
                }
            },
        ],
    }
}

message = RcsCustom(
    to=MESSAGES_TO_NUMBER,
    from_=RCS_SENDER_ID,
    custom=custom_dict,
)

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

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

python messages/rcs/send-suggested-action-multiple.py

Requisitos previos

Si no tiene una solicitud, puede crear uno. Asegúrese también de configure sus webhooks.

gem install vonage

Crea un archivo llamado send-suggested-action-multiple.rb y añade el siguiente código:

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

Ver fuente completa

Escriba el código

Añada lo siguiente a send-suggested-action-multiple.rb:

message = client.messaging.rcs(
  type: 'text',
  message: "Need some help? Call us now or visit our website for more information.",
  opts: {
    suggestions: [
      {
        type: "dial",
        text: "Call us",
        postback_data: "postback_data_1234",
        phone_number: "+447900000000",
        fallback_url: "https://www.example.com/contact/"
      },
      {
        type: "open_url",
        text: "Visit site",
        postback_data: "postback_data_1234",
        url: "https://www.example.com/",
        description: "A URL for the Example website"
      }
    ]
  }
)

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

Ver fuente completa

Ejecute su código

Guarde este archivo en su máquina y ejecútelo:

ruby send-suggested-action-multiple.rb

Pruébalo

Al ejecutar el código, se envía un mensaje al número de destino.