feat(performance): 토스쇼핑 매출 수집 — OAuth 토큰·주문 내역 조회(31일·커서)·원본 데이터 확인

- 인증: Access Key·Secret Key → POST oauth2.cert.toss.im/token(client_credentials, scope toss-shopping-fep:write),
  토큰(약 1년) 암호화 저장·재사용, 401 이면 한 번 새로 발급. 키 발급 때 등록한 IP 에서만 호출됨
- 입력칸 라벨을 Access Key / Secret Key 로(키 이름 api_key·api_secret 그대로 — 저장값 유지), 판매자 ID 칸 제거
- 수집: GET /api/v3/shopping-fep/orders/v2 31일 구간 + nextCursor, HTTP 200 + resultType FAIL 도 오류 처리
- 잠정 매출 규칙: 주문 단위(toss:{orderId}), 주문일(한국 날짜), price 합(할인 전·배송비 제외), 결제 전만 제외
- 설정 화면 "쇼핑몰 원본 데이터 확인"에 토스쇼핑 — 상태별 항목 합계·날짜별 현재 규칙 매출(개인정보 숨김)
- 테스트 3개 추가(토큰·연결·오류, 수집 규칙·구간·커서, 원본 확인 개인정보), 문서 갱신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-01 09:36:42 +09:00
parent d3761183c3
commit a45f78217c
6 changed files with 566 additions and 15 deletions
@@ -379,6 +379,183 @@ def test_sync_isolation_redaction_and_dedupe():
assert r3["skipped"]
def _toss_item(order_id, op_id, ordered_at, price, *, status="PAID", qty=1, dc=0, ship=0, group=None, name="밀폐용기"):
"""토스쇼핑 주문 내역 조회 results[] 한 줄(주문상품) — 개인정보 항목 포함(저장 안 되는지 확인용)."""
return {"orderId": order_id, "orderProductId": op_id, "orderedAt": ordered_at, "orderProductStatus": status,
"productName": name, "optionName": "3개입", "quantity": qty, "price": price, "originPrice": price,
"totalDiscountPrice": dc, "tossShoppingDiscount": dc, "tossPayDiscount": 0, "tossPayPoint": 0,
"deliveryFee": ship, "deliveryFeeGroupId": group,
"ordererName": "홍길동", "ordererPhone": "010-1234-5678", "receiverName": "홍길동",
"receiverPhone": "010-1234-5678", "address": "서울시 어딘가", "detailAddress": "101호", "zipCode": "01234",
"shippingNote": "문 앞에 두세요 010-9999-8888"}
class _TossCreds(dict):
def get(self, k, default=""):
return dict.get(self, k, default)
def has(self, k):
return bool(dict.get(self, k))
def set(self, k, v):
self[k] = v
def test_toss_token_and_connection():
"""토스쇼핑: Access Key·Secret Key → OAuth2 토큰(form, scope 고정) → Bearer 로 주문 내역 조회.
HTTP 200 + resultType FAIL 도 오류, 401 이면 토큰 한 번 새로 받기. 키·토큰은 오류 문구에 없음."""
import httpx
from app.modules.performance.adapters import toss as ts
from app.modules.performance.adapters.base import AdapterContext, AdapterError
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="ACCESS-KEY-1", api_secret="SECRET-KEY-1"))
seen = {"posts": [], "gets": []}
def post(url, data=None, timeout=None, headers=None):
seen["posts"].append((url, dict(data)))
return httpx.Response(200, json={"access_token": f"TOKEN-{len(seen['posts'])}", "expires_in": 31535999,
"token_type": "Bearer", "scope": "toss-shopping-fep:write"})
def get(url, params=None, headers=None, timeout=None):
seen["gets"].append((url, dict(params), headers["Authorization"]))
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {
"results": [_toss_item(1, 11, "2026-09-30T10:00:00", 12000)], "nextCursor": "c2"}})
orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC)
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0
try:
msg = ts.TossAdapter().test_connection(ctx)
assert "연결 정상" in msg and "1건 이상" in msg
url, form = seen["posts"][0]
assert url == "https://oauth2.cert.toss.im/token"
assert form == {"grant_type": "client_credentials", "client_id": "ACCESS-KEY-1",
"client_secret": "SECRET-KEY-1", "scope": "toss-shopping-fep:write"}
gurl, params, auth = seen["gets"][0]
assert gurl == "https://shopping-fep.toss.im/api/v3/shopping-fep/orders/v2" and auth == "Bearer TOKEN-1"
assert params["startDate"] == params["endDate"] and params["limit"] == 1
assert ctx.credentials["access_token"] == "TOKEN-1" and int(ctx.credentials["access_token_expires_at"]) > 0
# 저장된 토큰은 다시 쓴다(매번 발급하지 않음) — 401 이면 한 번만 새로 받는다
n_posts = len(seen["posts"])
statuses = iter([401, 200])
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
next(statuses), json={"resultType": "SUCCESS", "success": {"results": [], "nextCursor": None}})
assert ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1)) == []
assert len(seen["posts"]) == n_posts + 1 and ctx.credentials["access_token"] == f"TOKEN-{n_posts + 1}"
# HTTP 200 + resultType FAIL → API 오류
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
200, json={"resultType": "FAIL", "error": {"errorCode": "INVALID_DATE_RANGE", "reason": "조회 기간 초과"}})
try:
ts.TossAdapter()._window_items(ctx, date(2026, 9, 1), date(2026, 9, 1))
except AdapterError as exc:
assert exc.status == "api_error" and "INVALID_DATE_RANGE" in exc.message
else:
raise AssertionError("API 오류여야 합니다")
# 토큰 발급 거부 → 인증 실패(키는 문구에 없음)
httpx.post = lambda url, data=None, timeout=None, headers=None: httpx.Response(
401, json={"error": "invalid_client", "error_description": "client authentication failed"})
try:
ts.TossAdapter().test_connection(ctx)
except AuthFailed as exc:
assert "invalid_client" in exc.message and "SECRET-KEY-1" not in exc.message
assert "ACCESS-KEY-1" not in exc.message
else:
raise AssertionError("인증 실패여야 합니다")
# 주문 조회 403(IP 미등록 등) → 인증 실패 + IP 안내, 토큰은 문구에 없음
httpx.post = post
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
403, json={"resultType": "FAIL", "error": {"errorCode": "FORBIDDEN", "reason": "허용되지 않은 IP"}})
try:
ts.TossAdapter().test_connection(ctx)
except AuthFailed as exc:
assert "허용되지 않은 IP" in exc.message and "TOKEN-" not in exc.message
else:
raise AssertionError("권한 거부여야 합니다")
finally:
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig
def test_toss_collect_sales():
"""토스쇼핑 매출(잠정) = 주문 단위, 주문일(한국 날짜) 기준, 주문상품 price(판매가 × 수량) 합 — 할인 전, 배송비 제외.
결제 뒤 취소·반품도 포함, 결제 전만 뺀다. 31일 구간으로 나눠 부르고 커서로 끝까지 받는다. 구매자 정보는 저장 안 함."""
import httpx
from app.modules.performance.adapters import toss as ts
pages = {
("2026-08-01", None): ([_toss_item(1, 11, "2026-08-31T23:30:00+09:00", 20000, qty=2, dc=1000, ship=3000, group=7),
_toss_item(1, 12, "2026-08-31T23:30:00+09:00", 5000, ship=3000, group=7, name="뚜껑")], "p2"),
("2026-08-01", "p2"): ([_toss_item(2, 21, "2026-08-31T16:00:00Z", 9900, status="CANCELED_PAYMENT"), # 9/1 01:00 KST
_toss_item(3, 31, "2026-08-31T09:00:00", 4000, status="BEFORE_PAYMENT")], None),
("2026-09-01", None): ([_toss_item(4, 41, "2026-09-01T10:00:00", 15000, status="COMPLETED_RETURN")], None),
}
calls = []
def get(url, params=None, headers=None, timeout=None):
key = (params["startDate"], params.get("nextCursor"))
calls.append((params["startDate"], params["endDate"], params.get("nextCursor")))
rows, cur = pages.get(key, ([], None))
return httpx.Response(200, json={"resultType": "SUCCESS", "success": {"results": rows, "nextCursor": cur}})
def post(url, data=None, timeout=None, headers=None):
return httpx.Response(200, json={"access_token": "TOKEN-T", "expires_in": 31535999})
st = FakeStore()
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "toss"), {"api_key": "ak", "api_secret": "sk"})
orig = (httpx.post, httpx.get, ts.CALL_INTERVAL_SEC)
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = post, get, 0
try:
r = SyncService(st, creds).sync_marketplace("toss", date(2026, 8, 1), date(2026, 9, 2))
finally:
httpx.post, httpx.get, ts.CALL_INTERVAL_SEC = orig
assert r["ok"], r
assert calls == [("2026-08-01", "2026-08-31", None), ("2026-08-01", "2026-08-31", "p2"),
("2026-09-01", "2026-09-02", None)] # 31일 구간 + 커서
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "toss"}
assert set(ev_) == {"toss:1", "toss:2", "toss:4"} # 결제 전(3)만 제외
assert ev_["toss:1"]["amount"] == 25000 and ev_["toss:1"]["discount_amount"] == 1000 # 할인 전·배송비 제외
assert ev_["toss:1"]["quantity"] == 3 and ev_["toss:1"]["product_name"] == "밀폐용기 외 1건"
assert ev_["toss:1"]["sales_date"] == date(2026, 8, 31)
assert ev_["toss:2"]["amount"] == 9900 and ev_["toss:2"]["sales_date"] == date(2026, 9, 1) # UTC → 한국 날짜
assert ev_["toss:4"]["amount"] == 15000 and ev_["toss:4"]["order_status"] == "반품완료"
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
def test_toss_reconcile_hides_personal():
import time as _t
import httpx
from app.modules.performance.adapters import toss as ts
from app.modules.performance.adapters.base import AdapterContext
ctx = AdapterContext(code="toss", credentials=_TossCreds(api_key="a", api_secret="b", access_token="T",
access_token_expires_at=str(int(_t.time()) + 99999)))
rows = [_toss_item(1, 11, "2026-09-09T10:00:00", 20000, ship=3000, group=1),
_toss_item(2, 21, "2026-09-09T11:00:00", 9900, status="CANCELED_PAYMENT", ship=3000, group=2)]
orig = (httpx.get, ts.CALL_INTERVAL_SEC)
httpx.get = lambda url, params=None, headers=None, timeout=None: httpx.Response(
200, json={"resultType": "SUCCESS", "success": {"results": rows, "nextCursor": None}})
ts.CALL_INTERVAL_SEC = 0
try:
rec = ts.TossAdapter().reconcile(ctx, date(2026, 9, 9), to=date(2026, 9, 10))
finally:
httpx.get, ts.CALL_INTERVAL_SEC = orig
allp = rec["probes"][0]
assert allp["ok"] and allp["count"] == 2
f = {x["name"]: x for x in allp["fields"]}
assert f["price"]["sum"] == 29900
for k in ("ordererName", "ordererPhone", "address", "zipCode", "shippingNote"):
assert f[k]["personal"] and f[k]["sample"] == "", k
assert not f["productName"]["personal"] and f["productName"]["sample"] == "밀폐용기"
assert "홍길동" not in repr(rec) and "010-1234-5678" not in repr(rec) and "010-9999-8888" not in repr(rec)
assert rec["days"] == [{"date": "2026-09-09", "orders": 2, "amount": 29900, "claimed": 9900, "ship": 6000},
{"date": "2026-09-10", "orders": 0, "amount": 0, "claimed": 0, "ship": 0}]
assert any("결제 뒤 취소·반품(매출 포함)" in p["label"] for p in rec["probes"])
def test_not_implemented_and_mock():
st = FakeStore()
creds = CredentialService(st, lambda: ring())