콘텐츠로 이동

Replifier 웹훅과 서명 검증

발신 웹훅은 Replifier에서 어떤 일이 일어났을 때 API를 계속 조회하지 않아도 내 시스템에 알려 줍니다. 모든 전달 요청은 Replifier와 나만 아는 시크릿으로 서명됩니다. 누구든 내 URL만 알면 가짜 데이터를 보낼 수 있으므로 내용을 신뢰하기 전에 서명을 검증하세요.

webhooks.manage 권한이 있는 API 키 또는 앱 세션으로 등록합니다.

터미널 창
curl -X POST "https://api.replifier.com/v1/brands/$BRAND_ID/webhooks" \
-H "Authorization: Bearer $REPLIFIER_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "name": "My system", "url": "https://mydomain.com/hooks/replifier", "events": ["message.sent", "message.failed"] }'

사용할 수 있는 이벤트는 message.sent, message.failed, contact.created, contact.updated, contact.unsubscribed, campaign.sent, campaign.failed, campaign.started, flow.email_sent, whatsapp.message.received, whatsapp.message.status, whatsapp.template.status, message.received, message.delivered, message.read, message.replied, link.clicked, conversion.recorded입니다. 응답에는 secret 필드가 단 한 번만 들어 있으니 환경 변수에 보관하세요. 시크릿을 잃어버렸거나 유출이 의심되면 POST /v1/brands/{brandId}/webhooks/{whkId}/rotate-secret으로 교체하세요. 새 시크릿이 반환됩니다.

URL은 localhost나 사설 네트워크 주소를 가리킬 수 없으며, Replifier는 리디렉션을 따라가지 않습니다.

모든 전달 요청은 JSON 본문과 다음 헤더가 포함된 POST입니다.

헤더 내용
X-Replifier-Signature 서명이며 sha256=<16진수> 형태입니다.
X-Replifier-Event 이벤트 유형. 예: message.sent.
X-Replifier-Delivery 전달 요청의 고유 식별자. 중복을 무시할 때 사용하세요.

5초 이내에 2xx 코드로 응답하세요. 그 외의 응답은 실패로 간주됩니다. Replifier는 이전 시도로부터 1분, 5분, 30분, 2시간, 8시간, 24시간 뒤에 최대 6번 재시도합니다. 재시도로 같은 전달 요청이 반복될 수 있으므로 각 X-Replifier-Delivery는 한 번만 처리하세요. 전달 내역은 GET /v1/brands/{brandId}/webhooks/{whkId}/deliveries로 확인하고, POST …/deliveries/{wdlId}/redeliver로 다시 보낼 수 있습니다.

서명은 시크릿을 키로 사용해 요청의 원본 본문에 HMAC-SHA256을 적용한 16진수 값이며, 앞에 sha256=이 붙습니다. 가장 흔한 실수를 막는 세 가지 규칙이 있습니다.

  1. 원본 본문으로 서명하세요. 도착한 그대로의 본문을 사용해야 합니다. 객체로 파싱한 뒤 다시 직렬화하면 공백과 순서가 바뀌어 서명이 더 이상 일치하지 않습니다.
  2. 상수 시간으로 비교하세요. ==가 아니라 사용하는 언어의 전용 함수를 쓰면, 응답 시간을 측정해 서명을 추측하는 공격을 막을 수 있습니다.
  3. 서명이 일치하지 않으면 401로 응답하고 아무것도 처리하지 마세요.
import { createHmac, timingSafeEqual } from 'node:crypto'
import express from 'express'
const app = express()
// express.raw keeps the body exactly as it arrived.
app.post('/hooks/replifier', express.raw({ type: 'application/json' }), (req, res) => {
const expected = 'sha256=' + createHmac('sha256', process.env.REPLIFIER_WEBHOOK_SECRET).update(req.body).digest('hex')
const received = req.get('X-Replifier-Signature') ?? ''
const ok = received.length === expected.length && timingSafeEqual(Buffer.from(received), Buffer.from(expected))
if (!ok) return res.sendStatus(401)
const event = JSON.parse(req.body.toString('utf8'))
console.log(req.get('X-Replifier-Event'), req.get('X-Replifier-Delivery'), event)
res.sendStatus(200)
})
app.listen(3000)
<?php
$raw = file_get_contents('php://input'); // the raw body
$expected = 'sha256=' . hash_hmac('sha256', $raw, getenv('REPLIFIER_WEBHOOK_SECRET'));
$received = $_SERVER['HTTP_X_REPLIFIER_SIGNATURE'] ?? '';
if (!hash_equals($expected, $received)) {
http_response_code(401);
exit;
}
$event = json_decode($raw, true);
error_log($_SERVER['HTTP_X_REPLIFIER_EVENT'] . ' ' . $_SERVER['HTTP_X_REPLIFIER_DELIVERY']);
http_response_code(200);
import hashlib
import hmac
import os
from flask import Flask, abort, request
app = Flask(__name__)
@app.post("/hooks/replifier")
def replifier_hook():
raw = request.get_data() # the raw body
expected = "sha256=" + hmac.new(os.environ["REPLIFIER_WEBHOOK_SECRET"].encode(), raw, hashlib.sha256).hexdigest()
received = request.headers.get("X-Replifier-Signature", "")
if not hmac.compare_digest(expected, received):
abort(401)
event = request.get_json()
print(request.headers["X-Replifier-Event"], request.headers["X-Replifier-Delivery"], event)
return "", 200

실제 전달 요청을 기다리지 않고 코드를 확인하려면, openssl로 테스트 본문에 서명한 뒤 서버가 계산한 값과 비교하세요.

터미널 창
BODY='{"hello":"world"}'
printf 'sha256=%s\n' "$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$REPLIFIER_WEBHOOK_SECRET" -hex | sed 's/^.* //')"
curl -X POST http://localhost:3000/hooks/replifier \
-H "Content-Type: application/json" \
-H "X-Replifier-Signature: sha256=<the signature above>" \
-d "$BODY"

각 전송의 본문은 이벤트에 따라 다릅니다. 아래에 그룹별 필드가 있습니다. 이후 버전에서 필드가 추가될 수 있으니 모르는 필드는 무시하세요. 모든 이벤트의 정확한 샘플은 GET /v1/hooks/samples/{event}로 받을 수 있습니다.

이메일, 연락처, 캠페인, 플로우

섹션 제목: “이메일, 연락처, 캠페인, 플로우”

이 이벤트들은 event 필드와 표의 필드로 이루어진 평평한 JSON입니다. id는 이벤트에 따라 발송, 연락처 또는 캠페인의 식별자입니다.

이벤트 필드
message.sent, message.failed id, brandId
contact.created, contact.updated id, brandId
contact.unsubscribed contactId, listId, brandId
campaign.started, campaign.sent id
campaign.failed id, reason
flow.email_sent flowId, nodeId, contactId, sendId, campaignId

whatsapp.message.received, whatsapp.message.status, whatsapp.template.status는 수신 메시지, 전달 상태, 템플릿 심사를 알려 줍니다. 필드는 WhatsApp API 레퍼런스에 설명되어 있습니다.

message.received, message.delivered, message.read, message.replied, link.clicked, conversion.recorded는 id, type(이벤트와 같음), created_at, data로 이루어진 공통 봉투를 사용합니다. 예를 들어 클릭은 다음과 같습니다.

{
"id": "evt_…",
"type": "link.clicked",
"created_at": "2026-01-01T00:00:00.000Z",
"data": {
"message_id": "ccm_…",
"contact_id": "ctc_…",
"brand_id": "brd_…",
"campaign_id": "cmp_…",
"channel": "email",
"url": "https://example.com"
}
}

data에는 식별자만 들어가며 메시지 내용은 절대 포함되지 않습니다. message_id, contact_id, brand_id와, 해당하는 경우 campaign_id와 channel(예: whatsapp, email)이 들어갑니다. 값이 없는 키는 생략됩니다. link.clicked는 url을, conversion.recorded는 amount, currency, order_id를 추가합니다. message.delivered와 message.read는 WhatsApp과 SMS 메시지에 대해 전송됩니다.

엔드포인트가 시크릿으로 서명된 전달 요청에는 200으로 응답하고, 본문이나 서명을 한 글자라도 바꾸면 401로 응답하며, 각 X-Replifier-Delivery를 한 번만 처리한다면 완료입니다.