curl, Node, PHP, Python으로 보는 WhatsApp API 예제
이 예제들은 레퍼런스에서 설명한 발송 경로를 사용합니다. 모든 예제에서 API 키와 연결 식별자는 환경 변수(REPLIFIER_API_KEY와 REPLIFIER_CONNECTION)에서 가져오며, 메시지마다 고유한 Idempotency-Key를 보냅니다. 429를 받으면 예제는 Retry-After에 적힌 초만큼 기다린 뒤 같은 키로 다시 시도하므로 메시지가 중복되지 않습니다.
curl
섹션 제목: “curl”매개변수가 하나인 템플릿:
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": "+14155550123", "type": "template", "templateName": "order_shipped", "languageCode": "en_US", "components": [{ "type": "body", "parameters": [{ "type": "text", "text": "Ana" }] }] }'자유 텍스트(24시간 이내):
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": "+14155550123", "type": "text", "text": "Your order ships today.", "previewUrl": false }'Node.js
섹션 제목: “Node.js”Node 18 이상이 필요하며, 여기에는 fetch와 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: '+14155550123', type: 'template', templateName: 'order_shipped', languageCode: 'en_US', components: [{ type: 'body', parameters: [{ type: 'text', text: 'Ana' }] }],})await sendWhatsApp({ to: '+14155550123', type: 'text', text: 'Your order ships today.' })PHP
섹션 제목: “PHP”<?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' => '+14155550123', 'type' => 'template', 'templateName' => 'order_shipped', 'languageCode' => 'en_US', 'components' => [['type' => 'body', 'parameters' => [['type' => 'text', 'text' => 'Ana']]]],]);sendWhatsApp(['to' => '+14155550123', 'type' => 'text', 'text' => 'Your order ships today.']);Python
섹션 제목: “Python”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": "+14155550123", "type": "template", "templateName": "order_shipped", "languageCode": "en_US", "components": [{"type": "body", "parameters": [{"type": "text", "text": "Ana"}]}],})send_whatsapp({"to": "+14155550123", "type": "text", "text": "Your order ships today."})그 밖의 메시지 유형
섹션 제목: “그 밖의 메시지 유형”아래 본문들은 같은 POST에 넣어 보내며 24시간 창 안에서만 동작합니다. 위의 어떤 함수를 사용하든 이 객체를 message로 전달하면 됩니다.
캡션이 있는 이미지:
{ "to": "+14155550123", "type": "image", "link": "https://mydomain.com/fotos/pedido.jpg", "caption": "Your order, packed" }문서:
{ "to": "+14155550123", "type": "document", "link": "https://mydomain.com/facturas/1042.pdf", "filename": "factura-1042.pdf", "caption": "Your invoice" }위치:
{ "to": "+14155550123", "type": "location", "latitude": 19.4326, "longitude": -99.1332, "name": "Downtown branch", "address": "10 Main Street, Mexico City" }답장 버튼(최대 3개):
{ "to": "+14155550123", "type": "buttons", "body": "Do you confirm your appointment tomorrow?", "buttons": [{ "id": "confirmar", "title": "Yes, I confirm" }, { "id": "cambiar", "title": "Change time" }]}목록:
{ "to": "+14155550123", "type": "list", "body": "What do you need?", "buttonText": "See options", "sections": [{ "title": "Orders", "rows": [ { "id": "rastrear", "title": "Track my order", "description": "We tell you where it is" }, { "id": "devolver", "title": "Request a return" } ] }]}완료 기준
섹션 제목: “완료 기준”스크립트가 템플릿과 텍스트를 보내고, 429를 강제로 발생시켰을 때 같은 키로 재시도하더라도 수신자가 메시지를 두 번 받지 않는다면 완료입니다.