Ejemplos de la API de WhatsApp en curl, Node, PHP y Python
Estos ejemplos emplean la ruta de envío descrita en la referencia. En todos, la llave de API y el identificador de la conexión se toman de variables de entorno (REPLIFIER_API_KEY y REPLIFIER_CONNECTION), y cada mensaje lleva su propio Idempotency-Key. Si te llega un 429, los ejemplos aguardan los segundos de Retry-After y reintentan con la misma clave, de modo que el mensaje nunca se duplica.
Plantilla con un parámetro:
curl -X POST "https://api.replifier.com/v1/connections/whatsapp/$REPLIFIER_CONNECTION/send" \ -H "Authorization: Bearer $REPLIFIER_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "to": "+5215512345678", "type": "template", "templateName": "pedido_enviado", "languageCode": "es_MX", "components": [{ "type": "body", "parameters": [{ "type": "text", "text": "Ana" }] }] }'Texto libre (dentro de las 24 horas):
curl -X POST "https://api.replifier.com/v1/connections/whatsapp/$REPLIFIER_CONNECTION/send" \ -H "Authorization: Bearer $REPLIFIER_API_KEY" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "to": "+5215512345678", "type": "text", "text": "Tu pedido sale hoy.", "previewUrl": false }'Node.js
Sección titulada «Node.js»Hace falta Node 18 o superior, que ya incluye fetch y crypto.randomUUID().
const BASE = 'https://api.replifier.com'const url = `${BASE}/v1/connections/whatsapp/${process.env.REPLIFIER_CONNECTION}/send`
// Sends one message; retries on 429 with the SAME Idempotency-Key.export async function sendWhatsApp(message, attempts = 3) { const key = crypto.randomUUID() for (let i = 0; i < attempts; i++) { const res = await fetch(url, { method: 'POST', headers: { Authorization: `Bearer ${process.env.REPLIFIER_API_KEY}`, 'Idempotency-Key': key, 'Content-Type': 'application/json', }, body: JSON.stringify(message), }) if (res.status === 429) { const wait = Number(res.headers.get('Retry-After') ?? 60) await new Promise((r) => setTimeout(r, wait * 1000)) continue } const body = await res.json() if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`) if (!body.ok) throw new Error(`Meta rejected it: ${body.providerCode} ${body.providerMessage}`) return body.providerMessageId } throw new Error('rate limited after retries')}
// Template, then free text inside the 24-hour window.await sendWhatsApp({ to: '+5215512345678', type: 'template', templateName: 'pedido_enviado', languageCode: 'es_MX', components: [{ type: 'body', parameters: [{ type: 'text', text: 'Ana' }] }],})await sendWhatsApp({ to: '+5215512345678', type: 'text', text: 'Tu pedido sale hoy.' })<?phpfunction sendWhatsApp(array $message, int $attempts = 3): string { $url = 'https://api.replifier.com/v1/connections/whatsapp/' . getenv('REPLIFIER_CONNECTION') . '/send'; $key = bin2hex(random_bytes(16)); // same key for every retry of this message for ($i = 0; $i < $attempts; $i++) { $headers = []; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('REPLIFIER_API_KEY'), 'Idempotency-Key: ' . $key, 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode($message), CURLOPT_HEADERFUNCTION => function ($c, $line) use (&$headers) { $parts = explode(':', $line, 2); if (count($parts) === 2) $headers[strtolower(trim($parts[0]))] = trim($parts[1]); return strlen($line); }, ]); $raw = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); curl_close($ch); if ($status === 429) { sleep((int) ($headers['retry-after'] ?? 60)); continue; } $body = json_decode($raw, true); if ($status >= 400) throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']); if (!$body['ok']) throw new RuntimeException('Meta rejected it: ' . $body['providerCode']); return $body['providerMessageId']; } throw new RuntimeException('rate limited after retries');}
sendWhatsApp([ 'to' => '+5215512345678', 'type' => 'template', 'templateName' => 'pedido_enviado', 'languageCode' => 'es_MX', 'components' => [['type' => 'body', 'parameters' => [['type' => 'text', 'text' => 'Ana']]]],]);sendWhatsApp(['to' => '+5215512345678', 'type' => 'text', 'text' => 'Tu pedido sale hoy.']);Se apoya en la biblioteca requests (pip install requests).
import osimport timeimport uuid
import requests
URL = f"https://api.replifier.com/v1/connections/whatsapp/{os.environ['REPLIFIER_CONNECTION']}/send"
def send_whatsapp(message: dict, attempts: int = 3) -> str: """Sends one message; retries on 429 with the SAME Idempotency-Key.""" key = str(uuid.uuid4()) for _ in range(attempts): res = requests.post( URL, json=message, headers={ "Authorization": f"Bearer {os.environ['REPLIFIER_API_KEY']}", "Idempotency-Key": key, }, timeout=30, ) if res.status_code == 429: time.sleep(int(res.headers.get("Retry-After", "60"))) continue body = res.json() if not res.ok: raise RuntimeError(f"{body['error']['code']}: {body['error']['message']}") if not body["ok"]: raise RuntimeError(f"Meta rejected it: {body['providerCode']} {body['providerMessage']}") return body["providerMessageId"] raise RuntimeError("rate limited after retries")
send_whatsapp({ "to": "+5215512345678", "type": "template", "templateName": "pedido_enviado", "languageCode": "es_MX", "components": [{"type": "body", "parameters": [{"type": "text", "text": "Ana"}]}],})send_whatsapp({"to": "+5215512345678", "type": "text", "text": "Tu pedido sale hoy."})Los demás tipos de mensaje
Sección titulada «Los demás tipos de mensaje»Los cuerpos que siguen van en el mismo POST y solo funcionan dentro de la ventana de 24 horas. Con cualquiera de las funciones de arriba, pasale el objeto como message.
Imagen con pie de foto:
{ "to": "+5215512345678", "type": "image", "link": "https://midominio.com/fotos/pedido.jpg", "caption": "Tu pedido, empacado" }Documento:
{ "to": "+5215512345678", "type": "document", "link": "https://midominio.com/facturas/1042.pdf", "filename": "factura-1042.pdf", "caption": "Tu factura" }Ubicación:
{ "to": "+5215512345678", "type": "location", "latitude": 19.4326, "longitude": -99.1332, "name": "Sucursal Centro", "address": "Calle 5 de Mayo 10, Ciudad de México" }Botones de respuesta (hasta 3):
{ "to": "+5215512345678", "type": "buttons", "body": "¿Confirmas tu cita de mañana?", "buttons": [{ "id": "confirmar", "title": "Sí, confirmo" }, { "id": "cambiar", "title": "Cambiar hora" }]}Lista:
{ "to": "+5215512345678", "type": "list", "body": "¿Qué necesitas?", "buttonText": "Ver opciones", "sections": [{ "title": "Pedidos", "rows": [ { "id": "rastrear", "title": "Rastrear mi pedido", "description": "Te decimos dónde va" }, { "id": "devolver", "title": "Hacer una devolución" } ] }]}Listo cuando
Sección titulada «Listo cuando»Tu script manda una plantilla y un texto, y al forzar un 429 reintenta con la misma clave sin que el destinatario reciba el mensaje dos veces.