본문으로 건너뛰기
엔지니어링 · · 5분 소요

웹훅으로 딥 링크 이벤트를 Slack 알림으로 받기

작성자 Tolinku 팀
|
웹훅으로 딥 링크 이벤트를 Slack 알림으로 받기

딥 링크 이벤트가 실시간으로 Slack에 쌓이는 걸 지켜보면 묘하게 동기가 생겨요. 그로스 팀은 설치 알림을 보고 캠페인이 잘 되고 있다는 걸 알아요. 엔지니어링 팀은 웹훅 실패를 보고 고객 지원 티켓으로 번지기 전에 조사할 수 있어요. 프로덕트 매니저는 추천 완료 알림을 보고 추천 흐름이 제대로 작동한다는 걸 알아요.

이 가이드에서는 세 가지 방법을 다뤄요. Tolinku 웹훅 모두 이벤트를 Slack으로 보내는 방법이에요. Slack의 수신 웹훅을 직접 쓰는 연동, 메시지 형식을 꾸밀 수 있는 커스텀 수신기, Zapier로 코드 없이 연결하는 방법이 있어요. 팀의 엔지니어링 여력에 맞는 방법을 고르세요.

이벤트 알림을 위한 Tolinku 웹훅 설정 생성 폼, 웹훅 목록, 전달 로그가 있는 웹훅 페이지.

방법 1: Slack 수신 웹훅 직접 연결

가장 간단한 방법이에요. Slack의 수신 웹훅 을 쓰면 채널 URL로 JSON 메시지를 POST할 수 있어요. Slack 앱을 따로 설치할 필요 없이 Slack에서 받은 웹훅 URL만 있으면 돼요.

Slack 웹훅 설정

  1. 다음 페이지로 이동하세요: api.slack.com/apps 에서 새 앱을 만들어요(기존 앱이 있으면 그걸 써도 돼요).
  2. 다음 조항에 따르면 기능 > 수신 웹훅으로 가서 켜세요.
  3. Click 워크스페이스에 새 웹훅 추가 채널을 선택하세요(예: #deep-link-events).
  4. 웹훅 URL을 복사하세요(예: https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX)

수신기 만들기

import express from 'express';
import crypto from 'crypto';

const app = express();
app.use('/webhooks', express.raw({ type: 'application/json' }));

const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET!;
const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL!;

app.post('/webhooks/tolinku', async (req, res) => {
  const signature = req.headers['x-webhook-signature'] as string;
  const expected = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(req.body)
    .digest('hex');

  if (signature !== expected) {
    return res.status(401).send('Invalid signature');
  }

  res.status(200).send('OK');

  const event = JSON.parse(req.body.toString());
  await sendToSlack(event);
});

async function sendToSlack(event: any) {
  const message = formatSlackMessage(event);

  await fetch(SLACK_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(message),
  });
}

app.listen(3000);

메시지 포맷 설정

일반 텍스트 알림도 동작하지만 Block Kit 을 쓰면 바쁜 채널에서 메시지를 훑어보기 쉬워요.

function formatSlackMessage(event: any) {
  const { event: eventType, timestamp, data } = event;
  const time = new Date(timestamp).toLocaleString('en-US', {
    timeZone: 'UTC',
    hour12: false,
  });

  const emoji = getEmoji(eventType);
  const title = getTitle(eventType);

  const fields: Array<{ type: string; text: string }> = [];

  if (data.campaign) {
    fields.push({
      type: 'mrkdwn',
      text: `*캠페인:* ${data.campaign}`,
    });
  }
  if (data.platform) {
    fields.push({
      type: 'mrkdwn',
      text: `*플랫폼:* ${data.platform}`,
    });
  }
  if (data.token) {
    fields.push({
      type: 'mrkdwn',
      text: `*링크:* ${data.prefix || ''}/${data.token}`,
    });
  }
  if (data.device_type) {
    fields.push({
      type: 'mrkdwn',
      text: `*기기:* ${data.device_type}`,
    });
  }

  return {
    blocks: [
      {
        type: 'section',
        text: {
          type: 'mrkdwn',
          text: `${emoji} *${title}*`,
        },
      },
      ...(fields.length > 0
        ? [
            {
              type: 'section',
              fields,
            },
          ]
        : []),
      {
        type: 'context',
        elements: [
          {
            type: 'mrkdwn',
            text: `${time} UTC`,
          },
        ],
      },
    ],
  };
}

function getEmoji(eventType: string): string {
  const emojis: Record<string, string> = {
    'link.clicked': ':link:',
    'deferred_link.claimed': ':calling:',
    'install.tracked': ':iphone:',
    'referral.created': ':handshake:',
    'referral.completed': ':tada:',
    'test': ':test_tube:',
  };
  return emojis[eventType] || ':bell:';
}

function getTitle(eventType: string): string {
  const titles: Record<string, string> = {
    'link.clicked': '링크 클릭됨',
    'deferred_link.claimed': '디퍼드 링크 확인됨',
    'install.tracked': '설치 추적됨',
    'referral.created': '추천 생성됨',
    'referral.completed': '추천 완료됨',
    'test': '테스트 웹훅',
  };
  return titles[eventType] || eventType;
}

이렇게 하면 이벤트 유형, 관련 필드, 타임스탬프가 담긴 깔끔한 Slack 메시지가 만들어져요.

방법 2: 필터링된 알림

아마 모든 이벤트가 link.clicked Slack 채널을 뒤덮는 건 원하지 않을 거예요. 트래픽이 많은 링크는 하루에 수천 건의 클릭이 발생할 수 있어요. 중요한 신호만 남기는 방법을 소개할게요.

원본에서 필터링

대시보드에서 웹훅을 설정할 때 Tolinku, 알림을 받을 이벤트만 선택하세요. 대부분의 팀에서는 install.tracked, referral.created, referral.completed 알림을 받을 가치가 있는 핵심 이벤트이고, 나머지는 link.clicked 대신 분석 파이프라인에서 처리하세요.

수신기에서 필터링

웹훅 하나에서 여러 이벤트를 구독한다면, 핸들러에서 필터링하세요:

const NOTIFY_EVENTS = new Set([
  'install.tracked',
  'referral.created',
  'referral.completed',
]);

async function sendToSlack(event: any) {
  if (!NOTIFY_EVENTS.has(event.event)) return;

  const message = formatSlackMessage(event);
  await fetch(SLACK_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(message),
  });
}

이벤트마다 알리는 대신 집계하기

클릭 이벤트는 개별 알림보다 주기적인 요약이 더 유용해요. 이벤트를 모았다가 다이제스트로 보내세요:

let clickBuffer: any[] = [];

setInterval(async () => {
  if (clickBuffer.length === 0) return;

  const count = clickBuffer.length;
  const campaigns = new Map<string, number>();
  for (const event of clickBuffer) {
    const campaign = event.data.campaign || 'unknown';
    campaigns.set(campaign, (campaigns.get(campaign) || 0) + 1);
  }

  const campaignList = [...campaigns.entries()]
    .sort((a, b) => b[1] - a[1])
    .map(([name, n]) => `  ${name}: ${n}`)
    .join('\n');

  await fetch(SLACK_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      text: `:chart_with_upwards_trend: 지난 15분 동안 *${count}건의 링크 클릭*\n${campaignList}`,
    }),
  });

  clickBuffer = [];
}, 15 * 60 * 1000); // 15분마다

방법 3: 여러 채널

대상에 맞게 이벤트마다 다른 Slack 채널로 보내세요:

const CHANNEL_MAP: Record<string, string> = {
  'install.tracked': process.env.SLACK_GROWTH_CHANNEL!,
  'referral.created': process.env.SLACK_GROWTH_CHANNEL!,
  'referral.completed': process.env.SLACK_SALES_CHANNEL!,
  'link.clicked': process.env.SLACK_ANALYTICS_CHANNEL!,
};

async function sendToSlack(event: any) {
  const channelUrl = CHANNEL_MAP[event.event];
  if (!channelUrl) return;

  const message = formatSlackMessage(event);
  await fetch(channelUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(message),
  });
}

Slack 수신 웹훅은 특정 채널에 연결되므로, 대상 채널마다 별도의 웹훅 URL이 필요해요.

방법 4: Zapier로 코드 없이 연결

수신 서버를 직접 운영하고 싶지 않다면 Zapier 을 써서 Tolinku 웹훅을 Slack에 연결하세요:

  1. 트리거로 "Webhooks by Zapier"(Catch Hook)를 사용해 Zap을 만드세요
  2. 원하는 이벤트 유형을 고르는 Filter 단계 추가
  3. Slack 액션 추가: "Send Channel Message"
  4. 웹훅 필드를 메시지에 매핑

트레이드오프가 있어요. Zapier는 웹훅 서명을 검증하지 않고, 전달 시점은 Zapier 요금제의 폴링 간격에 따라 달라져요. 중요하지 않은 알림이라면 괜찮아요. 운영 환경의 알림이라면 직접 만든 수신 서버를 사용하세요.

실패 처리

Slack API가 중단되었거나 속도 제한에 걸리면 알림 전송이 실패해요. 하지만 웹훅 처리에는 영향을 주면 안 돼요. 항상 다음과 같이 하세요:

  1. Slack 알림을 시도하기 전에 Tolinku에 200 응답을 보내세요
  2. Slack API 오류를 잡아서 기록하고, 다시 던지지 마세요
  3. Slack 전송 실패에 대해 지수 백오프를 적용한 간단한 재시도를 고려해 보세요
async function sendToSlack(event: any) {
  if (!NOTIFY_EVENTS.has(event.event)) return;

  const message = formatSlackMessage(event);

  for (let attempt = 0; attempt < 3; attempt++) {
    try {
      const resp = await fetch(SLACK_WEBHOOK_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(message),
      });
      if (resp.ok) return;
      if (resp.status === 429) {
        // Rate limited; wait and retry
        const retryAfter = parseInt(resp.headers.get('retry-after') || '5');
        await new Promise(r => setTimeout(r, retryAfter * 1000));
        continue;
      }
      console.error(`Slack API error: ${resp.status}`);
      return;
    } catch (err) {
      console.error('Slack send failed:', err);
      if (attempt < 2) await new Promise(r => setTimeout(r, 1000 * (attempt + 1)));
    }
  }
}

Slack 웹훅 API의 속도 제한은 웹훅 URL당 초당 1개 메시지예요. 이보다 많이 보내야 한다면 알림을 묶거나 집계하세요.

설정 방법은 웹훅 설정 가이드부터 보세요.. 연동을 확인하려면 다음 문서에 있는 웹훅 테스트 가이드.

딥 링킹 팁을 메일로 받아 보세요

일주일에 한 번만 보내요. 스팸은 없어요.

앱에 딥 링킹을 추가해 볼까요?

유니버설 링크, 앱 링크, 디퍼드 딥 링킹, 분석을 몇 분 만에 설정할 수 있어요. 무료로 시작하세요.