From dd6a849fbd4af1fbe7265c18d7b78f53051e3868 Mon Sep 17 00:00:00 2001 From: king Date: Wed, 30 Sep 2026 00:14:06 +0900 Subject: [PATCH] =?UTF-8?q?feat(performance):=20=EC=BF=A0=ED=8C=A1=20?= =?UTF-8?q?=EC=97=B0=EA=B2=B0=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20=E2=80=94=20?= =?UTF-8?q?HMAC(CEA)=20=EC=84=9C=EB=AA=85=EC=9C=BC=EB=A1=9C=20=EB=B0=9C?= =?UTF-8?q?=EC=A3=BC=EC=84=9C=20=EC=8B=A4=EC=A0=9C=20=EC=A1=B0=ED=9A=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 쿠팡 OPEN API 키를 입력했지만 연결 테스트가 "다음 단계에서 구현"만 돌려줘 키가 이 서버에서 통하는지 알 수 없었다. 키는 판매자당 1개이고 사방넷용 (연동업체 선택)으로 발급한 키는 이 서버 IP 에서 막힐 수 있어 먼저 확인이 필요. - CEA HMAC-SHA256 서명(signed-date + METHOD + path + query, 공식 예제 방식), 쿠팡 예시와 같은 쿼리 인코딩(+ → %2B, : 유지) - test_connection: 오늘 결제완료 발주서(v5 ordersheets) 1건 조회 - 401/403 → 인증 실패 + "연동업체 키면 자체개발로 바꾸고 이 서버 IP 허용" 안내 - 매출 수집은 아직 — 맞출 WING 화면을 정한 뒤 구현(주석에 API 조사 결과) - 테스트: 서명 형식·쿼리 인코딩·403 메시지·비밀값 미노출 Co-Authored-By: Claude Opus 5.5 --- app/modules/performance/adapters/coupang.py | 92 ++++++++++++++++++- .../performance/tests/test_performance.py | 49 ++++++++++ 2 files changed, 139 insertions(+), 2 deletions(-) diff --git a/app/modules/performance/adapters/coupang.py b/app/modules/performance/adapters/coupang.py index b6725e2..825b39d 100644 --- a/app/modules/performance/adapters/coupang.py +++ b/app/modules/performance/adapters/coupang.py @@ -1,12 +1,57 @@ """쿠팡 — 쿠팡 윙(마켓플레이스) Open API. 인증: Vendor ID + Access Key + Secret Key 로 요청마다 HMAC 서명(CEA 헤더). + signed-date = UTC "yyMMddTHHmmssZ", message = signed-date + METHOD + path + query(물음표 없이, 보내는 그대로) + Authorization: CEA algorithm=HmacSHA256, access-key=…, signed-date=…, signature=hex(HMAC-SHA256(secret, message)) + (공식 문서 developers.coupangcorp.com → 시작하기 → HMAC Signature 생성 / Python Example, 2026-09-30 확인) + +OPEN API 키는 판매자당 1개(유효기간 180일). 발급 방식이 둘 — + · 연동업체 선택(사방넷 등 1곳만): 그 업체 서버에서 쓰는 키. 우리 서버에서 부르면 막힐 수 있다. + · 자체개발: 업체명·URL·허용 IP(최대 10개). 우리 서버 IP 를 넣어야 한다. +연결 테스트는 오늘 결제완료 발주서 1건을 실제로 조회해 키·IP 가 통하는지 확인한다. + +매출 수집(fetch_orders)은 아직 — 어느 WING 화면과 맞출지 정한 뒤 구현한다. + · 발주서 목록(v5 ordersheets, 주문일 기준, 상태별 조회) + 반품/취소 요청(v6 returnRequests, 접수일 기준, 금액 없음) + · 매출내역(v1 revenue-history)은 매출인식일(구매확정 또는 배송완료+7일) 기준이라 결제일 기준 일별 매출과 다르다. 로켓(공급) 매출은 기존 쿠팡 밀크런 모듈의 cupang_sales 에 있다 — 필요 시 별도 연계. """ from __future__ import annotations -from .base import CredentialField, MarketplaceAdapter +import hashlib +import hmac +import time +from typing import Any +from urllib.parse import quote, urlencode + +from .base import ( + AdapterContext, + ApiError, + AuthFailed, + CredentialField, + MarketplaceAdapter, + NotConfigured, +) + +HOST = "https://api-gateway.coupang.com" + + +def signed_date(now: float | None = None) -> str: + return time.strftime("%y%m%dT%H%M%SZ", time.gmtime(now)) + + +def authorization(method: str, path: str, query: str, access_key: str, secret_key: str, + *, now: float | None = None) -> str: + """쿠팡 CEA HMAC 헤더. query 는 실제로 보내는 문자열 그대로(물음표 제외).""" + dt = signed_date(now) + sig = hmac.new(secret_key.encode("utf-8"), f"{dt}{method}{path}{query}".encode("utf-8"), + hashlib.sha256).hexdigest() + return f"CEA algorithm=HmacSHA256, access-key={access_key}, signed-date={dt}, signature={sig}" + + +def build_query(params: dict[str, Any]) -> str: + """쿠팡 예시와 같은 인코딩 — '+' 는 %2B, ':' 는 그대로(2026-09-30%2B09:00).""" + return urlencode({k: v for k, v in params.items() if v is not None}, quote_via=quote, safe=":") class CoupangAdapter(MarketplaceAdapter): @@ -14,7 +59,9 @@ class CoupangAdapter(MarketplaceAdapter): name = "쿠팡" auth_type = "api_key" docs_url = "https://developers.coupangcorp.com/" - note = "쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다." + note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, " + "'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 " + "이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).") def credential_fields(self) -> list[CredentialField]: return [ @@ -22,3 +69,44 @@ class CoupangAdapter(MarketplaceAdapter): CredentialField("access_key", "Access Key", secret=True), CredentialField("secret_key", "Secret Key", secret=True), ] + + # ── 호출 ────────────────────────────────────────────── + def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]: + import httpx # 지연 import + + access, secret = ctx.credentials.get("access_key").strip(), ctx.credentials.get("secret_key").strip() + if not (access and secret): + raise NotConfigured("쿠팡 Vendor ID·Access Key·Secret Key 를 모두 입력하세요.") + query = build_query(params) + headers = {"Authorization": authorization("GET", path, query, access, secret), + "Content-Type": "application/json;charset=UTF-8"} + try: + res = httpx.get(f"{HOST}{path}?{query}", headers=headers, timeout=ctx.timeout_sec) + except httpx.HTTPError as exc: + raise ApiError(f"쿠팡 API 연결 실패: {type(exc).__name__}") from None + try: + body = res.json() + except ValueError: + body = {} + msg = str(body.get("message") or body.get("error") or res.text[:200] or "").strip() + if res.status_code in (401, 403): + raise AuthFailed( + f"쿠팡 인증 거부({res.status_code}): {msg}. Vendor ID·키가 맞는지 확인하세요. 키를 '연동업체(사방넷 등)'로 " + "발급했다면 이 서버에서 쓸 수 없을 수 있습니다 — WING 에서 '자체개발'로 바꾸고 이 서버 IP 를 허용 IP 에 " + "넣어야 합니다(사방넷 IP 도 함께 넣어야 사방넷이 계속 동작).") + if res.status_code >= 400: + raise ApiError(f"쿠팡 API 오류({res.status_code}): {msg}") + return body + + def test_connection(self, ctx: AdapterContext) -> str: + from app.timezone import today_kst # noqa: WPS433 + + self.authenticate(ctx) + vendor = ctx.credentials.get("vendor_id").strip() + today = today_kst().isoformat() + body = self._get(ctx, f"/v2/providers/openapi/apis/api/v5/vendors/{vendor}/ordersheets", + {"createdAtFrom": f"{today}+09:00", "createdAtTo": f"{today}+09:00", + "status": "ACCEPT", "maxPerPage": 1}) + n = len(body.get("data") or []) + return (f"쿠팡 연결 정상(발주서 조회 권한 확인, 오늘 결제완료 {'있음' if n else '없음'}). " + "매출 수집은 다음 단계에서 구현됩니다.") diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py index 1116f9d..fce4c7c 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -754,6 +754,55 @@ def test_cafe24_market_map_empty_by_default(): assert target_code("shopn") == target_code("coupang", "coupang") == target_code("NCHECKOUT") == "cafe24" +def test_coupang_hmac_and_connection_errors(): + """쿠팡 CEA HMAC 서명(공식 예제 방식) + 연결 테스트 오류 구분. 비밀값은 메시지에 없다.""" + import hashlib + import hmac as _hmac + + import httpx + + from app.modules.performance.adapters import coupang as cp + from app.modules.performance.adapters.base import AdapterContext + + q = cp.build_query({"createdAtFrom": "2026-09-30+09:00", "status": "ACCEPT", "maxPerPage": 1}) + assert q == "createdAtFrom=2026-09-30%2B09:00&status=ACCEPT&maxPerPage=1" + now = 1_790_000_000 # 2026-09-21 14:13:20 UTC + h = cp.authorization("GET", "/p", q, "AK", "SK", now=now) + dt = "260921T141320Z" + sig = _hmac.new(b"SK", f"{dt}GET/p{q}".encode(), hashlib.sha256).hexdigest() + assert h == f"CEA algorithm=HmacSHA256, access-key=AK, signed-date={dt}, signature={sig}" + + class Creds(dict): + def get(self, k, default=""): + return dict.get(self, k, default) + + def has(self, k): + return bool(dict.get(self, k)) + + ctx = AdapterContext(code="coupang", credentials=Creds(vendor_id="A00012345", access_key="AK-1", secret_key="SK-SECRET")) + seen = {} + + def fake_get(url, headers=None, timeout=None, status=200, body=None): + seen["url"], seen["auth"] = url, headers["Authorization"] + return httpx.Response(status, json=body if body is not None else {"code": 200, "data": []}) + + orig = httpx.get + try: + httpx.get = fake_get + msg = cp.CoupangAdapter().test_connection(ctx) + assert "연결 정상" in msg and "/vendors/A00012345/ordersheets?createdAtFrom=" in seen["url"] + assert "%2B09:00" in seen["url"] and "SK-SECRET" not in seen["auth"] + httpx.get = lambda url, headers=None, timeout=None: fake_get(url, headers, timeout, 403, {"message": "Access Denied"}) + try: + cp.CoupangAdapter().test_connection(ctx) + except AuthFailed as exc: + assert "403" in exc.message and "자체개발" in exc.message and "SK-SECRET" not in exc.message + else: + raise AssertionError("403 이면 인증 실패여야 합니다") + finally: + httpx.get = orig + + def test_registry_and_event_validation(): codes = [a.code for a in all_adapters()] assert len(codes) == len(set(codes)) == 10