Files
dbx-main/app/modules/performance/adapters/coupang.py
T
king dd6a849fbd feat(performance): 쿠팡 연결 테스트 — HMAC(CEA) 서명으로 발주서 실제 조회
쿠팡 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 <noreply@anthropic.com>
2026-09-30 00:14:06 +09:00

113 lines
5.9 KiB
Python

"""쿠팡 — 쿠팡 윙(마켓플레이스) 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
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):
code = "coupang"
name = "쿠팡"
auth_type = "api_key"
docs_url = "https://developers.coupangcorp.com/"
note = ("쿠팡 윙 → 판매자정보 → 추가판매정보 → OPEN API 키 발급에서 확인합니다. 키는 판매자당 1개이며, "
"'연동업체(사방넷 등)'로 발급한 키는 이 서버에서 막힐 수 있습니다 — 그때는 '자체개발'로 바꾸고 "
"이 서버 IP 를 허용 IP 에 넣어야 합니다(연결 테스트로 확인).")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("vendor_id", "Vendor ID(업체코드)", placeholder="A00012345"),
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 '없음'}). "
"매출 수집은 다음 단계에서 구현됩니다.")