Files
dbx-main/app/modules/performance/adapters/gsshop.py
T
king e56c5685ca feat(performance): GS샵 연결 테스트·원본 데이터 확인 — 제휴 API AES256 토큰
- 인증: 헤더 supCd + token = base64(AES256(yyyyMMddHHmmss + 협력사코드)), 암호화 모드는 문서에 없어
  CBC(IV=키 앞 16) → ECB → CBC(IV=0) 순서로 시도하고 통과한 모드 기억, HTTP 200 + result=fail 401 도 인증 실패로
- 운영 주소 withgs-api.gsshop.com, 매출 내역(매출인식일, 10일씩·쪽 넘김)·배송비 내역
- 설정 "쇼핑몰 원본 데이터 확인"에 GS샵 — 응답 항목 이름이 문서에 없어 실데이터로 매출 규칙 확정 예정
  (그 전까지 매출 수집은 연동 준비 중)
- 입력칸 라벨: 협력사코드(supCd)·AES256 암복호화 키(저장된 값 그대로 사용)
- 테스트 1개 추가(28개 통과), 문서 갱신

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

196 lines
10 KiB
Python

"""GS샵 — GSSHOP 제휴 API(협력사 API V3, partners.gsshop.com → 제휴 API → 개발가이드).
인증(개발가이드 2026-09-30 확인): 요청 헤더
supCd = 협력사코드
token = AES256( Sysdate("yyyyMMddHHmmss") + 협력사코드 ) 예: "20181017174913" + "1036018"
AES256 암복호화 키는 partners.gsshop.com/api/apiMain 에 로그인하면 보인다.
암호화 모드(CBC/ECB, IV)는 문서에 없다 → 흔한 순서(CBC·IV=키 앞 16바이트 → ECB → CBC·IV=0)로 시도하고
통과한 방식을 기억한다(TOKEN_MODES). 출력은 base64.
token 이 틀리면 HTTP 200 + {"result":"fail","message":"키 인증 중 오류…","code":"401 UNAUTHORIZED"}.
주소: 운영 https://withgs-api.gsshop.com (개발가이드의 예시 주소 atwithgs-api 는 테스트용 — 두 곳 모두 응답 확인).
매출(Settlement API 1.0): GET /api/v2/settlement/out/sales/period?supCode=&fromDate=&toDate=&pageIdx=&rowsPerPage=
— 매출인식일(YYYYMMDD) 기준, 한 번에 10일까지, 쪽당 최대 1만 건. 응답 {data:[…], hasMorePage, totalCount, …}.
배송비는 /api/v2/settlement/out/sales/shippingFee/period(같은 조건).
응답 줄의 항목 이름은 개발가이드 예시에 없어("property1") 설정 화면 "쇼핑몰 원본 데이터 확인"으로 실데이터를 보고
매출 규칙을 확정한다 — 그 전까지 매출 수집(fetch_orders)은 "연동 준비 중".
"""
from __future__ import annotations
import base64
from datetime import date, datetime, timedelta
from typing import Any, Iterable
from .base import (
AdapterContext,
AdapterError,
ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
NotConfigured,
)
from .elevenst import field_summary
HOST = "https://withgs-api.gsshop.com"
SALES_PATH = "/api/v2/settlement/out/sales/period"
SHIPPING_PATH = "/api/v2/settlement/out/sales/shippingFee/period"
DAILY_SALES_PATH = "/api/v2/settlement/out/sales"
CHUNK_DAYS = 10 # 기간 조회는 시작일부터 10일 이내
ROWS_PER_PAGE = 10000
MAX_PAGES = 50
PROBE_MAX_DAYS = 31
TOKEN_MODES = ("cbc-keyiv", "ecb", "cbc-zeroiv")
MODE_LABEL = {"cbc-keyiv": "AES/CBC(IV=키 앞 16바이트)", "ecb": "AES/ECB", "cbc-zeroiv": "AES/CBC(IV=0)"}
def make_token(aes_key: str, sup_cd: str, now: datetime, mode: str) -> str:
"""token = base64(AES(yyyyMMddHHmmss + 협력사코드)), PKCS7(=PKCS5) 패딩."""
from cryptography.hazmat.primitives import padding # 지연 import
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = aes_key.encode("utf-8")
if len(key) not in (16, 24, 32):
raise AuthFailed(f"AES 키 길이가 올바르지 않습니다({len(key)}바이트 — 16·24·32 중 하나여야 함). "
"제휴 API 메인 화면의 키를 그대로 붙여 넣으세요.")
plain = (now.strftime("%Y%m%d%H%M%S") + sup_cd).encode("utf-8")
padder = padding.PKCS7(128).padder()
data = padder.update(plain) + padder.finalize()
if mode == "ecb":
cipher = Cipher(algorithms.AES(key), modes.ECB())
elif mode == "cbc-zeroiv":
cipher = Cipher(algorithms.AES(key), modes.CBC(b"\0" * 16))
else:
cipher = Cipher(algorithms.AES(key), modes.CBC(key[:16]))
enc = cipher.encryptor()
return base64.b64encode(enc.update(data) + enc.finalize()).decode("ascii")
def _rows(body: dict[str, Any]) -> list[dict[str, Any]]:
data = body.get("data")
return [r for r in data if isinstance(r, dict)] if isinstance(data, list) else []
def _strs(row: dict[str, Any]) -> dict[str, str]:
"""원본 확인용 — 값은 모두 글자로(중첩은 JSON 글자 그대로 짧게)."""
return {str(k): ("" if v is None else str(v)) for k, v in row.items()}
class GsshopAdapter(MarketplaceAdapter):
code = "gsshop"
name = "GS샵"
auth_type = "api_key"
docs_url = "https://partners.gsshop.com/api/apiDevGuide"
note = ("GS SHOP 협력사 포털(partners.gsshop.com) → 제휴 API 메인 화면에 로그인하면 보이는 협력사코드와 "
"AES256 암복호화 키를 입력합니다.")
def __init__(self) -> None:
self._mode: dict[str, str] = {} # 협력사코드 → 통과한 암호화 모드
def credential_fields(self) -> list[CredentialField]:
# 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게.
return [
CredentialField("vendor_code", "협력사코드(supCd)", help="예: 1036018"),
CredentialField("api_key", "AES256 암복호화 키", secret=True,
help="제휴 API 메인 화면(로그인 후)에 표시되는 키"),
]
# ── 호출 ──────────────────────────────────────────────
def _creds(self, ctx: AdapterContext) -> tuple[str, str]:
sup = ctx.credentials.get("vendor_code").strip()
key = ctx.credentials.get("api_key").strip()
if not sup or not key:
raise NotConfigured("협력사코드와 AES256 키를 입력하세요.")
return sup, key
def _call(self, ctx: AdapterContext, path: str, params: dict[str, Any], mode: str) -> dict[str, Any]:
import httpx # 지연 import
from app.timezone import now_kst # noqa: WPS433
sup, key = self._creds(ctx)
headers = {"supCd": sup, "token": make_token(key, sup, now_kst(), mode), "Accept": "application/json"}
try:
res = httpx.get(f"{HOST}{path}", params={"supCode": sup, **params}, headers=headers, timeout=ctx.timeout_sec)
except httpx.HTTPError as exc:
raise ApiError(f"GS샵 API 연결 실패: {type(exc).__name__}") from None
try:
body = res.json()
except ValueError:
raise ApiError(f"GS샵이 예상하지 못한 응답을 돌려줬습니다({res.status_code}): {res.text[:150].strip()}") from None
if not isinstance(body, dict):
body = {"data": body}
code = str(body.get("code") or "")
msg = str(body.get("message") or "")[:200]
if res.status_code in (401, 403) or (str(body.get("result")) == "fail" and ("401" in code or "403" in code)):
raise AuthFailed(f"GS샵 인증 거부({code or res.status_code}): {msg}")
if res.status_code >= 400 or str(body.get("result")) == "fail":
raise ApiError(f"GS샵 API 오류({code or res.status_code}): {msg or res.text[:150].strip()}")
return body
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""토큰 암호화 모드를 모르면 순서대로 시도 — 통과한 모드를 기억한다."""
sup, _ = self._creds(ctx)
known = self._mode.get(sup)
if known:
return self._call(ctx, path, params, known)
last: AuthFailed | None = None
for mode in TOKEN_MODES:
try:
body = self._call(ctx, path, params, mode)
except AuthFailed as exc:
last = exc
continue
self._mode[sup] = mode
return body
raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 암호화 방식 {len(TOKEN_MODES)}가지 모두 거부. "
"협력사코드·AES256 키가 맞는지, 서버 시각이 정확한지 확인하세요.")
def _pages(self, ctx: AdapterContext, path: str, lo: date, hi: date) -> list[dict[str, Any]]:
"""[lo, hi] 를 10일씩 나눠 쪽을 넘겨 모두 받는다."""
out: list[dict[str, Any]] = []
s = lo
while s <= hi:
e = min(hi, s + timedelta(days=CHUNK_DAYS - 1))
for page in range(1, MAX_PAGES + 1):
body = self._get(ctx, path, {"fromDate": s.strftime("%Y%m%d"), "toDate": e.strftime("%Y%m%d"),
"pageIdx": page, "rowsPerPage": ROWS_PER_PAGE})
rows = _rows(body)
out.extend(rows)
if not body.get("hasMorePage") or not rows:
break
ctx.progress.step(items=len(out))
s = e + timedelta(days=1)
return out
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
self.authenticate(ctx)
sup, _ = self._creds(ctx)
self._mode.pop(sup, None) # 입력값을 바꿨을 수 있으니 모드를 다시 찾는다
day = today_kst() - timedelta(days=1)
body = self._get(ctx, DAILY_SALES_PATH, {"stdDate": day.strftime("%Y%m%d"), "pageIdx": 1, "rowsPerPage": 10})
total = body.get("totalCount")
return (f"GS샵 연결 정상(매출 내역 조회 확인, 어제 매출 {total if total is not None else len(_rows(body))}건, "
f"토큰 {MODE_LABEL.get(self._mode.get(sup, ''), '')}).")
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
"""매출 내역·배송비 내역을 기간(최대 31일, 10일씩)으로 실제 불러 항목별 합계를 돌려준다(저장 안 함).
응답 항목 이름이 개발가이드에 없어 협력사 포털 매출 화면과 맞는 항목을 실데이터로 확정하는 용도."""
self.authenticate(ctx)
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
probes = []
for key, label, path in (("sales", "매출 내역(매출인식일 기준)", SALES_PATH),
("shipping", "배송비 내역(매출인식일 기준)", SHIPPING_PATH)):
row: dict[str, Any] = {"key": key, "label": label, "path": path}
try:
rows = self._pages(ctx, path, day, to)
except AdapterError as exc:
probes.append({**row, "ok": False, "error": exc.message[:300]})
continue
probes.append({**row, "ok": True, "count": len(rows), "fields": field_summary([_strs(r) for r in rows])})
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes}