Cómo programar mensajes en canales de WhatsApp de la manera fácil

15 de enero de 2025

En este tutorial aprenderás a programar la entrega de mensajes usando la API

Hay dos maneras de programar la entrega de un mensaje para más adelante (hora y/o día): especificando el día y la hora exactos en los que quieres que se envíe o indicando cuántos minutos, horas o días deseas retrasar la entrega diferida.

Si quieres enviar mensajes desde código, puedes usar cualquier lenguaje de programación para realizar solicitudes HTTPS a la API. A continuación encontrarás el probador de API en vivo con ejemplos de código listos para usar en varios lenguajes de programación.

Requisitos

  • Tener un número de WhatsApp ya vinculado a la plataforma y en línea.
  • Número de teléfono del destinatario con prefijo internacional en formato E164. Ejemplo: +393517224449. Puedes validar el número de teléfono aquí.

Endpoint de la API

En este tutorial usaremos el siguiente endpoint de la API:

Preparar la solicitud

URL objetivo de la API (POST)

https://api.wassenger.com/v1/messages

Encabezados HTTPS requeridos

Content-Type: application/json
Token: ENTER API KEY HERE

Enviar un mensaje en una fecha específica en formato ISO8601

Ejemplo de cuerpo de la solicitud en formato JSON

{ "channel": "${channel_ID}@newsletter", "message": "This is a scheduled message to be sent tomorrow to a channel. Date format is based on ISO 8601 format with default UTC time zone", "deliverAt": "2025-01-15T10:42:34.416Z" }

¡Felicidades! Ahora puedes enviar mensajes automáticos usando la API a canales en WhatsApp.

🤩 🤖 Wassenger es una solución completa de API para WhatsApp. Regístrate para una prueba gratuita de 7 días y comienza en minutos!

¿Eres desarrollador?

Explora cómo usar el código en tu navegador sin instalar ningún software.

Además, puedes encontrar distintos lenguajes que puedes probar en Replit.com:

# Examples requires to have installed requests Python package.
# Install it by running: pip install requests
import requests
url = "https://api.wassenger.com/v1/messages"
payload = {
"channel": "${channel_id}@newsletter", 
"message": "This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone", 
"deliverAt": "2025-01-15T10:42:34.416Z"
}
headers = {
"Content-Type": "application/json", 
"Token": "API TOKEN GOES HERE"
}
response = requests.post(url, json=payload, headers=headers)
print(response.json())
<?php
$curl = curl_init();
curl_setopt_array($curl, [
  CURLOPT_URL => 'https://api.wassenger.com/v1/messages',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => json_encode([
    'channel' => '${channel_id}@newsletter',
    'message' =>
      'This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone',
    'deliverAt' => '2025-01-15T10:42:34.416Z',
  ]),
  CURLOPT_HTTPHEADER => [
    'Content-Type: application/json',
    'Token: API TOKEN GOES HERE',
  ],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
  echo 'cURL Error #:' . $err;
} else {
  echo $response;
}
// This code example requires to have installed pecl_http package, a simple and elegant HTTP client for PHP.
// Install it by running: pecl install pecl_http
// More information: https://mdref.m6w6.name/http
<?php
$client = new http\Client();
$request = new http\Client\Request();
$body = new http\Message\Body();
$body->append(
  json_encode([
    'channel' => '${channel_id}@newsletter',
    'message' =>
      'This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone',
    'deliverAt' => '2025-01-15T10:42:34.416Z',
  ])
);
$request->setRequestUrl('https://api.wassenger.com/v1/messages');
$request->setRequestMethod('POST');
$request->setBody($body);
$request->setHeaders([
  'Content-Type' => 'application/json',
  'Token' => 'API TOKEN GOES HERE',
]);
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
// This code example requires to have installed Guzzle package, a flexible and elegant HTTP client for PHP.
// Install it first following these instructions:
// https://docs.guzzlephp.org/en/stable/overview.html#installation
<?php
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'https://api.wassenger.com/v1/messages', [
  'body' =>
    '{"channel":"${channel_id}@newsletter", "message":"This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone", "deliverAt":"2025-01-15T10:42:34.416Z"}',
  'headers' => [
    'Content-Type' => 'application/json',
    'Token' => 'API TOKEN GOES HERE',
  ],
]);
echo $response->getBody();
// This code example requires to have installed pecl_http package, a simple and elegant HTTP client for PHP.
// Install it by running: pecl install pecl_http
// More information: https://mdref.m6w6.name/http
<?php
$client = new http\Client();
$request = new http\Client\Request();
$body = new http\Message\Body();
$body->append(
  json_encode([
    'channel' => '${channel_id}@newsletter',
    'message' =>
      'This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone',
    'deliverAt' => '2025-01-15T10:42:34.416Z',
  ])
);
$request->setRequestUrl('https://api.wassenger.com/v1/messages');
$request->setRequestMethod('POST');
$request->setBody($body);
$request->setHeaders([
  'Content-Type' => 'application/json',
  'Token' => 'API TOKEN GOES HERE',
]);
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
  • C# (RestClient)
// This code requires you to have installed RestSharp package.
// Documentation: https://restsharp.dev
// Installation: https://www.nuget.org/packages/RestSharp
var client = new RestClient("https://api.wassenger.com/v1/messages");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Token", "API TOKEN GOES HERE");
request.AddParameter("application/json", "{\"channel\":\"${channel_id}@newsletter\", \"message\":\"This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone\", \"deliverAt\":\"2025-01-15T10:42:34.416Z\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
  • C# (HttpClient)
// This code uses the built-in HttpClient package in the.NET framework.
// Documentation: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0
using System.Net.Http.Headers;
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Post, 
RequestUri = new Uri("https://api.wassenger.com/v1/messages"), 
Headers =
{
{ "Token", "API TOKEN GOES HERE" }, 
}, 
Content = new StringContent("{\"channel\":\"${channel_id}@newsletter\", \"message\":\"This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone\", \"deliverAt\":\"2025-01-15T10:42:34.416Z\"}")
{
Headers =
{
ContentType = new MediaTypeHeaderValue("application/json")
}
}
};
using(var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Console.WriteLine(body);
}
// This code requires you to have installed Unirest package.
// Documentation: https://kong.github.io/unirest-java/#requests
// Installation: http://kong.github.io/unirest-java/
HttpResponse<String> response = Unirest.post("https://api.wassenger.com/v1/messages")
.header("Content-Type", "application/json")
.header("Token", "API TOKEN GOES HERE")
.body("{\"channel\":\"${channel_id}@newsletter\", \"message\":\"This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone\", \"deliverAt\":\"2025-01-15T10:42:34.416Z\"}")
.asString();
$headers=@{}
$headers.Add("Content-Type", "application/json")
$headers.Add("Token", "API TOKEN GOES HERE")
$response = Invoke-WebRequest -Uri 'https://api.wassenger.com/v1/messages' -Method POST -Headers $headers -ContentType 'application/json' -Body '{"channel":"${channel_id}@newsletter", "message":"This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone", "deliverAt":"2025-01-15T10:42:34.416Z"}'
require 'uri'
require 'net/http'
url = URI("https://api.wassenger.com/v1/messages")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request["Token"] = 'API TOKEN GOES HERE'
request.body = "{\"channel\":\"${channel_id}@newsletter\", \"message\":\"This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone\", \"deliverAt\":\"2025-01-15T10:42:34.416Z\"}"
response = http.request(request)
puts response.read_body
package main
import(
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url:= "https://api.wassenger.com/v1/messages"
payload:= strings.NewReader("{\"channel\":\"${channel_id}@newsletter\", \"message\":\"This is a scheduled message to be sent tomorrow to a channel.Date format is based on ISO 8601 format with default UTC time zone\", \"deliverAt\":\"2025-01-15T10:42:34.416Z\"}")
req, _:= http.NewRequest("POST", url, payload)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Token", "API TOKEN GOES HERE")
res, _:= http.DefaultClient.Do(req)
defer res.Body.Close()
body, _:= io.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}

🤩 🤖 Wassenger es una plataforma de comunicación completa y una solución API para WhatsApp. Explora más de 100 casos de uso de la API y automatiza cualquier cosa en WhatsApp regístrate para una prueba gratuita y comienza en minutos!

Pruebas en vivo para enviar un mensaje a un grupo vía API

Preguntas frecuentes

¿Cuál es la diferencia entre enviar mensajes individuales y realizar una difusión a un canal de WhatsApp?

Con Wassenger, puedes enviar mensajes individuales para conversaciones personalizadas o mensajes de difusión mediante campañas para alcanzar a múltiples destinatarios simultáneamente. La difusión te permite dirigirte a grupos de clientes de manera eficiente, cumpliendo con las políticas de mensajería de WhatsApp.

¿Wassenger admite la programación de mensajes para canales de WhatsApp?

Sí. Wassenger te permite programar mensajes para fechas y horas específicas, garantizando una comunicación oportuna con tus clientes.

¿Hay límites en la cantidad de mensajes que puedo enviar en un día?

La cantidad de mensajes depende del tipo de cuenta de WhatsApp Business y del plan que tengas. Wassenger ofrece herramientas para ayudarte a mantenerte dentro de las directrices de WhatsApp y evitar sanciones.

¿Puedo incluir multimedia (imágenes, videos, archivos) en mensajes enviados a canales de WhatsApp?

Sí, Wassenger admite mensajería multimedia, lo que te permite enviar imágenes, videos, documentos e incluso notas de voz a contactos o canales de WhatsApp.

Recursos útiles adicionales

Documentación de la API

Para más detalles sobre el endpoint de la API, consulta nuestra documentación. Encontrarás todos los detalles sobre los parámetros de solicitud aceptados, las posibles respuestas de éxito o error y ejemplos de código listos para usar en múltiples lenguajes de programación.

https://app.wassenger.com/docs/#tag/Messages

Ready to transform your WhatsApp communication?

Start automating your customer interactions today with Wassenger

Get Started Free