feat(performance): 11번가 연결 테스트 — openapikey 로 결제완료 주문 실제 조회

11번가 셀러 API 키 입력·IP 등록을 마쳤는데 연결 테스트가 "다음 단계에서
구현"만 돌려줘 이 서버에서 통하는지 알 수 없었다.

- test_connection: GET /rest/ordservices/complete/{오늘0000}/{오늘2359},
  헤더 openapikey (공식 이용방법 문서). 셀러 API 는 등록 IP 에서만 호출됨
- XML 응답(euc-kr 선언) 직접 디코딩 후 파싱, result_code 오류·401/403 구분,
  연결 실패 시 등록 IP 확인 안내
- 기존 테스트가 실제 11번가를 부르지 않게 httpx 대체 + 11번가 테스트 추가
- 매출 수집은 아직(맞출 셀러오피스 화면 정한 뒤)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-30 00:31:57 +09:00
parent dd6a849fbd
commit c93ab2fbd8
2 changed files with 128 additions and 4 deletions
+75 -3
View File
@@ -1,11 +1,54 @@
"""11번가 — 11번가 셀러 오픈API.
인증: 셀러오피스에서 발급한 Open API Key 를 요청 헤더(openapikey)에 넣는다.
인증: 셀러오피스(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
from .base import CredentialField, MarketplaceAdapter
import re
import xml.etree.ElementTree as ET
from typing import Any
from .base import AdapterContext, 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]:
"""(결과코드, 결과문구, 주문 수). 네임스페이스와 무관하게 태그 끝 이름으로 찾는다."""
try:
root = ET.fromstring(_xml_text(content))
except ET.ParseError:
return "", "", 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
class ElevenstAdapter(MarketplaceAdapter):
@@ -13,9 +56,38 @@ class ElevenstAdapter(MarketplaceAdapter):
name = "11번가"
auth_type = "api_key"
docs_url = "https://openapi.11st.co.kr/"
note = "11번가 셀러오피스 → 오픈API 에서 발급한 키를 입력합니다."
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 and code not in ("0", "200", "00"):
raise ApiError(f"11번가 API 오류(코드 {code}): {detail}")
return res.content
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}건). "
"매출 수집은 다음 단계에서 구현됩니다.")