"""틱톡 광고(TikTok API for Business v1.3) — 날짜별 광고비·매출·ROAS. 화면은 틱톡 탭(광고비 탭·매출 실적에는 안 나옴). 인증(2026-11-05): 광고 계정(advertiser) ID 하나 + 장기 액세스 토큰(머리글 Access-Token). 토큰 앱에 보고서·광고 계정 읽기 권한이 있어야 한다. 조회 GET /report/integrated/get/ — report_type=BASIC · data_level=AUCTION_ADVERTISER · 차원 advertiser_id·stat_time_day. 매출 = 웹 구매금액(total_complete_payment_rate — 이름과 달리 금액) + 틱톡샵 매출(total_onsite_shopping_value). GET /gmv_max/report/get/ — 틱톡샵 ID 를 넣었을 때만. 비용(cost)·매출(gross_revenue)을 더한다. - 하루 단위 조회는 기간 제한이 있어 30일씩 나눠 묻는다. - 금액은 광고 계정 통화 → 그날 환율로 원화(fx.krw_rates, 메타와 같음). - ROAS(%) = 매출 ÷ 광고비 × 100(합친 값으로 계산 — 틱톡의 ROAS 칸은 더할 수 없다). 공식 문서가 스크립트 화면이라 지표 이름을 이차 자료로 확인했다 — 연결 테스트가 어제 하루를 실제로 물어 지표 이름 오류까지 잡는다. """ from __future__ import annotations import json import re from datetime import date, timedelta from decimal import ROUND_HALF_UP, Decimal from typing import Any import httpx from app.timezone import today_kst from .. import fx from ..adapters.base import AdapterContext, ApiError, AuthFailed, CredentialField, TokenExpired from .base import AdDay, AdSource from .meta_ads import _num, _won API_BASE = "https://business-api.tiktok.com/open_api/v1.3" MAX_DAYS = 366 SPAN_DAYS = 30 PAGE_SIZE = 100 # 계정 하나·30일 = 많아야 30줄이라 한 쪽이면 된다 RATE_LIMIT = 40100 REPORT_METRICS = ("spend", "impressions", "clicks", "complete_payment", "total_complete_payment_rate", "onsite_shopping", "total_onsite_shopping_value") GMV_METRICS = ("cost", "gross_revenue", "orders") # metrics 키 — 화면 이름 그대로 저장. 틱톡 탭은 M_REVENUE 를 매출로 읽는다(ad_spend.build_tiktok_dashboard). M_SPEND, M_REVENUE, M_ROAS = "광고비", "매출", "ROAS(%)" M_IMPR, M_CLICKS, M_ORDERS = "노출수", "클릭수", "구매수" M_WEB, M_SHOP, M_GMV_COST, M_GMV_REVENUE = "웹 구매금액", "틱톡샵 매출", "GMV Max 비용", "GMV Max 매출" def _http(ctx: AdapterContext) -> httpx.Client: """HTTP 클라이언트 — 테스트가 바꿔 끼운다.""" return httpx.Client(timeout=ctx.timeout_sec) def _spans(start: date, end: date) -> list[tuple[date, date]]: """기간을 SPAN_DAYS 일씩 나눈다.""" out = [] while start <= end: stop = min(start + timedelta(days=SPAN_DAYS - 1), end) out.append((start, stop)) start = stop + timedelta(days=1) return out class TiktokAdsSource(AdSource): code = "tiktok" name = "틱톡" docs_url = "https://business-api.tiktok.com/portal/docs" note = ("TikTok API for Business 로 날짜별 광고비·매출·ROAS 를 가져와 틱톡 탭에 보여 줍니다(매출 실적·광고비 탭 합계에는 들어가지 않음). " "준비: 개발자 앱에서 광고 계정을 승인해 장기 액세스 토큰 발급(보고서·광고 계정 읽기 권한). 외화 계정은 그날 환율로 원화로 바꿉니다.") def credential_fields(self) -> list[CredentialField]: return [ CredentialField("advertiser_id", "광고 계정 ID", placeholder="7123456789012345678", help="틱톡 광고 관리자 주소의 aadvid= 뒤 숫자."), CredentialField("access_token", "액세스 토큰", secret=True, help="광고 계정을 승인할 때 받은 장기 액세스 토큰. 저장 후에는 화면에 다시 보이지 않습니다."), CredentialField("shop_id", "틱톡샵 ID", required=False, placeholder="GMV Max 캠페인을 쓸 때만", help="GMV Max 캠페인은 일반 보고서와 따로 조회합니다 — 넣으면 그 비용·매출도 더합니다. 안 쓰면 비워 둡니다."), ] def validate_credentials(self, values: dict[str, str]) -> list[str]: errors = super().validate_credentials(values) advertiser = (values.get("advertiser_id") or "").strip() if advertiser and advertiser != "__stored__" and not re.fullmatch(r"\d{5,30}", advertiser): errors.append("광고 계정 ID 는 숫자여야 합니다.") shop = (values.get("shop_id") or "").strip() if shop and shop != "__stored__" and not re.fullmatch(r"\d{5,30}", shop): errors.append("틱톡샵 ID 는 숫자여야 합니다.") token = (values.get("access_token") or "").strip() if token and token != "__stored__" and (len(token) < 20 or re.search(r"\s", token)): errors.append("액세스 토큰 형식이 아닙니다(공백 없이 통째로 붙여 넣으세요).") return errors def _get(self, ctx: AdapterContext, client: httpx.Client, path: str, params: dict[str, Any]) -> dict[str, Any]: """틱톡은 오류도 HTTP 200 + code 로 준다. 토큰은 머리글로만 보내 주소·오류 문구에 들어가지 않는다.""" ctx.progress.check() token = (ctx.credentials.get("access_token") or "").strip() try: resp = client.get(API_BASE + path, params=params, headers={"Access-Token": token}) except httpx.HTTPError as exc: raise ApiError(f"틱톡 API 에 연결하지 못했습니다({type(exc).__name__}).") from None try: body = resp.json() except ValueError: raise ApiError(f"틱톡 API 응답을 읽을 수 없습니다(HTTP {resp.status_code}).") from None code = body.get("code") if isinstance(body, dict) else None if resp.status_code == 200 and code == 0: return body.get("data") or {} text = f"틱톡 API 오류({code if code is not None else resp.status_code}): {str((body or {}).get('message') or '')[:200]}" if code == 40102: raise TokenExpired(text + " — 액세스 토큰을 다시 발급해 넣으세요.") if code == RATE_LIMIT: raise ApiError(text + " — 호출 한도에 걸렸습니다. 잠시 뒤 다시 누르세요.") if resp.status_code in (401, 403) or (isinstance(code, int) and 40100 < code < 40200): raise AuthFailed(text + " — 토큰과 광고 계정 ID, 앱 권한을 확인하세요.") raise ApiError(text) def _info(self, ctx: AdapterContext, client: httpx.Client) -> dict[str, Any]: advertiser = (ctx.credentials.get("advertiser_id") or "").strip() rows = self._get(ctx, client, "/advertiser/info/", { "advertiser_ids": json.dumps([advertiser]), "fields": json.dumps(["name", "currency", "timezone"])}).get("list") or [] if not rows: raise AuthFailed("이 토큰으로 볼 수 없는 광고 계정입니다 — 광고 계정 ID 와 승인 여부를 확인하세요.") return rows[0] def _rows(self, ctx: AdapterContext, client: httpx.Client, path: str, metrics: tuple[str, ...], start: date, end: date, **extra: Any) -> list[tuple[date, dict[str, Any]]]: """보고서 하나를 30일씩 물어 (날짜, 지표) 목록으로.""" advertiser = (ctx.credentials.get("advertiser_id") or "").strip() out = [] for s, e in _spans(start, end): data = self._get(ctx, client, path, { "advertiser_id": advertiser, "dimensions": json.dumps(["advertiser_id", "stat_time_day"]), "metrics": json.dumps(metrics), "start_date": s.isoformat(), "end_date": e.isoformat(), "page": 1, "page_size": PAGE_SIZE, **extra}) for r in data.get("list") or []: try: day = date.fromisoformat(str((r.get("dimensions") or {}).get("stat_time_day"))[:10]) except ValueError: continue out.append((day, r.get("metrics") or {})) return out def _collect(self, ctx: AdapterContext, client: httpx.Client, start: date, end: date) -> dict[date, dict[str, Decimal]]: """날짜 → 항목 합(계정 통화).""" sums: dict[date, dict[str, Decimal]] = {} def day_of(d: date) -> dict[str, Decimal]: return sums.setdefault(d, {k: Decimal(0) for k in ("spend", "impr", "clicks", "orders", "web", "shop", "gmv_cost", "gmv")}) for d, m in self._rows(ctx, client, "/report/integrated/get/", REPORT_METRICS, start, end, report_type="BASIC", data_level="AUCTION_ADVERTISER"): one = day_of(d) one["spend"] += _num(m.get("spend")) one["impr"] += _num(m.get("impressions")) one["clicks"] += _num(m.get("clicks")) one["orders"] += _num(m.get("complete_payment")) + _num(m.get("onsite_shopping")) one["web"] += _num(m.get("total_complete_payment_rate")) one["shop"] += _num(m.get("total_onsite_shopping_value")) shop_id = (ctx.credentials.get("shop_id") or "").strip() if shop_id: for d, m in self._rows(ctx, client, "/gmv_max/report/get/", GMV_METRICS, start, end, store_ids=json.dumps([shop_id])): one = day_of(d) one["orders"] += _num(m.get("orders")) one["gmv_cost"] += _num(m.get("cost")) one["gmv"] += _num(m.get("gross_revenue")) return sums def test_connection(self, ctx: AdapterContext) -> str: self.require_configured(ctx) yesterday = today_kst() - timedelta(days=1) with _http(ctx) as client: info = self._info(ctx, client) self._collect(ctx, client, yesterday, yesterday) # 지표 이름·GMV Max 권한까지 실제로 확인 return f"연결됨 — {info.get('name') or '광고 계정'}({info.get('currency') or '?'}·{info.get('timezone') or '?'})" def fetch_days(self, ctx: AdapterContext, start: date, end: date) -> list[AdDay]: if end < start: start, end = end, start if (end - start).days + 1 > MAX_DAYS: raise ApiError(f"한 번에 {MAX_DAYS}일까지 가져올 수 있습니다.") self.require_configured(ctx) with _http(ctx) as client: currency = str(self._info(ctx, client).get("currency") or "").upper() if not re.fullmatch(r"[A-Z]{3}", currency): raise ApiError(f"광고 계정 통화({currency[:10] or '없음'})를 알 수 없습니다.") sums = self._collect(ctx, client, start, end) try: rates = fx.krw_rates(client, currency, start, end) if sums else {} except fx.FxError as exc: raise ApiError(f"{currency} 광고 계정을 원화로 바꿀 환율을 가져오지 못했습니다 — {exc}") from None return [_day(d, sums[d], rates[d]) for d in sorted(sums)] def _day(day: date, a: dict[str, Decimal], rate: Decimal) -> AdDay: """합친 값(계정 통화) → 하루치(원화). ROAS 는 비율이라 반올림 전 값으로.""" spend = (a["spend"] + a["gmv_cost"]) * rate revenue = (a["web"] + a["shop"] + a["gmv"]) * rate roas = (revenue / spend * 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if spend > 0 else None return AdDay(day=day, amount=_won(spend), roas=roas, metrics={ M_SPEND: _won(spend), M_REVENUE: _won(revenue), M_ROAS: float(roas) if roas is not None else None, M_WEB: _won(a["web"] * rate), M_SHOP: _won(a["shop"] * rate), M_GMV_COST: _won(a["gmv_cost"] * rate), M_GMV_REVENUE: _won(a["gmv"] * rate), M_IMPR: int(a["impr"]), M_CLICKS: int(a["clicks"]), M_ORDERS: int(a["orders"]), })