"""카카오 — 카카오쇼핑(톡스토어) Open API(shopping-developers.kakao.com, 2026-10-13 문서 확인). 인증(“API 공통 인증 헤더 구성”) — 모든 호출에 같은 헤더 3개, 주소 https://kapi.kakao.com Authorization: KakaoAK {앱 어드민 키} 카카오디벨로퍼스 앱(연동 앱) → 앱 설정 → 앱 → 어드민 키 Target-Authorization: KakaoAK {판매자 API 인증키} 카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키 channel-ids: 101(톡스토어) / 1(선물하기) / "1,101"(둘 다) 두 헤더에 같은 앱의 키를 넣으면 {"code": -2, "msg": "invalid authorization or target-authorization header."}, 판매자 인증키가 바뀌었거나 무효면 {"code": -401, "msg": "appKey(판매자인증키) is already deactivated"}, 연동 앱과 판매자가 연결되지 않았으면 "대행사 매핑/권한 확인이 필요합니다." Open API 는 카카오쇼핑 검토를 거쳐 허락된 앱만 쓸 수 있다(“카카오쇼핑 API 연동 검토 요청하기”). 매출 수집 — 네이버와 같은 기준(결제일, 할인 뒤 상품 금액, 배송비 제외, 결제 뒤 취소·반품분도 결제일 매출에 포함): - 결제일시 기준 주문내역 조회 GET /v2/shopping/orders/paidAt?from=YYYY-MM-DD HH:mm:ss&to=…&size=100(&token=) — 한 번에 24시간까지(하루씩 부른다), 쪽당 100건, 다음 쪽은 응답의 token(더 없으면 token 없음). 목록에는 금액이 없다(orderId·paymentId·orderStatus·paidAt …). - 주문 하나씩 주문정보 조회 GET /v1/shopping/order?order_id= 로 orderProduct 금액을 받는다. 한 번 받은 주문은 목록의 modifiedAt 이 같으면 다시 부르지 않는다(프로세스 안 메모리 캐시). - 카카오 주문(orderId)은 상품 한 줄이고 결제(paymentId)가 장바구니 하나 → SALE = 결제 하나(`kakao:{paymentId}`), 날짜 = 결제일(paidAt, 한국 시간), 금액 = 그 결제에 든 상품 줄 금액 합. - 상품 줄 금액(line_amount) = (productPrice + optionPrice) × quantity − sellerDiscountPrice − sellerCouponDiscountPrice − adminDiscountPrice. 문서에 결제금액 항목이 따로 없어 이 식으로 만든다 — **판매자센터 매출 화면과 아직 대조 전**. 설정 화면 "쇼핑몰 원본 데이터 확인"에서 항목별 합계를 보고 맞는 식으로 확정한다. - 미결제(주문 생성·결제 요청·입금 대기/확인·결제 실패·미입금 취소)만 뺀다. - 구매자 이름·연락처·주소는 저장하지 않는다(원본 확인에서도 값 없이 이름만). """ from __future__ import annotations import re import time from datetime import date, timedelta from typing import Any, Iterable from .base import ( AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, MarketplaceAdapter, NotConfigured, SaleEvent, ) from .naver import field_summary, flatten HOST = "https://kapi.kakao.com" PAID_PATH = "/v2/shopping/orders/paidAt" ORDER_PATH = "/v1/shopping/order" EVENT_PREFIX = "kakao:" DEFAULT_CHANNELS = "101" # 톡스토어 PAGE_SIZE = 100 MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지 CALL_INTERVAL_SEC = 0.1 # 호출 사이 간격(문서에 제한 없음 — 넉넉히) RETRY_429 = 3 PROBE_MAX_DAYS = 31 CACHE_MAX = 20000 # 매출에서 빼는 상태 — 결제되지 않은 것만. 결제 뒤 취소·반품은 결제일 매출에 그대로(네이버 "판매금액(총)"과 같은 기준). UNPAID_STATUS = frozenset({"Created", "PayRequest", "PayWaiting", "PayChecking", "PayFailed", "UnpaidCancelComplete"}) # 결제 뒤 취소·환불·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌 CLAIMED_STATUS = frozenset({ "PayCancelComplete", "RefundComplete", "ShippingCancelComplete", "ShippingRefundComplete", "ReturnCancelComplete", "ReturnRefundComplete", "TicketCancelComplete", "TicketRefundComplete", }) STATUS_KO = { "Created": "주문 생성", "PayRequest": "결제 요청", "PayWaiting": "결제 대기", "PayChecking": "입금 확인 중", "PayFailed": "결제 실패", "PayComplete": "결제 완료", "ShippingRequest": "배송 요청", "PayCancelRequest": "결제 취소 예정", "PayCancelComplete": "결제 취소 완료", "RefundComplete": "환불 완료", "UnpaidCancelComplete": "미입금 취소 완료", "ShippingWaiting": "배송 준비 중", "ShippingCancelComplete": "결제 취소 완료", "ShippingProgress": "배송 중", "ShippingComplete": "배송 완료", "ShippingRefundComplete": "환불 완료", "ExchangeShippingComplete": "교환 완료", "ReturnRequest": "반품 요청", "ReturnCancelComplete": "반품 결제 취소 완료", "ReturnRefundComplete": "반품 환불 완료", "TicketSendComplete": "발송 완료", "TicketCancelComplete": "결제 취소 완료", "TicketRefundComplete": "환불 완료", "BuyDecision": "구매 결정", } def _won(value: Any) -> int: try: return int(round(float(str(value if value is not None else 0).replace(",", "")))) except ValueError: return 0 def _day(value: Any) -> date | None: """"20251201201735" 또는 "2025-12-01 20:17:35" → date(2025, 12, 1). 카카오 날짜는 한국 시간.""" s = "".join(ch for ch in str(value or "") if ch.isdigit())[:8] if len(s) < 8: return None try: return date(int(s[:4]), int(s[4:6]), int(s[6:8])) except ValueError: return None def line_amount(op: dict[str, Any]) -> int: """상품 줄 금액 = (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오(관리자) 할인. 배송비 제외.""" qty = max(1, _won(op.get("quantity"))) gross = (_won(op.get("productPrice")) + _won(op.get("optionPrice"))) * qty return max(0, gross - line_discount(op)) def line_discount(op: dict[str, Any]) -> int: return sum(abs(_won(op.get(k))) for k in ("sellerDiscountPrice", "sellerCouponDiscountPrice", "adminDiscountPrice")) # 구매자 개인정보 — 받자마자 값을 지운다(메모리 캐시·원본 확인 표 어디에도 남기지 않음, 항목 이름만 남김). PERSONAL_OBJECTS = ("orderer", "orderDeliveryRequest", "orderTicketReceiver") PERSONAL_KEY = re.compile(r"^(pickup|exchange)(Name|ZipCode|RoadZipCode|Address\d*|MobileNumber|PhoneNumber)$|reasonComment") def strip_personal(det: dict[str, Any]) -> dict[str, Any]: out: dict[str, Any] = {} for k, v in det.items(): if k in PERSONAL_OBJECTS and isinstance(v, dict): out[k] = {kk: "" for kk in v} elif isinstance(v, dict): out[k] = {kk: ("" if PERSONAL_KEY.search(str(kk)) else vv) for kk, vv in v.items()} else: out[k] = v return out def order_detail(body: Any) -> dict[str, Any]: """주문정보 조회 응답에서 주문 하나(orderBase·orderProduct …)를 꺼낸다(개인정보 값은 지움). 감싼 모양(data/content)도 받아들인다.""" if not isinstance(body, dict): return {} if isinstance(body.get("orderProduct"), dict) or isinstance(body.get("orderBase"), dict): return strip_personal(body) for k in ("data", "content", "contents"): v = body.get(k) if isinstance(v, list) and v and isinstance(v[0], dict): v = v[0] if isinstance(v, dict) and (isinstance(v.get("orderProduct"), dict) or isinstance(v.get("orderBase"), dict)): return strip_personal(v) return {} def group_payments(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]: """주문(상품 줄) → 결제 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함). items = {"row": 목록 줄, "detail": 주문정보}. 배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다.""" pays: dict[str, dict[str, Any]] = {} for it in items: row, det = it.get("row") or {}, it.get("detail") or {} base, op = det.get("orderBase") or {}, det.get("orderProduct") or {} status = str(row.get("orderStatus") or base.get("status") or "") day = _day(row.get("paidAt") or base.get("paidAt")) oid = str(row.get("orderId") or base.get("id") or det.get("id") or "") pid = str(row.get("paymentId") or base.get("paymentId") or oid) if not oid or day is None or not (start <= day <= end) or status in UNPAID_STATUS or not op: continue p = pays.setdefault(pid, {"paymentId": pid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0, "discount": 0, "names": [], "opt": "", "statuses": [], "orders": [], "order_day": _day(row.get("createdAt") or base.get("createdAt"))}) amt = line_amount(op) p["amount"] += amt if status in CLAIMED_STATUS: p["claimed"] += amt p["ship"] += _won(op.get("deliveryAmount")) + _won(op.get("areaAdditionalDeliveryAmount")) p["qty"] += max(1, _won(op.get("quantity"))) p["discount"] += line_discount(op) p["orders"].append(oid) name = str(op.get("name") or "") if name and name not in p["names"]: p["names"].append(name) p["opt"] = p["opt"] or str(op.get("optionContent") or "") if status and status not in p["statuses"]: p["statuses"].append(status) return pays def _err_text(body: dict[str, Any], res: Any) -> str: parts = [str(body.get(k)) for k in ("code", "msg", "message") if body.get(k) not in (None, "")] ex = body.get("extras") if isinstance(ex, dict): parts += [str(ex.get(k)) for k in ("error_code", "error_message") if ex.get(k) not in (None, "")] return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음" class KakaoAdapter(MarketplaceAdapter): code = "kakao" name = "카카오" auth_type = "api_key" implemented = True replace_range = True event_prefix = EVENT_PREFIX docs_url = "https://shopping-developers.kakao.com/hc/ko/articles/4578909656975" note = ("카카오쇼핑 Open API 는 카카오쇼핑 검토로 허락된 카카오디벨로퍼스 앱만 쓸 수 있습니다. " "그 앱의 어드민 키와, 판매자센터(정보관리 → 판매채널 정보 → API 인증키)의 판매자 API 인증키를 입력합니다. " "두 키는 서로 다른 앱의 키여야 합니다.") def __init__(self) -> None: self._last_call = 0.0 self._details: dict[str, tuple[str, dict[str, Any]]] = {} # orderId → (modifiedAt, 주문정보) def credential_fields(self) -> list[CredentialField]: # api_key 는 처음 만든 입력칸 이름 그대로 — 이미 저장한 판매자 인증키를 다시 넣지 않아도 되게. return [ CredentialField("admin_key", "앱 어드민 키(Authorization)", secret=True, help="카카오디벨로퍼스 → 내 애플리케이션(카카오쇼핑 API 허락된 앱) → 앱 설정 → 앱 → 어드민 키"), CredentialField("api_key", "판매자 API 인증키(Target-Authorization)", secret=True, help="카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키"), CredentialField("channel_ids", "판매채널(channel-ids)", required=False, placeholder=DEFAULT_CHANNELS, help="톡스토어 101(기본), 선물하기 1, 둘 다 1,101"), ] # ── 호출 ────────────────────────────────────────────── def _headers(self, ctx: AdapterContext) -> dict[str, str]: admin = ctx.credentials.get("admin_key").strip() seller = ctx.credentials.get("api_key").strip() if not admin or not seller: raise NotConfigured("앱 어드민 키와 판매자 API 인증키를 입력하세요.") channels = re.sub(r"\s+", "", ctx.credentials.get("channel_ids") or "") or DEFAULT_CHANNELS return {"Authorization": f"KakaoAK {admin}", "Target-Authorization": f"KakaoAK {seller}", "channel-ids": channels, "Accept": "application/json"} def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]: """GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시. 키 오류는 AuthFailed(무엇을 확인할지 안내).""" import httpx # 지연 import headers = self._headers(ctx) for attempt in range(RETRY_429 + 1): ctx.progress.check() # [업데이트 취소]면 여기서 멈춤 wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call) if wait > 0: time.sleep(wait) try: res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec) except httpx.HTTPError as exc: raise ApiError(f"카카오쇼핑 API 연결 실패: {type(exc).__name__}") from None finally: self._last_call = time.monotonic() if res.status_code == 429 and attempt < RETRY_429: time.sleep(1.0 * (2 ** attempt)) continue try: body = res.json() except ValueError: body = {} if not isinstance(body, dict): body = {"contents": body} code = _won(body.get("code")) if body.get("code") not in (None, "") else 0 text = _err_text(body, res) if code == -2 or "target-authorization" in text.lower(): raise AuthFailed(f"카카오 인증 헤더 거부({text}). 앱 어드민 키와 판매자 API 인증키가 서로 다른 앱의 키인지, " "어드민 키가 REST API 키가 아닌지 확인하세요.") if code == -401 or "deactivated" in text: raise AuthFailed(f"카카오 판매자 API 인증키 무효({text}). 판매자센터의 API 인증키를 다시 복사해 넣으세요.") if "매핑" in text or "대행사" in text: raise AuthFailed(f"카카오쇼핑 연동 앱과 판매자가 연결되지 않았습니다({text}). 판매자 연결(POST /v1/store/register)이 " "끝났는지, 앱이 카카오쇼핑 API 허락을 받았는지 확인하세요.") if res.status_code in (401, 403): raise AuthFailed(f"카카오 권한 거부({res.status_code}): {text}. 앱이 카카오쇼핑 API 허락을 받았는지, " "두 키가 맞는지 확인하세요.") if res.status_code >= 400 or code < 0: raise ApiError(f"카카오쇼핑 API 오류({res.status_code}): {text}") return body raise ApiError("카카오쇼핑 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.") def _day_rows(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]: """결제일이 d(한국 시간 0시~23:59:59)인 주문 목록 — 모든 상태, 금액 없음.""" params: dict[str, Any] = {"from": f"{d.isoformat()} 00:00:00", "to": f"{d.isoformat()} 23:59:59", "size": PAGE_SIZE} out: list[dict[str, Any]] = [] token = "" seen: set[str] = set() for _ in range(MAX_PAGES): body = self._get(ctx, PAID_PATH, {**params, **({"token": token} if token else {})}) rows = [r for r in body.get("contents") or [] if isinstance(r, dict)] out.extend(rows) token = str(body.get("token") or "") if not token or not rows: break if token in seen: # 커서 반복 — 끝까지 받았는지 알 수 없다(검토 F05) raise ApiError(f"카카오 {d.isoformat()} 주문 목록의 다음 쪽 표시가 반복됩니다 — 저장하지 않았습니다.") seen.add(token) else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 raise ApiError(f"카카오 {d.isoformat()} 주문이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.") return out def _detail(self, ctx: AdapterContext, row: dict[str, Any]) -> dict[str, Any]: oid = str(row.get("orderId") or "") mod = str(row.get("modifiedAt") or "") hit = self._details.get(oid) if hit and hit[0] == mod and mod: return hit[1] det = order_detail(self._get(ctx, ORDER_PATH, {"order_id": oid})) if det: if len(self._details) >= CACHE_MAX: self._details.clear() self._details[oid] = (mod, det) return det def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]: """하루씩 목록 → 결제된 주문만 주문정보까지 받아 {"row", "detail"}.""" ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계 d = start while d <= end: rows = self._day_rows(ctx, d) got = [] for r in rows: if not r.get("orderId") or str(r.get("orderStatus") or "") in UNPAID_STATUS: got.append({"row": r, "detail": {}}) continue got.append({"row": r, "detail": self._detail(ctx, r)}) ctx.progress.step(items=len(rows)) yield from got d += timedelta(days=1) # ── 수집 ────────────────────────────────────────────── def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]: yield from group_payments(self._items(ctx, start, end), start, end).values() def normalize_order(self, p: dict[str, Any]) -> list[SaleEvent]: pid, day = str(p.get("paymentId") or ""), p.get("_day") if not pid or day is None: return [] names = p.get("names") or [] name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else "" statuses = [STATUS_KO.get(s, s) for s in p.get("statuses") or []] orders = p.get("orders") or [] return [SaleEvent( event_type="SALE", external_event_id=f"{EVENT_PREFIX}{pid}", external_order_id=pid, external_line_id=",".join(orders)[:100], order_date=p.get("order_day"), payment_date=day, event_date=day, amount=max(0, int(p.get("amount") or 0)), product_name=name[:200], option_name=str(p.get("opt") or "")[:200], quantity=int(p.get("qty") or 0), discount_amount=max(0, int(p.get("discount") or 0)), order_status="/".join(statuses)[:50], )] def test_connection(self, ctx: AdapterContext) -> str: from app.timezone import today_kst # noqa: WPS433 self.authenticate(ctx) rows = self._day_rows(ctx, today_kst()) return f"카카오쇼핑 API 연결 정상(결제일 기준 주문 조회 확인, 오늘 결제 주문 {len(rows)}건)." # ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ───────── def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]: """결제일 기준 기간(최대 31일)의 주문과 주문정보를 실제로 불러 항목별 합계·상태별 합계·날짜별 현재 규칙 매출을 돌려준다(저장 안 함). 판매자센터 매출 화면과 어느 항목이 맞는지 실데이터로 확정하는 용도. 개인정보는 이름만.""" self.authenticate(ctx) to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1)) try: items = list(self._items(ctx, day, to)) except AdapterError as exc: return {"date": day.isoformat(), "to": to.isoformat(), "probes": [ {"key": "paid", "label": "결제일 기준 주문", "path": PAID_PATH, "ok": False, "error": exc.message[:300]}]} flat = [{**flatten(it["row"], "list"), **flatten(it["detail"])} for it in items] probes = [{"key": "paid", "label": "결제일 기준 주문 + 주문정보(전체 상태)", "path": f"{PAID_PATH} → {ORDER_PATH}", "ok": True, "count": len(items), "fields": field_summary(flat)}] by_status: dict[str, list[dict[str, str]]] = {} for it, f in zip(items, flat): by_status.setdefault(str(it["row"].get("orderStatus") or "?"), []).append(f) for st, rows in sorted(by_status.items()): probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})" + (" — 매출 제외(미결제)" if st in UNPAID_STATUS else " — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "orderStatus", "ok": True, "count": len(rows), "fields": [f for f in field_summary(rows) if f["sum"] is not None and f["name"].startswith("orderProduct.")]}) pays = group_payments(items, day, to) days = [] d = day while d <= to: day_pays = [p for p in pays.values() if p["_day"] == d] days.append({"date": d.isoformat(), "orders": len(day_pays), "amount": sum(p["amount"] for p in day_pays), "claimed": sum(p["claimed"] for p in day_pays), "ship": sum(p["ship"] for p in day_pays)}) d += timedelta(days=1) return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days, "rule": "결제일 기준 주문의 (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오 할인 합(배송비 제외, " "결제 뒤 취소·반품분 포함, 미결제 제외). 판매자센터 매출과 대조 전 — 표의 항목 합계로 확인"}