f4fadec0a4
- 포털 운영 KEY 가 16진수 글자라 키를 바이트로 쓰는 법을 모드와 함께 차례로 시도, 통과한 조합 기억 - 입력칸·안내 문구를 "운영 KEY"로(개발 KEY 아님), 연결 성공 문구에 통과한 방식 표시 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
223 lines
12 KiB
Python
223 lines
12 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)와 키를 바이트로 쓰는 법은 문서에 없다 → 키 변형(글자 그대로 / 16진수 풀기 / 앞 32자,
|
||
key_variants) × 모드(CBC·IV=키 앞 16바이트 → ECB → CBC·IV=0) 순서로 시도하고 통과한 조합을 기억한다. 출력은 base64.
|
||
(포털 "운영 KEY" 는 16진수처럼 보이는 글자 — 32자면 글자 그대로 AES256, 64자면 16진수로 풀어 32바이트일 수 있다.)
|
||
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)"}
|
||
|
||
|
||
KEY_LABEL = {"text": "키 글자 그대로", "hex": "키 16진수 풀기", "first32": "키 앞 32자"}
|
||
|
||
|
||
def key_variants(aes_key: str) -> list[tuple[str, bytes]]:
|
||
"""AES 키로 쓸 수 있는 바이트 후보(시도 순서). 하나도 없으면 길이 오류."""
|
||
raw = aes_key.strip().encode("utf-8")
|
||
out: list[tuple[str, bytes]] = []
|
||
if len(raw) in (16, 24, 32):
|
||
out.append(("text", raw))
|
||
txt = aes_key.strip()
|
||
if len(txt) in (32, 48, 64) and all(c in "0123456789abcdefABCDEF" for c in txt):
|
||
out.append(("hex", bytes.fromhex(txt)))
|
||
if len(raw) > 32:
|
||
out.append(("first32", raw[:32]))
|
||
if not out:
|
||
raise AuthFailed(f"AES 키 길이가 올바르지 않습니다({len(raw)}자). 제휴 API 메인 화면의 운영 KEY 를 "
|
||
"[복사] 버튼으로 복사해 그대로 붙여 넣으세요.")
|
||
return out
|
||
|
||
|
||
def make_token(aes_key: str | bytes, sup_cd: str, now: datetime, mode: str) -> str:
|
||
"""token = base64(AES(yyyyMMddHHmmss + 협력사코드)), PKCS7(=PKCS5) 패딩. aes_key 가 글자면 그대로 바이트로."""
|
||
from cryptography.hazmat.primitives import padding # 지연 import
|
||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||
|
||
key = aes_key if isinstance(aes_key, bytes) else 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 메인 화면의 협력사코드와 "
|
||
"운영 KEY(오른쪽 [복사] 버튼)를 입력합니다. 개발 KEY 가 아니라 운영 KEY 입니다.")
|
||
|
||
def __init__(self) -> None:
|
||
self._mode: dict[str, tuple[str, str]] = {} # 협력사코드 → 통과한 (키 변형, 암호화 모드)
|
||
|
||
def credential_fields(self) -> list[CredentialField]:
|
||
# 키 이름(vendor_code·api_key)은 처음 만든 입력칸 그대로 — 이미 저장한 값을 다시 넣지 않아도 되게.
|
||
return [
|
||
CredentialField("vendor_code", "협력사코드(supCd)", help="예: 1036018"),
|
||
CredentialField("api_key", "운영 KEY(AES256 암복호화 키)", secret=True,
|
||
help="제휴 API 메인 화면의 운영 KEY — [복사] 버튼으로 복사해 붙여 넣기"),
|
||
]
|
||
|
||
# ── 호출 ──────────────────────────────────────────────
|
||
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], how: tuple[str, str]) -> dict[str, Any]:
|
||
import httpx # 지연 import
|
||
|
||
from app.timezone import now_kst # noqa: WPS433
|
||
|
||
sup, key = self._creds(ctx)
|
||
key_bytes = dict(key_variants(key))[how[0]]
|
||
headers = {"supCd": sup, "token": make_token(key_bytes, sup, now_kst(), how[1]), "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, key = self._creds(ctx)
|
||
known = self._mode.get(sup)
|
||
if known:
|
||
return self._call(ctx, path, params, known)
|
||
tries = [(v, m) for v, _ in key_variants(key) for m in TOKEN_MODES]
|
||
last: AuthFailed | None = None
|
||
for how in tries:
|
||
try:
|
||
body = self._call(ctx, path, params, how)
|
||
except AuthFailed as exc:
|
||
last = exc
|
||
continue
|
||
self._mode[sup] = how
|
||
return body
|
||
raise AuthFailed(f"{last.message if last else 'GS샵 인증 실패'} — 토큰 만드는 방식 {len(tries)}가지 모두 거부. "
|
||
"협력사코드·운영 KEY 가 맞는지, 서버 시각이 정확한지 확인하세요.")
|
||
|
||
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"토큰 {self._how_label(sup)}).")
|
||
|
||
def _how_label(self, sup: str) -> str:
|
||
v, m = self._mode.get(sup, ("", ""))
|
||
return f"{MODE_LABEL.get(m, m)}, {KEY_LABEL.get(v, v)}"
|
||
|
||
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
|
||
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}
|