diff --git a/app/modules/performance/adapters/gsshop.py b/app/modules/performance/adapters/gsshop.py index ecf48bc..5342ffa 100644 --- a/app/modules/performance/adapters/gsshop.py +++ b/app/modules/performance/adapters/gsshop.py @@ -1,21 +1,195 @@ -"""GS샵 — 협력사 API. +"""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 -from .base import CredentialField, MarketplaceAdapter +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" - note = "입력 항목은 연동 단계에서 GS샵 협력사 API 문서로 확정합니다." + 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", "협력사 코드"), - CredentialField("api_key", "API Key", secret=True), + 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} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 04d346f..2ac48bc 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -239,4 +239,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/settings.html b/app/modules/performance/templates/performance/settings.html index a7d83f4..71e150a 100644 --- a/app/modules/performance/templates/performance/settings.html +++ b/app/modules/performance/templates/performance/settings.html @@ -122,11 +122,13 @@ 쇼핑몰 관리자 화면에서 매출이 있던 날을 넣고 결과를 알려 주시면 그 항목으로 매출 수집을 맞춥니다. 이름·연락처·주소 같은 개인정보는 값을 보이지 않습니다.
· 네이버: 결제일 기준 상품주문 전체(상태별 합계 포함)와 날짜별 "현재 규칙 매출" — 스마트스토어센터 매출과 비교해 주세요.
- · 11번가: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).

+ · 11번가: 주문·클레임·정산 조회 주소별 동작 여부. 정산은 정산일 기준일 수 있어 매출이 있던 날부터 넉넉히(예: 3주).
+ · GS샵: 매출 내역·배송비 내역(매출인식일 기준)의 항목별 합계 — 협력사 포털 매출 화면의 같은 기간 숫자와 비교해 주세요.

~ @@ -175,4 +177,4 @@ {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/tests/test_performance.py b/app/modules/performance/tests/test_performance.py index dcbb364..b1d383c 100644 --- a/app/modules/performance/tests/test_performance.py +++ b/app/modules/performance/tests/test_performance.py @@ -1198,6 +1198,91 @@ def test_sync_job_progress(): assert jobs.get_job(job.id) is job and jobs.running_job() is None +def test_gsshop_token_connection_and_probe(): + """GS샵: token = AES256(yyyyMMddHHmmss + 협력사코드), 헤더 supCd·token. 암호화 모드를 모르니 순서대로 시도해 + 통과한 모드를 기억. 인증 오류는 HTTP 200 + result=fail/code 401. 원본 확인은 10일씩·쪽 넘김, 키는 문구에 없음.""" + import base64 + from datetime import datetime + + import httpx + from cryptography.hazmat.primitives import padding + from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + + from app.modules.performance.adapters import gsshop as gs + from app.modules.performance.adapters.base import AdapterContext + + key = "0123456789abcdef0123456789ABCDEF" # 32바이트 = AES256 + + def decrypt(tok, mode): + m = {"ecb": modes.ECB(), "cbc-zeroiv": modes.CBC(b"\0" * 16)}.get(mode, modes.CBC(key.encode()[:16])) + d = Cipher(algorithms.AES(key.encode()), m).decryptor() + raw = d.update(base64.b64decode(tok)) + d.finalize() + u = padding.PKCS7(128).unpadder() + return (u.update(raw) + u.finalize()).decode() + + now = datetime(2018, 10, 17, 17, 49, 13) + for mode in gs.TOKEN_MODES: + assert decrypt(gs.make_token(key, "1036018", now, mode), mode) == "201810171749131036018" + try: + gs.make_token("short-key", "1", now, "ecb") + except AuthFailed as exc: + assert "short-key" not in exc.message + else: + raise AssertionError("키 길이 오류여야 합니다") + + 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="gsshop", credentials=Creds(vendor_code="1036018", api_key=key)) + calls = [] + + def get(url, params=None, headers=None, timeout=None): + assert headers["supCd"] == "1036018" and params["supCode"] == "1036018" + # 서버는 ECB 로 풀어 본다고 가정 — CBC 토큰은 거부(HTTP 200 + result=fail) + try: + plain = decrypt(headers["token"], "ecb") + except Exception: # noqa: BLE001 + plain = "" + if not plain.endswith("1036018"): + return httpx.Response(200, json={"result": "fail", "message": "키 인증 중 오류가 발생하였습니다.", "code": "401 UNAUTHORIZED"}) + calls.append((url, dict(params))) + if url.endswith("/sales"): + return httpx.Response(200, json={"data": [], "hasMorePage": False, "totalCount": 3}) + page = params["pageIdx"] + more = url.endswith("/sales/period") and params["fromDate"] == "20260901" and page == 1 + rows = [{"ordNo": f"{params['fromDate']}-{page}", "saleAmt": 10000, "custNm": "홍길동", "prdNm": "밀폐용기"}] + return httpx.Response(200, json={"data": rows, "hasMorePage": more, "totalCount": 2 if more else 1}) + + orig = httpx.get + httpx.get = get + try: + msg = gs.GsshopAdapter().test_connection(ctx) + assert "연결 정상" in msg and "3건" in msg and "ECB" in msg + adapter = gs.GsshopAdapter() + rec = adapter.reconcile(ctx, date(2026, 9, 1), to=date(2026, 9, 15)) # 10일 + 5일 + sales, ship = rec["probes"] + assert sales["ok"] and sales["count"] == 3 and ship["ok"] and ship["count"] == 2 # 9/1 두 쪽 + 9/11 + f = {x["name"]: x for x in sales["fields"]} + assert f["saleAmt"]["sum"] == 30000 and f["custNm"]["personal"] and f["custNm"]["sample"] == "" + assert f["prdNm"]["sample"] == "밀폐용기" and "홍길동" not in repr(rec) + periods = {(p["fromDate"], p["toDate"]) for u, p in calls if u.endswith("/sales/period")} + assert periods == {("20260901", "20260910"), ("20260911", "20260915")} + # 틀린 키 → 세 가지 모드 모두 거부 → 인증 실패(키는 문구에 없음) + bad = AdapterContext(code="gsshop", credentials=Creds(vendor_code="1036018", api_key="X" * 32)) + try: + gs.GsshopAdapter().test_connection(bad) + except AuthFailed as exc: + assert "X" * 32 not in exc.message and "3가지" in exc.message + else: + raise AssertionError("인증 실패여야 합니다") + finally: + httpx.get = orig + + if __name__ == "__main__": os.environ.pop("APP_ENCRYPTION_KEY", None) n = 0 diff --git a/app/static/performance.js b/app/static/performance.js index 16af264..2bc60c2 100644 --- a/app/static/performance.js +++ b/app/static/performance.js @@ -936,8 +936,9 @@ probe.disabled = true; const codeSel = document.getElementById("perf-probe-code"); const code = codeSel ? codeSel.value : "elevenst"; - out.innerHTML = '

' + (code === "naver" ? "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)" - : "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)") + "

"; + const loading = { naver: "네이버에서 불러오는 중… (하루씩, 기간이 길면 수십 초)", + gsshop: "GS샵에서 불러오는 중… (10일 단위)" }[code] || "11번가에서 불러오는 중… (주소 10개 × 7일 단위, 기간이 길면 1분 이상)"; + out.innerHTML = '

' + loading + "

"; try { const to = document.getElementById("perf-probe-to").value || day; const r = await api("GET", "/performance/api/marketplaces/" + code + "/reconcile?date=" + encodeURIComponent(day) + diff --git a/docs/PERFORMANCE_MODULE.md b/docs/PERFORMANCE_MODULE.md index 2363142..c92a3f1 100644 --- a/docs/PERFORMANCE_MODULE.md +++ b/docs/PERFORMANCE_MODULE.md @@ -125,6 +125,18 @@ - 설정 화면 **"쇼핑몰 원본 데이터 확인"**(네이버 선택): 결제일 기준 상품주문 전체의 항목별 합계, 상태별 합계, 날짜별 매출·그중 결제 뒤 취소/반품(참고)·배송비(참고). 개인정보(주문자·수령인·주소·연락처·메모)는 값 없이 이름만. +### GS샵 (`adapters/gsshop.py`, 연결·원본 확인까지 — 매출 규칙 확정 전) + +- 문서: 협력사 포털 → 제휴 API → 개발가이드(`partners.gsshop.com/api/apiDevGuide`, 본문은 `/docs/withgs-api-docs.html` Redoc). +- 인증: 헤더 `supCd`(협력사코드) + `token` = base64(AES256(`yyyyMMddHHmmss` + 협력사코드)), 키는 제휴 API 메인 화면(로그인 후). + 문서에 암호화 모드가 없어 CBC(IV=키 앞 16바이트) → ECB → CBC(IV=0) 순서로 시도하고 통과한 모드를 기억(`TOKEN_MODES`). + 토큰이 틀리면 **HTTP 200** + `{"result":"fail","code":"401 UNAUTHORIZED"}`. 운영 주소 `withgs-api.gsshop.com`(문서 예시 + `atwithgs-api` 는 테스트용 — 두 곳 모두 응답). 입력칸 키는 처음 만든 `vendor_code`·`api_key` 그대로(라벨만 협력사코드·AES256 키). +- 매출: `GET /api/v2/settlement/out/sales/period?supCode&fromDate&toDate&pageIdx&rowsPerPage` — **매출인식일** 기준, 한 번에 10일, + 쪽당 1만 건, `{data, hasMorePage, totalCount}`. 배송비는 `/shippingFee/period`. 응답 줄 항목 이름이 문서 예시에 없어 + ("property1") 설정 화면 "쇼핑몰 원본 데이터 확인"(GS샵)으로 항목별 합계를 보고 협력사 포털 매출 화면과 맞춰 규칙을 정한다. + 그 전까지 매출 수집은 "연동 준비 중"(`implemented=False`). + ### 연동 단계 체크리스트(쇼핑몰마다) - 공식 문서로 인증 방식·호출 제한·페이지네이션·주문 상태 코드·취소/반품 API·날짜 필드 확인