Merge branch 'feat/performance' into feat/project — 네이버 스마트스토어 매출 수집

This commit is contained in:
2026-09-30 13:34:03 +09:00
7 changed files with 611 additions and 18 deletions
+379 -5
View File
@@ -1,27 +1,401 @@
"""네이버 스마트스토어 — 네이버 커머스API.
인증: 애플리케이션 ID + 시크릿으로 전자서명(bcrypt) → OAuth2 client_credentials 토큰.
토큰은 발급받아 암호화 저장하고 만료 시 재발급한다(다음 단계에서 구현).
인증(공식 방식): 애플리케이션 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)** 를 등록해야 호출된다.
매출 수집(1차 규칙 — 설정 화면 "원본 데이터 확인"으로 스마트스토어센터 화면과 맞춰 확정한다):
- 조건형 상품 주문 상세 조회 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) 합 + 배송비(deliveryFeeAmount − 배송비 할인, 주문에서 한 번).
- 취소·반품 완료(CANCELED·RETURNED)·미입금 취소(CANCELED_BY_NOPAYMENT) 상품주문은 뺀다. 기간을 통째로 다시 받아
(replace_range) 나중에 취소된 주문이 매출에서 빠진다(취소 사건을 따로 만들지 않음 — 11번가와 같은 방식).
- 구매자 이름·연락처·주소는 저장하지 않는다.
"""
from __future__ import annotations
from .base import CredentialField, MarketplaceAdapter
import base64
import re
import time
from datetime import date, datetime, timedelta
from typing import Any, Iterable
from .base import (
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({"CANCELED", "RETURNED", "CANCELED_BY_NOPAYMENT"})
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] 이고 취소·반품 완료가 아닌 것만)."""
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, "qty": 0, "discount": 0,
"names": [], "opt": "", "statuses": [], "order_day": _day(od.get("orderDate"))})
o["amount"] += _won(po.get("totalPaymentAmount"))
o["ship"] = max(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)
for o in orders.values():
o["amount"] += max(0, o.pop("ship"))
return orders
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/시크릿을 입력합니다."
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="판매자 계정 지정이 필요한 경우에만 입력"),
help="솔루션(SELLER) 방식으로 발급한 경우에만 입력 — 내 스토어 전용 애플리케이션은 비워 둡니다"),
CredentialField("access_token", "Access Token", secret=True, required=False, internal=True),
CredentialField("access_token_expires_at", "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
if tok 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))
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):
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
return out
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
d = start
while d <= end:
yield from self._day_items(ctx, d)
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 ""), "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)})
d += timedelta(days=1)
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"rule": "주문별 totalPaymentAmount 합 + 배송비(deliveryFeeAmount − deliveryDiscountAmount, 한 번), "
"취소·반품 완료·미입금 취소 제외"}
@@ -239,4 +239,4 @@
} | tojson }}</script>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930v" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930w" defer></script>{% endblock %}
@@ -117,16 +117,21 @@
</div>
<div class="erp-card perf-card perf-card-wide">
<div class="perf-card-head"><h2 class="perf-h">11번가 원본 데이터 확인</h2></div>
<p class="perf-muted">11번가 셀러 API 의 주문·클레임·정산 조회 주소를 기간(최대 31일)으로 실제 불러, 어느 주소가 동작하는지와
받은 항목·금액 합계를 보여 줍니다(저장하지 않음). 주문 목록은 지금 그 상태인 주문만, 정산은 정산일 기준일 수 있어
매출이 있던 날부터 넉넉히(예: 3주) 잡아 주세요. 셀러오피스에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로
매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.</p>
<div class="perf-card-head"><h2 class="perf-h">쇼핑몰 원본 데이터 확인</h2></div>
<p class="perf-muted">쇼핑몰 API 를 기간(최대 31일)으로 실제 불러, 받은 항목·금액 합계를 보여 줍니다(저장하지 않음).
쇼핑몰 관리자 화면에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 매출 수집을 맞춥니다.
이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.<br>
· <b>네이버</b>: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.<br>
· <b>11번가</b>: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).</p>
<div class="perf-sample-form">
<select class="erp-input" id="perf-probe-code" aria-label="쇼핑몰">
<option value="naver">네이버 스마트스토어</option>
<option value="elevenst">11번가</option>
</select>
<input class="erp-input perf-date" type="date" id="perf-probe-date" value="{{ default_sample_to }}" />
<span class="perf-muted">~</span>
<input class="erp-input perf-date" type="date" id="perf-probe-to" value="{{ default_sample_to }}" />
<button type="button" class="erp-btn erp-btn-outline" id="perf-probe" data-code="elevenst">불러오기</button>
<button type="button" class="erp-btn erp-btn-outline" id="perf-probe">불러오기</button>
</div>
<div id="perf-probe-result"></div>
</div>
@@ -170,4 +175,4 @@
</section>
{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930v" defer></script>{% endblock %}
{% block scripts %}<script src="/static/performance.js?v=20260930w" defer></script>{% endblock %}
@@ -966,6 +966,185 @@ def test_registry_and_event_validation():
raise AssertionError(f"검증 실패해야 함: {bad.event_type} {bad.amount}")
def _naver_item(order_id, po_id, pay_day, amount, *, status="PAYED", ship=0, ship_dc=0, qty=1, dc=0, name="밀폐용기"):
"""조건형 상품 주문 조회 응답의 contents[] 한 줄(개인정보 항목 포함 — 저장 안 되는지 확인용)."""
return {"productOrderId": po_id, "content": {
"order": {"orderId": order_id, "paymentDate": f"{pay_day}T10:11:12.0+09:00", "orderDate": f"{pay_day}T10:10:00.0+09:00",
"ordererName": "홍길동", "ordererTel": "010-1234-5678", "ordererId": "hong***"},
"productOrder": {"productOrderId": po_id, "productOrderStatus": status, "productName": name, "productOption": "3개입",
"quantity": qty, "totalPaymentAmount": amount, "productDiscountAmount": dc,
"deliveryFeeAmount": ship, "deliveryDiscountAmount": ship_dc,
"shippingAddress": {"name": "홍길동", "tel1": "010-1234-5678", "baseAddress": "서울시 어딘가"}},
}}
def test_naver_sign_token_and_connection():
"""네이버: bcrypt 전자서명 → 토큰(form) → Bearer 로 조건형 주문 조회. 시크릿·토큰은 오류 문구에 없음."""
import base64
import bcrypt
import httpx
from app.modules.performance.adapters import naver as nv
from app.modules.performance.adapters.base import AdapterContext
secret = bcrypt.gensalt(rounds=4).decode()
sig = nv.sign("my-app-id", secret, 1727600000000)
assert bcrypt.checkpw(b"my-app-id_1727600000000", base64.b64decode(sig))
try:
nv.sign("my-app-id", "not-a-bcrypt-salt", 1)
except AuthFailed as exc:
assert "not-a-bcrypt-salt" not in exc.message
else:
raise AssertionError("시크릿 형식 오류여야 합니다")
class Creds(dict):
def get(self, k, default=""):
return dict.get(self, k, default)
def has(self, k):
return bool(dict.get(self, k))
def set(self, k, v):
self[k] = v
ctx = AdapterContext(code="naver", credentials=Creds(client_id="my-app-id", client_secret=secret))
seen = {"gets": []}
def post(url, data=None, timeout=None, headers=None):
seen["post"] = (url, dict(data))
return httpx.Response(200, json={"access_token": "TOKEN-XYZ", "expires_in": 10799, "token_type": "Bearer"})
def get(url, params=None, headers=None, timeout=None):
seen["gets"].append((url, dict(params), headers["Authorization"]))
return httpx.Response(200, json={"data": {"contents": [_naver_item("O1", "P1", "2026-09-30", 12000)],
"pagination": {"page": 1, "size": 100, "hasNext": False}}})
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC)
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = post, get, 0
try:
msg = nv.NaverAdapter().test_connection(ctx)
assert "연결 정상" in msg and "1건" in msg
url, form = seen["post"]
assert url.endswith("/external/v1/oauth2/token") and form["type"] == "SELF" and form["grant_type"] == "client_credentials"
assert bcrypt.checkpw(f"my-app-id_{form['timestamp']}".encode(), base64.b64decode(form["client_secret_sign"]))
gurl, params, auth = seen["gets"][0]
assert gurl.endswith("/v1/pay-order/seller/product-orders") and auth == "Bearer TOKEN-XYZ"
assert params["rangeType"] == "PAYED_DATETIME" and params["from"].endswith("T00:00:00.000+09:00")
assert params["to"].endswith("T23:59:59.999+09:00") and params["from"][:10] == params["to"][:10]
assert ctx.credentials["access_token"] == "TOKEN-XYZ" and int(ctx.credentials["access_token_expires_at"]) > 0
# 토큰 발급 거부 → 인증 실패(시크릿·서명은 문구에 없음)
httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response(
400, json={"code": "BadRequest", "message": "client_secret_sign 이 올바르지 않습니다"})
try:
nv.NaverAdapter().test_connection(ctx)
except AuthFailed as exc:
assert secret not in exc.message and "올바르지 않습니다" in exc.message
else:
raise AssertionError("인증 실패여야 합니다")
# 주문 조회 403(IP 미등록 등) → 인증 실패 안내
httpx.post = post
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
403, json={"code": "GW.IP_NOT_ALLOWED", "message": "허용되지 않은 IP"})
try:
nv.NaverAdapter().test_connection(ctx)
except AuthFailed as exc:
assert "허용되지 않은 IP" in exc.message and "TOKEN-XYZ" not in exc.message
else:
raise AssertionError("권한 거부여야 합니다")
finally:
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = orig
def test_naver_collect_sales():
"""네이버 매출 = 주문 단위, 결제일 기준. 상품주문 결제금액 합 + 배송비(주문에서 한 번, 배송비 할인 뺌).
취소·반품 완료·미입금 취소 상품주문은 뺀다. 페이지를 넘겨 받고, 구매자 정보는 저장하지 않는다."""
import bcrypt
import httpx
from app.modules.performance.adapters import naver as nv
pages = {
("2026-09-09", 1): ([_naver_item("A", "A1", "2026-09-09", 20000, ship=3000, qty=2, dc=1000),
_naver_item("A", "A2", "2026-09-09", 5000, ship=3000, name="뚜껑")], True),
("2026-09-09", 2): ([_naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED")], False),
("2026-09-10", 1): ([_naver_item("C", "C1", "2026-09-10", 15000, ship=3000, ship_dc=3000, status="PURCHASE_DECIDED"),
_naver_item("C", "C2", "2026-09-10", 7000, status="RETURNED"),
_naver_item("D", "D1", "2026-09-10", 4000, status="CANCELED_BY_NOPAYMENT")], False),
}
calls = []
def get(url, params=None, headers=None, timeout=None):
key = (params["from"][:10], params["page"])
calls.append(key)
rows, more = pages.get(key, ([], False))
return httpx.Response(200, json={"data": {"contents": rows, "pagination": {"page": params["page"], "hasNext": more}}})
def post(url, data=None, timeout=None, headers=None):
return httpx.Response(200, json={"access_token": "TOKEN-N", "expires_in": 10799})
st = FakeStore()
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "naver"),
{"client_id": "app-id", "client_secret": bcrypt.gensalt(rounds=4).decode()})
orig = (httpx.post, httpx.get, nv.CALL_INTERVAL_SEC)
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = post, get, 0
try:
r = SyncService(st, creds).sync_marketplace("naver", date(2026, 9, 9), date(2026, 9, 10))
finally:
httpx.post, httpx.get, nv.CALL_INTERVAL_SEC = orig
assert r["ok"], r
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "naver"}
assert set(ev_) == {"naver:A", "naver:C"} # B 취소·D 미입금취소 제외
assert ev_["naver:A"]["amount"] == 20000 + 5000 + 3000 # 배송비는 주문에서 한 번
assert ev_["naver:A"]["quantity"] == 3 and ev_["naver:A"]["discount_amount"] == 1000
assert ev_["naver:A"]["sales_date"] == date(2026, 9, 9) and ev_["naver:A"]["product_name"] == "밀폐용기 외 1건"
assert ev_["naver:C"]["amount"] == 15000 # 반품 줄 제외, 무료배송(할인) 0
assert ev_["naver:C"]["order_status"] == "구매확정"
assert ("2026-09-09", 2) in calls and ("2026-09-10", 2) not in calls # hasNext 일 때만 다음 쪽
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
def test_naver_reconcile_hides_personal():
import httpx
from app.modules.performance.adapters import naver as nv
from app.modules.performance.adapters.base import AdapterContext
class Creds(dict):
def get(self, k, default=""):
return dict.get(self, k, default)
def has(self, k):
return bool(dict.get(self, k))
def set(self, k, v):
self[k] = v
import time as _t
ctx = AdapterContext(code="naver", credentials=Creds(client_id="x", client_secret="y", access_token="T",
access_token_expires_at=str(int(_t.time()) + 9999)))
rows = [_naver_item("A", "A1", "2026-09-09", 20000, ship=3000), _naver_item("B", "B1", "2026-09-09", 9900, status="CANCELED")]
orig = (httpx.get, nv.CALL_INTERVAL_SEC)
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
200, json={"data": {"contents": rows if params["from"].startswith("2026-09-09") else []}})
nv.CALL_INTERVAL_SEC = 0
try:
rec = nv.NaverAdapter().reconcile(ctx, date(2026, 9, 9), to=date(2026, 9, 10))
finally:
httpx.get, nv.CALL_INTERVAL_SEC = orig
allp = rec["probes"][0]
assert allp["ok"] and allp["count"] == 2
f = {x["name"]: x for x in allp["fields"]}
assert f["productOrder.totalPaymentAmount"]["sum"] == 29900
assert f["order.ordererName"]["personal"] and f["order.ordererName"]["sample"] == ""
assert f["productOrder.shippingAddress.baseAddress"]["personal"]
assert not f["productOrder.productName"]["personal"] and f["productOrder.productName"]["sample"] == "밀폐용기"
assert "홍길동" not in repr(rec) and "010-1234-5678" not in repr(rec)
assert rec["days"] == [{"date": "2026-09-09", "orders": 1, "amount": 23000}, {"date": "2026-09-10", "orders": 0, "amount": 0}]
assert any("매출 제외" in p["label"] for p in rec["probes"])
if __name__ == "__main__":
os.environ.pop("APP_ENCRYPTION_KEY", None)
n = 0
+17 -4
View File
@@ -826,17 +826,20 @@
}
});
// ── 11번가 원본 데이터 확인 — 후보 조회 주소별 동작 여부·항목 합계 ──
// ── 쇼핑몰 원본 데이터 확인(네이버·11번가) — 조회 주소별 동작 여부·항목 합계, 네이버는 날짜별 현재 규칙 매출 ──
const probe = document.getElementById("perf-probe");
if (probe) probe.addEventListener("click", async function () {
const day = document.getElementById("perf-probe-date").value;
const out = document.getElementById("perf-probe-result");
if (!day) return;
probe.disabled = true;
out.innerHTML = '<p class="perf-muted">11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)</p>';
const codeSel = document.getElementById("perf-probe-code");
const code = codeSel ? codeSel.value : "elevenst";
out.innerHTML = '<p class="perf-muted">' + (code === "naver" ? "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)"
: "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)") + "</p>";
try {
const to = document.getElementById("perf-probe-to").value || day;
const r = await api("GET", "/performance/api/marketplaces/" + probe.dataset.code + "/reconcile?date=" + encodeURIComponent(day) +
const r = await api("GET", "/performance/api/marketplaces/" + code + "/reconcile?date=" + encodeURIComponent(day) +
"&to=" + encodeURIComponent(to));
if (!r.ok) { out.innerHTML = '<p class="perf-notice is-warn">' + esc((r.label ? r.label + " — " : "") + r.message) + "</p>"; return; }
const summary = '<table class="perf-table" style="margin-top:8px"><thead><tr><th class="perf-th-label">조회</th>' +
@@ -855,7 +858,17 @@
(f.sum == null ? "" : fmt(f.sum)) + "</td><td>" + (f.personal ? '<span class="perf-muted">개인정보(숨김)</span>' : esc(f.sample)) + "</td></tr>";
}).join("") + "</tbody></table>";
}).join("");
out.innerHTML = summary + (details || '<p class="perf-muted" style="margin-top:8px">그날 조회된 주문이 없습니다. 셀러오피스에서 매출이 있던 날로 다시 해 보세요.</p>');
// 날짜별 현재 규칙 매출(네이버) — 쇼핑몰 관리자 화면 매출과 나란히 비교
const days = (r.days || []).length ? '<h4 class="perf-h" style="margin:14px 0 6px">날짜별 현재 규칙 매출</h4>' +
(r.rule ? '<p class="perf-muted">규칙: ' + esc(r.rule) + "</p>" : "") +
'<table class="perf-table"><thead><tr><th class="perf-th-label">결제일</th><th>주문 수</th><th>매출</th></tr></thead><tbody>' +
r.days.map(function (d) {
return '<tr><td class="perf-td-label">' + esc(d.date) + '</td><td class="perf-num">' + fmt(d.orders) +
'</td><td class="perf-num">' + fmt(d.amount) + "</td></tr>";
}).join("") + '<tr><td class="perf-td-label"><b>합계</b></td><td class="perf-num"><b>' +
fmt(r.days.reduce(function (a, d) { return a + d.orders; }, 0)) + '</b></td><td class="perf-num"><b>' +
fmt(r.days.reduce(function (a, d) { return a + d.amount; }, 0)) + "</b></td></tr></tbody></table>" : "";
out.innerHTML = summary + days + (details || '<p class="perf-muted" style="margin-top:8px">그 기간에 조회된 주문이 없습니다. 쇼핑몰 관리자 화면에서 매출이 있던 날로 다시 해 보세요.</p>');
} catch (err) {
out.innerHTML = '<p class="perf-notice is-warn">' + esc(err.message) + "</p>";
} finally { probe.disabled = false; }
+21 -1
View File
@@ -29,7 +29,7 @@
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
**연동 현황**: 카페24 = **구현됨**, 나머지 9개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
**연동 현황**: 카페24·11번가·네이버 스마트스토어 = **구현됨**(네이버는 1차 규칙, 실데이터 대조 전), 나머지 7개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
**연동 단계에서 공식 API 문서로 확정**한다.
### 카페24 (`adapters/cafe24.py`, 구현됨)
@@ -102,6 +102,26 @@
- `replace_range` — 기간을 통째로 다시 받아 취소·반품된 주문이 매출에서 빠진다(취소 사건을 따로 만들지 않음 → 지난 날짜
금액이 나중에 줄 수 있음). 구매자 이름·아이디·연락처는 저장하지 않는다.
### 네이버 스마트스토어 (`adapters/naver.py`, 구현됨 — 1차 규칙)
- 인증: 커머스API센터 애플리케이션 ID·시크릿 → 전자서명 `client_secret_sign = base64(bcrypt.hashpw("{client_id}_{timestamp ms}",
client_secret))` → `POST https://api.commerce.naver.com/external/v1/oauth2/token`(form: client_id·timestamp·client_secret_sign·
grant_type=client_credentials·type=SELF, 판매자 ID 입력 시 type=SELLER+account_id). 토큰(약 3시간)은 `access_token`·
`access_token_expires_at`(internal, 암호화)으로 저장해 만료 5분 전까지 재사용, 401 이면 한 번 새로 받아 다시 호출.
[연결 테스트]는 입력값으로 시험하므로 항상 새 토큰. **애플리케이션의 API 호출 IP 에 운영 서버 외부 IP 등록 필요.**
의존성 `bcrypt`(requirements.txt).
- 수집: 조건형 상품 주문 상세 조회 `GET /v1/pay-order/seller/product-orders?from=&to=&rangeType=PAYED_DATETIME&pageSize=100&page=`
— 한 번에 **24시간까지**(하루씩 0시~23:59:59.999 +09:00), from 부터 180일 안 주문만(네이버 안내, GitHub discussions #1875·#2380).
응답 모양은 `data.contents[].content.{order, productOrder, …}` 로 보고 목록·`content` 유무가 달라도 받는다(`product_order_items`),
다음 쪽은 `pagination.hasNext`(없으면 100건 꽉 차면). 호출 간격 0.35초, 429 는 1·2·4초 쉬고 다시.
- **1차 매출 규칙**: SALE = 주문 하나(`naver:{orderId}`), 날짜 = 결제일(`order.paymentDate`). 금액 = 상품주문
`totalPaymentAmount` 합 + 배송비(`deliveryFeeAmount − deliveryDiscountAmount`, 주문에서 최댓값 한 번). 할인 = `productDiscountAmount` 합.
취소·반품 완료(`CANCELED`·`RETURNED`)·미입금 취소(`CANCELED_BY_NOPAYMENT`) 상품주문은 뺀다. `replace_range` — 기간을 다시 받으면
나중에 취소된 주문이 빠진다(11번가와 같은 방식).
- **확정 전 할 일**: 설정 화면 **"쇼핑몰 원본 데이터 확인"**(네이버 선택) — 결제일 기준 상품주문 전체의 항목별 합계,
상태별 합계, 날짜별 "현재 규칙 매출"을 스마트스토어센터 화면 매출과 비교해 금액 항목(결제금액 vs 상품금액, 네이버 부담 할인,
배송비 묶음 기준)을 확정한다. 개인정보(주문자·수령인·주소·연락처·메모)는 값 없이 이름만.
### 연동 단계 체크리스트(쇼핑몰마다)
- 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인
+2
View File
@@ -12,6 +12,8 @@ pdfplumber>=0.11
pillow>=10.0
# 카페24 OAuth 토큰 암호화 저장(Fernet) — app/integrations/cafe24/crypto.py
cryptography>=42.0
# 네이버 커머스API 토큰 전자서명(client_secret_sign) — app/modules/performance/adapters/naver.py
bcrypt>=4.1
google-api-python-client>=2.100
google-auth>=2.30
# refresh token 발급 스크립트(scripts/google_sheets_authorize.py) 전용