Files
dbx-main/app/modules/performance/adapters/elevenst.py
T
king 7d96f2e738 fix(performance): 11번가 원본 데이터 확인 — "해당 건 없음"은 0건, 기간 조회·구매확정 후보
9/9 확인 결과: 취소·반품 주소는 코드 -1 "해당 건이 없습니다"(= 0건)인데 실패로
표시했고, 주문 목록 4개는 지금 그 상태인 주문만 주는 듯해 이미 구매확정된
9/9 주문이 어디에도 없었다. 정산 내역은 정산확정일 기준일 가능성이 있다.

- 결과 문구가 "해당 건이 없습니다" 류면 오류가 아니라 0건
- 기간 조회(최대 31일, 7일씩 나눠 호출) — 매출일부터 정산확정일까지 넓게 확인
- 구매확정 목록 후보 주소 추가
- 테스트 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 01:14:32 +09:00

190 lines
9.8 KiB
Python

"""11번가 — 11번가 셀러 오픈API.
인증: 셀러오피스(openapi.11st.co.kr → 서비스등록·확인)에서 발급한 Open API Key 를 요청 헤더 `openapikey` 에 넣는다.
셀러 API 는 등록한 IP 에서만 호출된다("Seller API 정보 수정"에서 서버 IP 등록, 셀링툴(사방넷 등)과 함께 쓸 수 있음).
(공식 이용방법 openapi.11st.co.kr → OpenApiOperationGuide SERVICE_METHOD, 2026-09-30 확인)
연결 테스트는 결제완료(발주확인할) 주문 목록을 오늘 하루로 조회한다 — GET /rest/ordservices/complete/{시작}/{끝}
(yyyyMMddHHmm). 엔드포인트 상세 문서는 로그인 뒤에만 보여 널리 쓰이는 경로를 쓰고, 실제 호출 결과로 확인한다.
응답은 XML. 매출 수집(fetch_orders)은 맞출 셀러오피스 화면을 정한 뒤 구현한다.
"""
from __future__ import annotations
import re
import xml.etree.ElementTree as ET
from datetime import date, timedelta
from typing import Any
from .base import AdapterContext, AdapterError, ApiError, AuthFailed, CredentialField, MarketplaceAdapter
HOST = "https://api.11st.co.kr"
def _xml_text(content: bytes) -> str:
"""11번가 XML 은 euc-kr 선언이 많다 — 파이썬 XML 파서가 다바이트 인코딩 선언을 못 읽어 직접 풀고 선언을 뗀다."""
head = content[:200].decode("ascii", "ignore")
m = re.search(r"encoding=[\"']([\w-]+)", head)
enc = (m.group(1) if m else "utf-8").lower()
try:
text = content.decode("cp949" if enc in ("euc-kr", "euckr", "ks_c_5601-1987") else enc)
except (LookupError, UnicodeDecodeError):
text = content.decode("utf-8", "replace")
return re.sub(r"^\s*<\?xml[^>]*\?>", "", text)
def xml_result(content: bytes) -> tuple[str, str, int]:
"""(결과코드, 결과문구, 주문 수). 네임스페이스와 무관하게 태그 끝 이름으로 찾는다. XML 이 아니면 코드 "not-xml"."""
try:
root = ET.fromstring(_xml_text(content))
except ET.ParseError:
return "not-xml", "", 0
if root.tag.rsplit("}", 1)[-1].lower() == "html": # 오류 안내 웹페이지(IP 차단 등)
return "not-xml", "", 0
code = text = ""
orders = 0
for el in root.iter():
tag = el.tag.rsplit("}", 1)[-1].lower()
if tag in ("result_code", "resultcode") and not code:
code = (el.text or "").strip()
elif tag in ("result_text", "resulttext", "result_message", "message") and not text:
text = (el.text or "").strip()
elif tag == "order":
orders += 1
return code, text, orders
# 원본 데이터 확인용 후보 주소 — {s}/{e} = yyyyMMddHHmm, {d} = yyyyMMdd. 문서 미확인 경로가 섞여 있어
# 404 등 실패도 그대로 보여 준다(어느 주소가 살아 있는지 확인하는 것이 목적).
PROBE_PATHS: tuple[tuple[str, str, str], ...] = (
("complete", "결제완료(발주확인 전)", "/rest/ordservices/complete/{s}/{e}"),
("packaging", "발송처리 대상(발주확인 후)", "/rest/ordservices/packaging/{s}/{e}"),
("shipping", "배송중", "/rest/ordservices/shipping/{s}/{e}"),
("completed", "배송완료", "/rest/ordservices/completed/{s}/{e}"),
("cancelorders", "취소신청", "/rest/claimservice/cancelorders/{s}/{e}"),
("canceledorders", "취소완료", "/rest/claimservice/canceledorders/{s}/{e}"),
("returnorders", "반품신청", "/rest/claimservice/returnorders/{s}/{e}"),
("returnedorders", "반품완료", "/rest/claimservice/returnedorders/{s}/{e}"),
("purchaseconfirm", "구매확정(후보)", "/rest/ordservices/purchaseconfirm/{s}/{e}"),
("settlement", "정산 내역", "/rest/settlement/settlementList/{ds}/{de}"),
)
NO_DATA = re.compile(r"해당\s*건이\s*없|조회된?\s*(내역|건|데이터)이?\s*없") # 코드 -1 이어도 "0건"
PROBE_CHUNK_DAYS = 7
PROBE_MAX_DAYS = 31
# 개인정보로 보이는 항목 — 값은 보이지 않고 이름만(이름·연락처·주소·우편번호·아이디·메일·메모)
PERSONAL = re.compile(r"(nm|name|tel|tlphn|phone|hp|addr|zip|mail|id|memo|msg|pcc|clearance|birth)$|rcvr|ordnm|buyer",
re.IGNORECASE)
NUMBER = re.compile(r"^-?\d+(\.\d+)?$")
SAFE = re.compile(r"^(prd|opt|slct|dlvEtprs|dlvMthd|clm|reason|stl|sel)", re.IGNORECASE) # 상품·옵션·클레임 사유 등은 보임
def xml_records(content: bytes) -> list[dict[str, str]]:
"""응답에서 주문(또는 클레임·정산) 한 줄씩 — 자식이 모두 글자 항목인 요소를 한 줄로 본다(태그 끝 이름 → 값)."""
try:
root = ET.fromstring(_xml_text(content))
except ET.ParseError:
return []
out: list[dict[str, str]] = []
for el in root.iter():
kids = list(el)
if len(kids) >= 3 and all(len(k) == 0 for k in kids):
out.append({k.tag.rsplit("}", 1)[-1]: (k.text or "").strip() for k in kids})
return out
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": bool(PERSONAL.search(k)) and not SAFE.match(k)})
if not 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 list(names.values())
class ElevenstAdapter(MarketplaceAdapter):
code = "elevenst"
name = "11번가"
auth_type = "api_key"
docs_url = "https://openapi.11st.co.kr/"
note = ("11번가 셀러오피스 → 오픈API 에서 발급한 키를 입력합니다. 셀러 API 는 등록한 IP 에서만 호출되므로 "
"'Seller API 정보 수정 → IP 직접 입력'에 이 서버의 외부 IP 를 넣어야 합니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("api_key", "Open API Key", secret=True),
]
def _get(self, ctx: AdapterContext, path: str) -> bytes:
import httpx # 지연 import
headers = {"openapikey": ctx.credentials.get("api_key").strip(), "Accept": "application/xml"}
try:
res = httpx.get(f"{HOST}{path}", headers=headers, timeout=ctx.timeout_sec)
except httpx.HTTPError as exc:
raise ApiError(f"11번가 API 연결 실패: {type(exc).__name__} — 등록한 IP 가 이 서버 IP 인지 확인하세요.") from None
code, text, _ = xml_result(res.content)
detail = text or res.text[:200].strip()
if res.status_code in (401, 403):
raise AuthFailed(f"11번가 인증 거부({res.status_code}): {detail}. 키와 등록 IP(이 서버 외부 IP)를 확인하세요.")
if res.status_code >= 400:
raise ApiError(f"11번가 API 오류({res.status_code}): {detail}")
if code == "not-xml":
raise ApiError(f"11번가가 예상하지 못한 응답을 돌려줬습니다(XML 아님): {res.text[:120].strip()}")
if code and code not in ("0", "200", "00") and not NO_DATA.search(text):
raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
return res.content
# ── 원본 데이터 확인(설정 화면 "11번가 원본 데이터 확인") ─────────
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
"""후보 조회 주소마다 기간(day~to, 최대 31일, 7일씩 나눠)을 실제로 불러 동작 여부·줄 수·항목별 합계를 돌려준다.
셀러 API 상세 문서가 로그인 뒤에만 있어, 어느 주소·항목이 셀러오피스 화면 매출과 맞는지 실데이터로 확정하는 용도.
개인정보 항목(이름·연락처·주소·아이디 등)은 값 없이 이름만."""
self.authenticate(ctx)
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
chunks = []
s = day
while s <= to:
e = min(to, s + timedelta(days=PROBE_CHUNK_DAYS - 1))
chunks.append((s, e))
s = e + timedelta(days=1)
out = []
for key, label, tmpl in PROBE_PATHS:
row: dict[str, Any] = {"key": key, "label": label, "path": tmpl.split("/{")[0] + "/…"}
records: list[dict[str, str]] = []
error = ""
for s, e in chunks:
ds, de = s.strftime("%Y%m%d"), e.strftime("%Y%m%d")
try:
records += xml_records(self._get(ctx, tmpl.format(s=f"{ds}0000", e=f"{de}2359", ds=ds, de=de)))
except AdapterError as exc:
error = exc.message[:200]
break
if error:
out.append({**row, "ok": False, "error": error})
else:
out.append({**row, "ok": True, "count": len(records), "fields": field_summary(records)})
return {"date": day.isoformat(), "to": to.isoformat(), "probes": out}
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
self.authenticate(ctx)
d = today_kst().strftime("%Y%m%d")
body = self._get(ctx, f"/rest/ordservices/complete/{d}0000/{d}2359")
_, _, orders = xml_result(body)
return (f"11번가 연결 정상(주문 조회 권한 확인, 오늘 결제완료 {orders}건). "
"매출 수집은 다음 단계에서 구현됩니다.")