feat: Meta 픽셀 및 전환 추적 연동

- index.html에 Meta Pixel 스크립트 및 noscript 폴백 추가 (PageView 자동 추적)
- 전환 추적 유틸 추가 (trackViewContent, trackCompleteRegistration,
  trackFirstVideoCreated) — 서버 CAPI와 동일 event_id로 픽셀 발화해 중복제거
- 랜딩 진입 시 UTM 파라미터 first-touch 캡처 (localStorage 보존,
  가입 전환 시 서버로 전달 후 제거)
- 카카오 로그인 콜백에서 is_new_user 판정 시 CompleteRegistration 발화
  (토큰 리다이렉트 경로 + code 콜백 경로 모두 처리)
- 영상 생성 완료 시 FirstVideoCreated 발화
- KakaoCallbackResponse 타입을 백엔드 LoginResponse 구조에 맞게 수정
  (user 객체 제거, is_new_user 평탄화)
- logout이 refresh_token을 body로 전달하도록 수정, 실패해도
  로컬 데이터는 항상 삭제되도록 try/finally 처리

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
skkimandClaude Fable 5 committed 2026-07-24 10:28:51 +09:00
1 parent a853c714fd
commit f36fd5a3cb
6 files changed
+205 -24

No files matched your search

+150 -7
View File
@@ -309,6 +309,139 @@ export async function generateVideo(taskId: string, orientation: 'vertical' | 'h
return response.json();
}
// ============================================================
// Meta 전환 추적 (FirstVideoCreated)
// ============================================================
// Meta 픽셀이 심는 1st-party 쿠키 값 읽기 (_fbc/_fbp)
function getCookieValue(name: string): string | null {
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : null;
}
// 첫 영상 생성 완료(FirstVideoCreated) 전환 이벤트 발화 API
// 서버가 first_video_created_at null 여부로 계정당 최초 1회를 판정하고,
// fired=true일 때만 브라우저 픽셀(fbq)을 동일 event_id로 발화해 중복제거를 보장한다.
export async function trackFirstVideoCreated(): Promise<void> {
try {
const response = await authenticatedFetch(`${API_URL}/tracking/meta/first-video-created`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fbc: getCookieValue('_fbc'),
fbp: getCookieValue('_fbp'),
event_source_url: window.location.href,
}),
});
if (!response.ok) return;
const data: { fired: boolean; event_id: string | null } = await response.json();
const fbq = (window as unknown as { fbq?: (...args: unknown[]) => void }).fbq;
if (data.fired && data.event_id && typeof fbq === 'function') {
// 서버 CAPI 이벤트와 동일한 event_id로 발화 → Meta가 중복제거
fbq('trackCustom', 'FirstVideoCreated', {}, { eventID: data.event_id });
}
} catch (error) {
// 전환 추적 실패는 서비스 기능에 영향을 주지 않도록 무시
console.error('[Tracking] FirstVideoCreated failed:', error);
}
}
// UTM 파라미터 localStorage 키 (first-touch 보존)
const UTM_STORAGE_KEY = 'castad_utm';
const UTM_PARAM_NAMES = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'] as const;
// fbq 전역 함수 안전 접근
function getFbq(): ((...args: unknown[]) => void) | null {
const fbq = (window as unknown as { fbq?: (...args: unknown[]) => void }).fbq;
return typeof fbq === 'function' ? fbq : null;
}
// 랜딩 진입 URL의 UTM 파라미터를 localStorage에 저장 (first-touch)
// 이미 저장된 값이 있으면 덮어쓰지 않아 최초 유입 경로를 보존한다.
export function storeUtmFromUrl(): void {
try {
if (localStorage.getItem(UTM_STORAGE_KEY)) return;
const params = new URLSearchParams(window.location.search);
const utm: Record<string, string> = {};
for (const name of UTM_PARAM_NAMES) {
const value = params.get(name);
if (value) utm[name] = value;
}
if (Object.keys(utm).length > 0) {
localStorage.setItem(UTM_STORAGE_KEY, JSON.stringify(utm));
}
} catch (error) {
console.error('[Tracking] storeUtmFromUrl failed:', error);
}
}
// 랜딩 진입(ViewContent) 이벤트 발화 — 비로그인 시점이므로 브라우저 픽셀 단독
export function trackViewContent(): void {
try {
const fbq = getFbq();
if (fbq) {
fbq('track', 'ViewContent', {}, { eventID: crypto.randomUUID() });
}
} catch (error) {
console.error('[Tracking] ViewContent failed:', error);
}
}
// 회원가입 완료(CompleteRegistration) 전환 이벤트 발화 API
// 서버가 registration_tracked_at null 여부로 계정당 최초 1회를 판정하고 UTM을 함께 기록한다.
// fired=true일 때만 브라우저 픽셀(fbq)을 동일 event_id로 발화해 중복제거를 보장한다.
export async function trackCompleteRegistration(): Promise<void> {
try {
let utm: Record<string, string> = {};
try {
utm = JSON.parse(localStorage.getItem(UTM_STORAGE_KEY) ?? '{}');
} catch {
utm = {};
}
const response = await authenticatedFetch(`${API_URL}/tracking/meta/complete-registration`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fbc: getCookieValue('_fbc'),
fbp: getCookieValue('_fbp'),
event_source_url: window.location.href,
utm_source: utm.utm_source ?? null,
utm_medium: utm.utm_medium ?? null,
utm_campaign: utm.utm_campaign ?? null,
utm_content: utm.utm_content ?? null,
utm_term: utm.utm_term ?? null,
}),
});
if (!response.ok) return;
const data: { fired: boolean; event_id: string | null } = await response.json();
if (data.fired && data.event_id) {
const fbq = getFbq();
if (fbq) {
// 서버 CAPI 이벤트와 동일한 event_id로 발화 → Meta가 중복제거
fbq('track', 'CompleteRegistration', {}, { eventID: data.event_id });
}
// 가입 어트리뷰션 저장 완료 → 보관하던 UTM 제거
localStorage.removeItem(UTM_STORAGE_KEY);
}
} catch (error) {
// 전환 추적 실패는 서비스 기능에 영향을 주지 않도록 무시
console.error('[Tracking] CompleteRegistration failed:', error);
}
}
// 영상 상태 확인 API
export async function getVideoStatus(taskId: string): Promise<VideoStatusResponse> {
const response = await authenticatedFetch(`${API_URL}/video/status/${taskId}`, {
@@ -764,15 +897,25 @@ function clearAllLocalData() {
// 로그아웃
export async function logout(): Promise<void> {
const response = await authenticatedFetch(`${API_URL}/user/auth/logout`, {
method: 'POST',
});
const refreshToken = getRefreshToken();
// 응답과 관계없이 로컬 데이터 전체 삭제
clearAllLocalData();
try {
if (refreshToken) {
const response = await authenticatedFetch(`${API_URL}/user/auth/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
}
} finally {
// 응답과 관계없이 로컬 데이터 전체 삭제
clearAllLocalData();
}
}