"""네이버 스마트스토어 — 네이버 커머스API. 인증(공식 방식): 애플리케이션 ID + 시크릿으로 전자서명 → OAuth2 client_credentials 토큰. client_secret_sign = base64( bcrypt.hashpw("{client_id}_{timestamp(ms)}", client_secret) ) POST https://api.commerce.naver.com/external/v1/oauth2/token (client_id, timestamp, client_secret_sign, grant_type=client_credentials, type=SELF | SELLER+account_id) 토큰은 약 3시간 — 암호화 저장(access_token·access_token_expires_at)해 두고 만료 5분 전에 새로 받는다. 커머스API센터 애플리케이션에 **API 호출 IP(이 서버 외부 IP)** 를 등록해야 호출된다. 매출 수집 — 스마트스토어센터 **판매분석 "판매금액(총)"** 과 같은 기준(2026-09-30 사용자 확인: 9/1 매출 4,455,600원. 판매금액은 할인(판매자·네이버 부담) 뒤 금액, 배송비 332,486원은 별도, 환불 346,340원은 환불일에 따로 빠져 판매금액(순)): - 조건형 상품 주문 상세 조회 GET /v1/pay-order/seller/product-orders ?from=…&to=…&rangeType=PAYED_DATETIME&pageSize=&page= — 결제일 기준, 한 번에 24시간까지(하루씩 부른다), from 부터 180일 안의 주문만. 응답에 주문·상품주문 상세가 바로 들어 있다(네이버 안내: 소량·조회용 권장 API). - SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(order.paymentDate). 금액 = 상품주문들의 결제금액(productOrder.totalPaymentAmount) 합 — 배송비 제외. - 결제 뒤 취소·반품된 상품주문도 결제일 매출에 그대로 둔다(판매금액(총)). 입금대기·미입금 취소만 뺀다. 그래서 지난 날짜 매출이 나중에 줄지 않는다. 환불(판매금액(순))은 아직 따로 만들지 않는다. - 구매자 이름·연락처·주소는 저장하지 않는다. """ from __future__ import annotations import base64 import re import time from datetime import date, datetime, timedelta from typing import Any, Iterable from .base import ( credential_fingerprint, AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, MarketplaceAdapter, NotConfigured, SaleEvent, TokenExpired, ) HOST = "https://api.commerce.naver.com/external" TOKEN_PATH = "/v1/oauth2/token" ORDERS_PATH = "/v1/pay-order/seller/product-orders" EVENT_PREFIX = "naver:" PAGE_SIZE = 100 MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지 TOKEN_MARGIN_SEC = 300 # 만료 5분 전이면 새로 받는다 CALL_INTERVAL_SEC = 0.35 # 초당 호출 제한(넘으면 429) — 호출 사이 간격 RETRY_429 = 3 PROBE_MAX_DAYS = 31 # 매출에서 빼는 상품주문 상태 — 결제되지 않은 것만(입금대기·미입금 취소). 결제 뒤 취소·반품된 것은 판매분석 # "판매금액(총)"처럼 결제일 매출에 그대로 둔다(환불은 판매분석에서도 환불일에 따로 빠진다). EXCLUDED_STATUS = frozenset({"PAYMENT_WAITING", "CANCELED_BY_NOPAYMENT"}) CLAIMED_STATUS = frozenset({"CANCELED", "RETURNED"}) # 결제 뒤 취소·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌 STATUS_KO = { "PAYMENT_WAITING": "입금대기", "PAYED": "결제완료", "DELIVERING": "배송중", "DELIVERED": "배송완료", "PURCHASE_DECIDED": "구매확정", "EXCHANGED": "교환", "CANCELED": "취소", "RETURNED": "반품", "CANCELED_BY_NOPAYMENT": "미입금취소", } # 원본 데이터 확인 — 개인정보로 보이는 항목은 값 없이 이름만. 금액·상태·날짜·상품명 등은 보인다. PERSONAL = re.compile(r"orderer|receiver|shippingAddress|takingAddress|returnAddress|pickupAddress|collectAddress|" r"name$|tel|phone|address|zip|mail|memo|customsClearance|buyer|recipient", re.IGNORECASE) SAFE = re.compile(r"(productName|productOption|optionCode|productClass|productId|deliveryCompany|reason|Status|Type|" r"Date|Amount|Price|Fee|Quantity|Count|Id)$") NUMBER = re.compile(r"^-?\d+(\.\d+)?$") 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: """"2026-09-29T10:11:12.0+09:00" → date(2026, 9, 29). 네이버 날짜는 한국 시간(+09:00)으로 온다.""" s = str(value or "") m = re.match(r"(\d{4})-(\d{2})-(\d{2})", s) if not m: return None try: return date(int(m.group(1)), int(m.group(2)), int(m.group(3))) except ValueError: return None def sign(client_id: str, client_secret: str, timestamp_ms: int) -> str: """커머스API 전자서명 — bcrypt(비밀번호 = "{client_id}_{timestamp}", 솔트 = 애플리케이션 시크릿) 을 base64.""" import bcrypt # 지연 import try: hashed = bcrypt.hashpw(f"{client_id}_{timestamp_ms}".encode("utf-8"), client_secret.encode("utf-8")) except ValueError: raise AuthFailed("애플리케이션 시크릿 형식이 올바르지 않습니다. 커머스API센터의 시크릿을 그대로 붙여 넣으세요.") from None return base64.standard_b64encode(hashed).decode("ascii") def product_order_items(body: Any) -> list[dict[str, Any]]: """조건형 조회 응답에서 상품주문 하나씩 {"order": {...}, "productOrder": {...}, ...} 로 꺼낸다. 응답 모양(data.contents[].content / data 목록 / 바로 목록)이 달라도 받아들인다.""" data = body.get("data", body) if isinstance(body, dict) else body if isinstance(data, dict): data = data.get("contents") or data.get("productOrders") or data.get("items") or [] out = [] for it in data if isinstance(data, list) else []: if not isinstance(it, dict): continue c = it.get("content") if isinstance(it.get("content"), dict) else it if isinstance(c.get("productOrder"), dict): out.append(c) return out def has_next(body: Any, page: int, got: int) -> bool: data = body.get("data") if isinstance(body, dict) else None pg = data.get("pagination") if isinstance(data, dict) else None if isinstance(pg, dict): if "hasNext" in pg: return bool(pg["hasNext"]) total = pg.get("totalPages") or pg.get("totalPage") if total: return page < int(total) return got >= PAGE_SIZE def flatten(obj: Any, prefix: str = "") -> dict[str, str]: """중첩 사전 → {"productOrder.totalPaymentAmount": "12000", …}. 목록은 건너뛴다(개수만).""" out: dict[str, str] = {} if isinstance(obj, dict): for k, v in obj.items(): key = f"{prefix}.{k}" if prefix else str(k) if isinstance(v, dict): out.update(flatten(v, key)) elif isinstance(v, list): out[key + "[]"] = str(len(v)) elif v is not None: out[key] = str(v) return out def is_personal(key: str) -> bool: last = key.rsplit(".", 1)[-1] if "Address." in key or key.split(".")[0] in ("orderer",): return True return bool(PERSONAL.search(key)) and not SAFE.search(last) def field_summary(records: list[dict[str, str]]) -> list[dict[str, Any]]: """항목별: 채워진 줄 수, 숫자면 합계, 개인정보 아니면 예시 값 하나.""" names: dict[str, dict[str, Any]] = {} for r in records: for k, v in r.items(): f = names.setdefault(k, {"name": k, "filled": 0, "numeric": True, "sum": 0.0, "sample": "", "personal": is_personal(k)}) if v == "": continue f["filled"] += 1 if NUMBER.match(v) and f["numeric"]: f["sum"] += float(v) else: f["numeric"] = False if not f["sample"] and not f["personal"]: f["sample"] = v[:40] for f in names.values(): f["sum"] = int(round(f["sum"])) if f["numeric"] and f["filled"] else None return sorted(names.values(), key=lambda f: f["name"]) def group_orders(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]: """상품주문 → 주문 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함). 금액 = totalPaymentAmount 합(할인 뒤 상품 결제금액, 배송비 제외) = 판매분석 "판매금액(총)". 배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다.""" orders: dict[str, dict[str, Any]] = {} for c in items: po, od = c.get("productOrder") or {}, c.get("order") or {} oid = str(od.get("orderId") or po.get("orderId") or "") day = _day(od.get("paymentDate") or po.get("paymentDate")) status = str(po.get("productOrderStatus") or "") if not oid or day is None or not (start <= day <= end) or status in EXCLUDED_STATUS: continue o = orders.setdefault(oid, {"orderId": oid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0, "discount": 0, "names": [], "opt": "", "statuses": [], "order_day": _day(od.get("orderDate"))}) paid = _won(po.get("totalPaymentAmount")) o["amount"] += paid if status in CLAIMED_STATUS: o["claimed"] += paid o["ship"] += _won(po.get("deliveryFeeAmount")) - _won(po.get("deliveryDiscountAmount")) o["qty"] += _won(po.get("quantity")) o["discount"] += _won(po.get("productDiscountAmount")) name = str(po.get("productName") or "") if name and name not in o["names"]: o["names"].append(name) o["opt"] = o["opt"] or str(po.get("productOption") or "") if status and status not in o["statuses"]: o["statuses"].append(status) return orders # 토큰을 발급한 인증정보 — 이 값들이 바뀌면 저장된 토큰을 쓰지 않고 새로 받는다(credential_fingerprint) TOKEN_KEYS = ("client_id", "client_secret", "account_id") class NaverAdapter(MarketplaceAdapter): code = "naver" name = "네이버" auth_type = "oauth" implemented = True replace_range = True event_prefix = EVENT_PREFIX docs_url = "https://apicenter.commerce.naver.com/" note = ("커머스API센터에서 발급한 애플리케이션 ID/시크릿을 입력합니다. 애플리케이션의 API 호출 IP 에 " "이 서버의 외부 IP 를 등록해야 호출됩니다.") def __init__(self) -> None: self._last_call = 0.0 def credential_fields(self) -> list[CredentialField]: return [ CredentialField("client_id", "애플리케이션 ID(Client ID)"), CredentialField("client_secret", "애플리케이션 시크릿(Client Secret)", secret=True), CredentialField("account_id", "판매자 ID", required=False, help="솔루션(SELLER) 방식으로 발급한 경우에만 입력 — 내 스토어 전용 애플리케이션은 비워 둡니다"), CredentialField("access_token", "Access Token", secret=True, required=False, internal=True), CredentialField("access_token_expires_at", "Access Token 만료", required=False, internal=True), # 토큰을 발급한 인증정보 지문(원문 아님) — 계정·키를 바꾸면 이전 토큰을 쓰지 않는다(2026-10-15 검토 F04) CredentialField("access_token_for", "Access Token 발급 기준", required=False, internal=True), ] # ── 인증 ────────────────────────────────────────────── def _token(self, ctx: AdapterContext, *, force: bool = False) -> str: """저장된 토큰이 5분 넘게 남았으면 그대로, 아니면 새로 받아 암호화 저장.""" if not force: tok = ctx.credentials.get("access_token") try: exp = float(ctx.credentials.get("access_token_expires_at") or 0) except ValueError: exp = 0.0 same_account = ctx.credentials.get("access_token_for") == credential_fingerprint(ctx.credentials, TOKEN_KEYS) if tok and same_account and exp - time.time() > TOKEN_MARGIN_SEC: return tok return self._issue_token(ctx) def _issue_token(self, ctx: AdapterContext) -> str: import httpx # 지연 import client_id = ctx.credentials.get("client_id").strip() client_secret = ctx.credentials.get("client_secret").strip() if not client_id or not client_secret: raise NotConfigured("애플리케이션 ID와 시크릿을 입력하세요.") ts = int(time.time() * 1000) form = {"client_id": client_id, "timestamp": str(ts), "grant_type": "client_credentials", "client_secret_sign": sign(client_id, client_secret, ts), "type": "SELF"} account_id = ctx.credentials.get("account_id").strip() if account_id: form.update(type="SELLER", account_id=account_id) try: res = httpx.post(f"{HOST}{TOKEN_PATH}", data=form, timeout=ctx.timeout_sec, headers={"Accept": "application/json"}) except httpx.HTTPError as exc: raise ApiError(f"네이버 커머스API 연결 실패: {type(exc).__name__}") from None body = self._json(res) if res.status_code >= 400 or not body.get("access_token"): msg = self._err_text(body, res) if res.status_code in (400, 401, 403): raise AuthFailed(f"네이버 토큰 발급 실패({res.status_code}): {msg}. 애플리케이션 ID·시크릿과 " "API 호출 IP(이 서버 외부 IP) 등록을 확인하세요.") raise ApiError(f"네이버 토큰 발급 오류({res.status_code}): {msg}") tok = str(body["access_token"]) expires_in = _won(body.get("expires_in")) or 3 * 3600 ctx.credentials.set("access_token", tok) ctx.credentials.set("access_token_expires_at", str(int(time.time()) + expires_in)) ctx.credentials.set("access_token_for", credential_fingerprint(ctx.credentials, TOKEN_KEYS)) return tok def authenticate(self, ctx: AdapterContext) -> None: super().authenticate(ctx) self._token(ctx) def refresh_token(self, ctx: AdapterContext) -> None: self._token(ctx, force=True) # ── 호출 ────────────────────────────────────────────── @staticmethod def _json(res: Any) -> dict[str, Any]: try: body = res.json() except ValueError: return {} return body if isinstance(body, dict) else {"data": body} @staticmethod def _err_text(body: dict[str, Any], res: Any) -> str: parts = [str(body.get(k)) for k in ("code", "message", "error", "error_description") if body.get(k)] inv = body.get("invalidInputs") if isinstance(inv, list) and inv: parts.append("; ".join(str(i.get("message") or i) if isinstance(i, dict) else str(i) for i in inv[:3])) return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음" def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]: """GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시, 401 이면 토큰을 새로 받아 한 번 더.""" import httpx # 지연 import retried_auth = False 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) headers = {"Authorization": f"Bearer {self._token(ctx)}", "Accept": "application/json"} 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 if res.status_code == 401 and not retried_auth: retried_auth = True self._token(ctx, force=True) continue body = self._json(res) if res.status_code == 401: raise TokenExpired(f"네이버 인증 만료·거부(401): {self._err_text(body, res)}") if res.status_code == 403: raise AuthFailed(f"네이버 권한 거부(403): {self._err_text(body, res)}. 애플리케이션의 API 권한(주문)과 " "API 호출 IP 등록을 확인하세요.") if res.status_code >= 400: raise ApiError(f"네이버 API 오류({res.status_code}): {self._err_text(body, res)}") return body raise ApiError("네이버 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.") def _day_items(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]: """결제일이 d(한국 시간 0시~23:59:59.999)인 상품주문 전체 — 모든 상태.""" params: dict[str, Any] = { "from": f"{d.isoformat()}T00:00:00.000+09:00", "to": f"{d.isoformat()}T23:59:59.999+09:00", "rangeType": "PAYED_DATETIME", "pageSize": PAGE_SIZE, } out: list[dict[str, Any]] = [] for page in range(1, MAX_PAGES + 1): body = self._get(ctx, ORDERS_PATH, {**params, "page": page}) items = product_order_items(body) out.extend(items) if not items or not has_next(body, page, len(items)): break else: # 쪽 수 상한을 다 썼는데 아직 다음 쪽이 있음 — 일부만 받은 채 저장하지 않게(검토 F05) raise ApiError(f"네이버 {d.isoformat()} 주문이 {MAX_PAGES}쪽을 넘어 끝까지 받지 못했습니다 — 저장하지 않았습니다.") return out def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]: ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계 d = start while d <= end: rows = self._day_items(ctx, d) ctx.progress.step(items=len(rows)) yield from rows d += timedelta(days=1) # ── 수집 ────────────────────────────────────────────── def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]: yield from group_orders(self._items(ctx, start, end), start, end).values() def normalize_order(self, o: dict[str, Any]) -> list[SaleEvent]: oid, day = str(o.get("orderId") or ""), o.get("_day") if not oid or day is None: return [] names = o.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 o.get("statuses") or []] return [SaleEvent( event_type="SALE", external_event_id=f"{EVENT_PREFIX}{oid}", external_order_id=oid, order_date=o.get("order_day"), payment_date=day, event_date=day, amount=max(0, int(o.get("amount") or 0)), product_name=name[:200], option_name=str(o.get("opt") or "")[:200], quantity=int(o.get("qty") or 0), discount_amount=max(0, int(o.get("discount") or 0)), order_status="/".join(statuses)[:50], )] def test_connection(self, ctx: AdapterContext) -> str: from app.timezone import today_kst # noqa: WPS433 # 입력한 새 값으로 시험할 수 있으니 저장된 토큰을 쓰지 않고 항상 새로 받는다. super().authenticate(ctx) self._token(ctx, force=True) items = self._day_items(ctx, today_kst()) return f"네이버 커머스API 연결 정상(토큰 발급·주문 조회 확인, 오늘 결제 상품주문 {len(items)}건)." # ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ───────── 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": "payed", "label": "결제일 기준 상품주문", "path": ORDERS_PATH, "ok": False, "error": exc.message[:300]}]} by_status: dict[str, list[dict[str, Any]]] = {} for c in items: by_status.setdefault(str((c.get("productOrder") or {}).get("productOrderStatus") or "?"), []).append(c) probes = [{"key": "payed", "label": "결제일 기준 상품주문(전체 상태)", "path": ORDERS_PATH + " (PAYED_DATETIME)", "ok": True, "count": len(items), "fields": field_summary([flatten(c) for c in items])}] 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 EXCLUDED_STATUS else " — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "productOrderStatus", "ok": True, "count": len(rows), "fields": [f for f in field_summary([flatten(c) for c in rows]) if f["sum"] is not None and f["name"].startswith("productOrder.")]}) days = [] orders = group_orders(items, day, to) d = day while d <= to: day_orders = [o for o in orders.values() if o["_day"] == d] days.append({"date": d.isoformat(), "orders": len(day_orders), "amount": sum(o["amount"] for o in day_orders), "claimed": sum(o["claimed"] for o in day_orders), "ship": sum(o["ship"] for o in day_orders)}) d += timedelta(days=1) return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days, "rule": "결제일 기준 상품주문 totalPaymentAmount 합(할인 뒤, 배송비 제외, 결제 뒤 취소·반품분 포함, " "미입금 제외) = 판매분석 '판매금액(총)'. 취소·반품분·배송비는 참고"}