feat(performance): 카카오쇼핑 Open API 매출 수집(결제일 기준)

- kapi.kakao.com, Authorization(앱 어드민 키)·Target-Authorization(판매자 API 인증키)·channel-ids 헤더
- 결제일시 기준 주문내역(paidAt, 하루씩·token 페이징) → 주문정보(order_id)로 금액
- 결제(paymentId) 하나 = SALE, (상품가+옵션가)×수량 − 할인, 배송비 제외, 미결제만 제외
- 인증 오류(-2·-401·대행사 매핑) 안내, 개인정보는 받자마자 지움, 원본 데이터 확인 지원

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-13 16:11:28 +09:00
parent f8245b4499
commit e6d38f342f
3 changed files with 519 additions and 7 deletions
+351 -6
View File
@@ -1,21 +1,366 @@
"""카카오 — 카카오쇼핑(톡스토어) 판매자 API.
"""카카오 — 카카오쇼핑(톡스토어) Open API(shopping-developers.kakao.com, 2026-10-13 문서 확인).
인증 방식·필드는 연동 단계에서 공식 문서로 확정한다.
인증(“API 공통 인증 헤더 구성”) — 모든 호출에 같은 헤더 3개, 주소 https://kapi.kakao.com
Authorization: KakaoAK {앱 어드민 키} 카카오디벨로퍼스 앱(연동 앱) → 앱 설정 → 앱 → 어드민 키
Target-Authorization: KakaoAK {판매자 API 인증키} 카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키
channel-ids: 101(톡스토어) / 1(선물하기) / "1,101"(둘 다)
두 헤더에 같은 앱의 키를 넣으면 {"code": -2, "msg": "invalid authorization or target-authorization header."},
판매자 인증키가 바뀌었거나 무효면 {"code": -401, "msg": "appKey(판매자인증키) is already deactivated"},
연동 앱과 판매자가 연결되지 않았으면 "대행사 매핑/권한 확인이 필요합니다."
Open API 는 카카오쇼핑 검토를 거쳐 허락된 앱만 쓸 수 있다(“카카오쇼핑 API 연동 검토 요청하기”).
매출 수집 — 네이버와 같은 기준(결제일, 할인 뒤 상품 금액, 배송비 제외, 결제 뒤 취소·반품분도 결제일 매출에 포함):
- 결제일시 기준 주문내역 조회 GET /v2/shopping/orders/paidAt?from=YYYY-MM-DD HH:mm:ss&to=…&size=100(&token=)
— 한 번에 24시간까지(하루씩 부른다), 쪽당 100건, 다음 쪽은 응답의 token(더 없으면 token 없음).
목록에는 금액이 없다(orderId·paymentId·orderStatus·paidAt …).
- 주문 하나씩 주문정보 조회 GET /v1/shopping/order?order_id= 로 orderProduct 금액을 받는다.
한 번 받은 주문은 목록의 modifiedAt 이 같으면 다시 부르지 않는다(프로세스 안 메모리 캐시).
- 카카오 주문(orderId)은 상품 한 줄이고 결제(paymentId)가 장바구니 하나 → SALE = 결제 하나(`kakao:{paymentId}`),
날짜 = 결제일(paidAt, 한국 시간), 금액 = 그 결제에 든 상품 줄 금액 합.
- 상품 줄 금액(line_amount) = (productPrice + optionPrice) × quantity − sellerDiscountPrice − sellerCouponDiscountPrice
− adminDiscountPrice. 문서에 결제금액 항목이 따로 없어 이 식으로 만든다 — **판매자센터 매출 화면과 아직 대조 전**.
설정 화면 "쇼핑몰 원본 데이터 확인"에서 항목별 합계를 보고 맞는 식으로 확정한다.
- 미결제(주문 생성·결제 요청·입금 대기/확인·결제 실패·미입금 취소)만 뺀다.
- 구매자 이름·연락처·주소는 저장하지 않는다(원본 확인에서도 값 없이 이름만).
"""
from __future__ import annotations
from .base import CredentialField, MarketplaceAdapter
import re
import time
from datetime import date, timedelta
from typing import Any, Iterable
from .base import (
AdapterContext,
AdapterError,
ApiError,
AuthFailed,
CredentialField,
MarketplaceAdapter,
NotConfigured,
SaleEvent,
)
from .naver import field_summary, flatten
HOST = "https://kapi.kakao.com"
PAID_PATH = "/v2/shopping/orders/paidAt"
ORDER_PATH = "/v1/shopping/order"
EVENT_PREFIX = "kakao:"
DEFAULT_CHANNELS = "101" # 톡스토어
PAGE_SIZE = 100
MAX_PAGES = 200 # 하루 2만 건 — 무한 반복 방지
CALL_INTERVAL_SEC = 0.1 # 호출 사이 간격(문서에 제한 없음 — 넉넉히)
RETRY_429 = 3
PROBE_MAX_DAYS = 31
CACHE_MAX = 20000
# 매출에서 빼는 상태 — 결제되지 않은 것만. 결제 뒤 취소·반품은 결제일 매출에 그대로(네이버 "판매금액(총)"과 같은 기준).
UNPAID_STATUS = frozenset({"Created", "PayRequest", "PayWaiting", "PayChecking", "PayFailed", "UnpaidCancelComplete"})
# 결제 뒤 취소·환불·반품 완료 — 원본 확인 표에 참고로 따로 보여 줌
CLAIMED_STATUS = frozenset({
"PayCancelComplete", "RefundComplete", "ShippingCancelComplete", "ShippingRefundComplete",
"ReturnCancelComplete", "ReturnRefundComplete", "TicketCancelComplete", "TicketRefundComplete",
})
STATUS_KO = {
"Created": "주문 생성", "PayRequest": "결제 요청", "PayWaiting": "결제 대기", "PayChecking": "입금 확인 중",
"PayFailed": "결제 실패", "PayComplete": "결제 완료", "ShippingRequest": "배송 요청",
"PayCancelRequest": "결제 취소 예정", "PayCancelComplete": "결제 취소 완료", "RefundComplete": "환불 완료",
"UnpaidCancelComplete": "미입금 취소 완료", "ShippingWaiting": "배송 준비 중",
"ShippingCancelComplete": "결제 취소 완료", "ShippingProgress": "배송 중", "ShippingComplete": "배송 완료",
"ShippingRefundComplete": "환불 완료", "ExchangeShippingComplete": "교환 완료", "ReturnRequest": "반품 요청",
"ReturnCancelComplete": "반품 결제 취소 완료", "ReturnRefundComplete": "반품 환불 완료",
"TicketSendComplete": "발송 완료", "TicketCancelComplete": "결제 취소 완료", "TicketRefundComplete": "환불 완료",
"BuyDecision": "구매 결정",
}
def _won(value: Any) -> int:
try:
return int(round(float(str(value if value is not None else 0).replace(",", ""))))
except ValueError:
return 0
def _day(value: Any) -> date | None:
""""20251201201735" 또는 "2025-12-01 20:17:35" → date(2025, 12, 1). 카카오 날짜는 한국 시간."""
s = "".join(ch for ch in str(value or "") if ch.isdigit())[:8]
if len(s) < 8:
return None
try:
return date(int(s[:4]), int(s[4:6]), int(s[6:8]))
except ValueError:
return None
def line_amount(op: dict[str, Any]) -> int:
"""상품 줄 금액 = (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오(관리자) 할인. 배송비 제외."""
qty = max(1, _won(op.get("quantity")))
gross = (_won(op.get("productPrice")) + _won(op.get("optionPrice"))) * qty
return max(0, gross - line_discount(op))
def line_discount(op: dict[str, Any]) -> int:
return sum(abs(_won(op.get(k))) for k in ("sellerDiscountPrice", "sellerCouponDiscountPrice", "adminDiscountPrice"))
# 구매자 개인정보 — 받자마자 값을 지운다(메모리 캐시·원본 확인 표 어디에도 남기지 않음, 항목 이름만 남김).
PERSONAL_OBJECTS = ("orderer", "orderDeliveryRequest", "orderTicketReceiver")
PERSONAL_KEY = re.compile(r"^(pickup|exchange)(Name|ZipCode|RoadZipCode|Address\d*|MobileNumber|PhoneNumber)$|reasonComment")
def strip_personal(det: dict[str, Any]) -> dict[str, Any]:
out: dict[str, Any] = {}
for k, v in det.items():
if k in PERSONAL_OBJECTS and isinstance(v, dict):
out[k] = {kk: "" for kk in v}
elif isinstance(v, dict):
out[k] = {kk: ("" if PERSONAL_KEY.search(str(kk)) else vv) for kk, vv in v.items()}
else:
out[k] = v
return out
def order_detail(body: Any) -> dict[str, Any]:
"""주문정보 조회 응답에서 주문 하나(orderBase·orderProduct …)를 꺼낸다(개인정보 값은 지움).
감싼 모양(data/content)도 받아들인다."""
if not isinstance(body, dict):
return {}
if isinstance(body.get("orderProduct"), dict) or isinstance(body.get("orderBase"), dict):
return strip_personal(body)
for k in ("data", "content", "contents"):
v = body.get(k)
if isinstance(v, list) and v and isinstance(v[0], dict):
v = v[0]
if isinstance(v, dict) and (isinstance(v.get("orderProduct"), dict) or isinstance(v.get("orderBase"), dict)):
return strip_personal(v)
return {}
def group_payments(items: Iterable[dict[str, Any]], start: date, end: date) -> dict[str, dict[str, Any]]:
"""주문(상품 줄) → 결제 하나로 합침(결제일이 [start, end] 이고 결제된 것 — 나중에 취소·반품된 것도 포함).
items = {"row": 목록 줄, "detail": 주문정보}. 배송비·취소/반품분은 참고용(ship·claimed)으로만 모은다."""
pays: dict[str, dict[str, Any]] = {}
for it in items:
row, det = it.get("row") or {}, it.get("detail") or {}
base, op = det.get("orderBase") or {}, det.get("orderProduct") or {}
status = str(row.get("orderStatus") or base.get("status") or "")
day = _day(row.get("paidAt") or base.get("paidAt"))
oid = str(row.get("orderId") or base.get("id") or det.get("id") or "")
pid = str(row.get("paymentId") or base.get("paymentId") or oid)
if not oid or day is None or not (start <= day <= end) or status in UNPAID_STATUS or not op:
continue
p = pays.setdefault(pid, {"paymentId": pid, "_day": day, "amount": 0, "ship": 0, "claimed": 0, "qty": 0,
"discount": 0, "names": [], "opt": "", "statuses": [], "orders": [],
"order_day": _day(row.get("createdAt") or base.get("createdAt"))})
amt = line_amount(op)
p["amount"] += amt
if status in CLAIMED_STATUS:
p["claimed"] += amt
p["ship"] += _won(op.get("deliveryAmount")) + _won(op.get("areaAdditionalDeliveryAmount"))
p["qty"] += max(1, _won(op.get("quantity")))
p["discount"] += line_discount(op)
p["orders"].append(oid)
name = str(op.get("name") or "")
if name and name not in p["names"]:
p["names"].append(name)
p["opt"] = p["opt"] or str(op.get("optionContent") or "")
if status and status not in p["statuses"]:
p["statuses"].append(status)
return pays
def _err_text(body: dict[str, Any], res: Any) -> str:
parts = [str(body.get(k)) for k in ("code", "msg", "message") if body.get(k) not in (None, "")]
ex = body.get("extras")
if isinstance(ex, dict):
parts += [str(ex.get(k)) for k in ("error_code", "error_message") if ex.get(k) not in (None, "")]
return " ".join(parts)[:300] or res.text[:200].strip() or "응답 없음"
class KakaoAdapter(MarketplaceAdapter):
code = "kakao"
name = "카카오"
auth_type = "api_key"
note = "입력 항목은 연동 단계에서 카카오쇼핑 판매자 API 문서로 확정합니다."
implemented = True
replace_range = True
event_prefix = EVENT_PREFIX
docs_url = "https://shopping-developers.kakao.com/hc/ko/articles/4578909656975"
note = ("카카오쇼핑 Open API 는 카카오쇼핑 검토로 허락된 카카오디벨로퍼스 앱만 쓸 수 있습니다. "
"그 앱의 어드민 키와, 판매자센터(정보관리 → 판매채널 정보 → API 인증키)의 판매자 API 인증키를 입력합니다. "
"두 키는 서로 다른 앱의 키여야 합니다.")
def __init__(self) -> None:
self._last_call = 0.0
self._details: dict[str, tuple[str, dict[str, Any]]] = {} # orderId → (modifiedAt, 주문정보)
def credential_fields(self) -> list[CredentialField]:
# api_key 는 처음 만든 입력칸 이름 그대로 — 이미 저장한 판매자 인증키를 다시 넣지 않아도 되게.
return [
CredentialField("seller_id", "판매자(채널) ID"),
CredentialField("api_key", "API Key", secret=True),
CredentialField("admin_key", "앱 어드민 키(Authorization)", secret=True,
help="카카오디벨로퍼스 → 내 애플리케이션(카카오쇼핑 API 허락된 앱) → 앱 설정 → 앱 → 어드민 키"),
CredentialField("api_key", "판매자 API 인증키(Target-Authorization)", secret=True,
help="카카오쇼핑 판매자센터 → 정보관리 → 판매채널 정보 → API 인증키"),
CredentialField("channel_ids", "판매채널(channel-ids)", required=False, placeholder=DEFAULT_CHANNELS,
help="톡스토어 101(기본), 선물하기 1, 둘 다 1,101"),
]
# ── 호출 ──────────────────────────────────────────────
def _headers(self, ctx: AdapterContext) -> dict[str, str]:
admin = ctx.credentials.get("admin_key").strip()
seller = ctx.credentials.get("api_key").strip()
if not admin or not seller:
raise NotConfigured("앱 어드민 키와 판매자 API 인증키를 입력하세요.")
channels = re.sub(r"\s+", "", ctx.credentials.get("channel_ids") or "") or DEFAULT_CHANNELS
return {"Authorization": f"KakaoAK {admin}", "Target-Authorization": f"KakaoAK {seller}",
"channel-ids": channels, "Accept": "application/json"}
def _get(self, ctx: AdapterContext, path: str, params: dict[str, Any]) -> dict[str, Any]:
"""GET — 호출 간격 유지, 429 는 잠깐 쉬고 다시. 키 오류는 AuthFailed(무엇을 확인할지 안내)."""
import httpx # 지연 import
headers = self._headers(ctx)
for attempt in range(RETRY_429 + 1):
ctx.progress.check() # [업데이트 취소]면 여기서 멈춤
wait = CALL_INTERVAL_SEC - (time.monotonic() - self._last_call)
if wait > 0:
time.sleep(wait)
try:
res = httpx.get(f"{HOST}{path}", params=params, headers=headers, timeout=ctx.timeout_sec)
except httpx.HTTPError as exc:
raise ApiError(f"카카오쇼핑 API 연결 실패: {type(exc).__name__}") from None
finally:
self._last_call = time.monotonic()
if res.status_code == 429 and attempt < RETRY_429:
time.sleep(1.0 * (2 ** attempt))
continue
try:
body = res.json()
except ValueError:
body = {}
if not isinstance(body, dict):
body = {"contents": body}
code = _won(body.get("code")) if body.get("code") not in (None, "") else 0
text = _err_text(body, res)
if code == -2 or "target-authorization" in text.lower():
raise AuthFailed(f"카카오 인증 헤더 거부({text}). 앱 어드민 키와 판매자 API 인증키가 서로 다른 앱의 키인지, "
"어드민 키가 REST API 키가 아닌지 확인하세요.")
if code == -401 or "deactivated" in text:
raise AuthFailed(f"카카오 판매자 API 인증키 무효({text}). 판매자센터의 API 인증키를 다시 복사해 넣으세요.")
if "매핑" in text or "대행사" in text:
raise AuthFailed(f"카카오쇼핑 연동 앱과 판매자가 연결되지 않았습니다({text}). 판매자 연결(POST /v1/store/register)이 "
"끝났는지, 앱이 카카오쇼핑 API 허락을 받았는지 확인하세요.")
if res.status_code in (401, 403):
raise AuthFailed(f"카카오 권한 거부({res.status_code}): {text}. 앱이 카카오쇼핑 API 허락을 받았는지, "
"두 키가 맞는지 확인하세요.")
if res.status_code >= 400 or code < 0:
raise ApiError(f"카카오쇼핑 API 오류({res.status_code}): {text}")
return body
raise ApiError("카카오쇼핑 API 호출 제한(429)이 계속됩니다. 잠시 뒤 다시 시도하세요.")
def _day_rows(self, ctx: AdapterContext, d: date) -> list[dict[str, Any]]:
"""결제일이 d(한국 시간 0시~23:59:59)인 주문 목록 — 모든 상태, 금액 없음."""
params: dict[str, Any] = {"from": f"{d.isoformat()} 00:00:00", "to": f"{d.isoformat()} 23:59:59",
"size": PAGE_SIZE}
out: list[dict[str, Any]] = []
token = ""
for _ in range(MAX_PAGES):
body = self._get(ctx, PAID_PATH, {**params, **({"token": token} if token else {})})
rows = [r for r in body.get("contents") or [] if isinstance(r, dict)]
out.extend(rows)
token = str(body.get("token") or "")
if not token or not rows:
break
return out
def _detail(self, ctx: AdapterContext, row: dict[str, Any]) -> dict[str, Any]:
oid = str(row.get("orderId") or "")
mod = str(row.get("modifiedAt") or "")
hit = self._details.get(oid)
if hit and hit[0] == mod and mod:
return hit[1]
det = order_detail(self._get(ctx, ORDER_PATH, {"order_id": oid}))
if det:
if len(self._details) >= CACHE_MAX:
self._details.clear()
self._details[oid] = (mod, det)
return det
def _items(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
"""하루씩 목록 → 결제된 주문만 주문정보까지 받아 {"row", "detail"}."""
ctx.progress.plan((end - start).days + 1, "일") # 진행 막대: 하루 = 한 단계
d = start
while d <= end:
rows = self._day_rows(ctx, d)
got = []
for r in rows:
if not r.get("orderId") or str(r.get("orderStatus") or "") in UNPAID_STATUS:
got.append({"row": r, "detail": {}})
continue
got.append({"row": r, "detail": self._detail(ctx, r)})
ctx.progress.step(items=len(rows))
yield from got
d += timedelta(days=1)
# ── 수집 ──────────────────────────────────────────────
def fetch_orders(self, ctx: AdapterContext, start: date, end: date) -> Iterable[dict[str, Any]]:
yield from group_payments(self._items(ctx, start, end), start, end).values()
def normalize_order(self, p: dict[str, Any]) -> list[SaleEvent]:
pid, day = str(p.get("paymentId") or ""), p.get("_day")
if not pid or day is None:
return []
names = p.get("names") or []
name = names[0] + (f" 외 {len(names) - 1}건" if len(names) > 1 else "") if names else ""
statuses = [STATUS_KO.get(s, s) for s in p.get("statuses") or []]
orders = p.get("orders") or []
return [SaleEvent(
event_type="SALE", external_event_id=f"{EVENT_PREFIX}{pid}", external_order_id=pid,
external_line_id=",".join(orders)[:100], order_date=p.get("order_day"), payment_date=day, event_date=day,
amount=max(0, int(p.get("amount") or 0)), product_name=name[:200], option_name=str(p.get("opt") or "")[:200],
quantity=int(p.get("qty") or 0), discount_amount=max(0, int(p.get("discount") or 0)),
order_status="/".join(statuses)[:50],
)]
def test_connection(self, ctx: AdapterContext) -> str:
from app.timezone import today_kst # noqa: WPS433
self.authenticate(ctx)
rows = self._day_rows(ctx, today_kst())
return f"카카오쇼핑 API 연결 정상(결제일 기준 주문 조회 확인, 오늘 결제 주문 {len(rows)}건)."
# ── 원본 데이터 확인(설정 화면 "쇼핑몰 원본 데이터 확인") ─────────
def reconcile(self, ctx: AdapterContext, day: date, to: date | None = None) -> dict[str, Any]:
"""결제일 기준 기간(최대 31일)의 주문과 주문정보를 실제로 불러 항목별 합계·상태별 합계·날짜별 현재 규칙 매출을
돌려준다(저장 안 함). 판매자센터 매출 화면과 어느 항목이 맞는지 실데이터로 확정하는 용도. 개인정보는 이름만."""
self.authenticate(ctx)
to = min(max(to or day, day), day + timedelta(days=PROBE_MAX_DAYS - 1))
try:
items = list(self._items(ctx, day, to))
except AdapterError as exc:
return {"date": day.isoformat(), "to": to.isoformat(), "probes": [
{"key": "paid", "label": "결제일 기준 주문", "path": PAID_PATH, "ok": False, "error": exc.message[:300]}]}
flat = [{**flatten(it["row"], "list"), **flatten(it["detail"])} for it in items]
probes = [{"key": "paid", "label": "결제일 기준 주문 + 주문정보(전체 상태)", "path": f"{PAID_PATH} → {ORDER_PATH}",
"ok": True, "count": len(items), "fields": field_summary(flat)}]
by_status: dict[str, list[dict[str, str]]] = {}
for it, f in zip(items, flat):
by_status.setdefault(str(it["row"].get("orderStatus") or "?"), []).append(f)
for st, rows in sorted(by_status.items()):
probes.append({"key": f"status-{st}", "label": f"상태 {STATUS_KO.get(st, st)}({st})"
+ (" — 매출 제외(미결제)" if st in UNPAID_STATUS else
" — 결제 뒤 취소·반품(매출 포함)" if st in CLAIMED_STATUS else ""), "path": "orderStatus",
"ok": True, "count": len(rows),
"fields": [f for f in field_summary(rows)
if f["sum"] is not None and f["name"].startswith("orderProduct.")]})
pays = group_payments(items, day, to)
days = []
d = day
while d <= to:
day_pays = [p for p in pays.values() if p["_day"] == d]
days.append({"date": d.isoformat(), "orders": len(day_pays), "amount": sum(p["amount"] for p in day_pays),
"claimed": sum(p["claimed"] for p in day_pays), "ship": sum(p["ship"] for p in day_pays)})
d += timedelta(days=1)
return {"date": day.isoformat(), "to": to.isoformat(), "probes": probes, "days": days,
"rule": "결제일 기준 주문의 (상품가 + 옵션가) × 수량 − 판매자 할인 − 판매자 쿠폰 − 카카오 할인 합(배송비 제외, "
"결제 뒤 취소·반품분 포함, 미결제 제외). 판매자센터 매출과 대조 전 — 표의 항목 합계로 확인"}
@@ -1772,6 +1772,158 @@ def test_gsshop_collect_sales():
assert rec["days"][1]["amount"] == -17000 and rec["days"][1]["claimed"] == 17000
def _kakao_detail(oid, pid, paid, price, qty=1, opt=0, sdc=0, cdc=0, adc=0, ship=3000, status="ShippingProgress"):
return {"id": oid,
"orderBase": {"id": oid, "paymentId": pid, "status": status, "createdAt": paid, "paidAt": paid,
"modifiedAt": paid},
"orderer": {"phoneNumber": "010-1234-5678"},
"orderProduct": {"id": oid, "name": "미라클통", "optionContent": "3200ml", "quantity": qty,
"productPrice": price, "optionPrice": opt, "sellerDiscountPrice": sdc,
"sellerCouponDiscountPrice": cdc, "adminDiscountPrice": adc, "deliveryAmount": ship,
"areaAdditionalDeliveryAmount": 0},
"orderDeliveryRequest": {"receiverName": "홍길동", "receiverAddress1": "서울 반품동", "requirement": "문 앞"},
"orderClaimReturn": {"claimItemStatus": "RETURN_COMPLETE", "pickupName": "홍길동", "reasonComment": "변심"}}
def test_kakao_connection_headers_and_errors():
"""카카오: kapi.kakao.com + Authorization(앱 어드민 키)·Target-Authorization(판매자 인증키)·channel-ids 헤더.
-2(두 키가 같은 앱)·-401(판매자 키 무효)·403 은 인증 실패, 키 값은 메시지에 없음."""
import httpx
from app.modules.performance.adapters import kakao as kk
from app.modules.performance.adapters.base import AdapterContext, NotConfigured
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="kakao", credentials=Creds(admin_key="ADMIN-SECRET", api_key="SELLER-SECRET"))
seen = {}
def ok(url, params=None, headers=None, timeout=None):
seen.update(url=url, params=params, headers=headers)
return httpx.Response(200, json={"contents": [{"orderId": 1, "paymentId": 9, "orderStatus": "PayComplete"}]})
orig, orig_iv = httpx.get, kk.CALL_INTERVAL_SEC
kk.CALL_INTERVAL_SEC = 0
try:
httpx.get = ok
msg = kk.KakaoAdapter().test_connection(ctx)
assert "연결 정상" in msg and "1건" in msg
assert seen["url"] == "https://kapi.kakao.com/v2/shopping/orders/paidAt"
assert seen["headers"]["Authorization"] == "KakaoAK ADMIN-SECRET"
assert seen["headers"]["Target-Authorization"] == "KakaoAK SELLER-SECRET"
assert seen["headers"]["channel-ids"] == "101" # 기본 톡스토어
assert seen["params"]["from"].endswith(" 00:00:00") and seen["params"]["to"].endswith(" 23:59:59")
ctx2 = AdapterContext(code="kakao", credentials=Creds(admin_key="A", api_key="S", channel_ids=" 1, 101 "))
kk.KakaoAdapter().test_connection(ctx2)
assert seen["headers"]["channel-ids"] == "1,101"
for status, body, kind, word in (
(401, {"msg": "invalid authorization or target-authorization header.", "code": -2}, AuthFailed, "서로 다른 앱"),
(401, {"msg": "appKey(판매자인증키) is already deactivated", "code": -401}, AuthFailed, "판매자 API 인증키"),
(400, {"code": -800, "msg": "대행사 매핑/권한 확인이 필요합니다."}, AuthFailed, "연결되지 않았습니다"),
(403, {"code": -3, "msg": "forbidden"}, AuthFailed, "403"),
(500, {"code": -500, "msg": "internal"}, ApiError, "500")):
httpx.get = (lambda s, b: lambda url, params=None, headers=None, timeout=None: httpx.Response(s, json=b))(status, body)
try:
kk.KakaoAdapter().test_connection(ctx)
except kind as exc:
assert word in exc.message and "ADMIN-SECRET" not in exc.message and "SELLER-SECRET" not in exc.message
else:
raise AssertionError("오류여야 합니다")
finally:
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
try:
kk.KakaoAdapter().test_connection(AdapterContext(code="kakao", credentials=Creds(api_key="S")))
except NotConfigured:
pass
else:
raise AssertionError("어드민 키 없으면 미설정")
def test_kakao_collect_sales():
"""카카오 매출 = 결제(paymentId) 하나, 결제일 기준, (상품가+옵션가)×수량 − 할인들, 배송비 제외.
목록(paidAt, token 으로 다음 쪽) → 주문정보(order_id). 미결제는 빼고 결제 뒤 취소는 포함. 개인정보 미저장."""
import httpx
from app.modules.performance.adapters import kakao as kk
from app.modules.performance.adapters.base import AdapterContext
details = {
11: _kakao_detail(11, 900, "20261001101500", 10000, qty=2, opt=1000, sdc=500, cdc=1000, adc=500), # 22000-2000
12: _kakao_detail(12, 900, "20261001101500", 5000), # 같은 결제
13: _kakao_detail(13, 901, "20261001200000", 7000, status="PayCancelComplete"), # 결제 뒤 취소
15: _kakao_detail(15, 903, "20261002090000", 3000),
}
rows = {
"2026-10-01": [[{"orderId": 11, "paymentId": 900, "orderStatus": "ShippingProgress", "paidAt": "20261001101500",
"modifiedAt": "20261001110000"},
{"orderId": 12, "paymentId": 900, "orderStatus": "ShippingProgress", "paidAt": "20261001101500",
"modifiedAt": "20261001110000"}],
[{"orderId": 13, "paymentId": 901, "orderStatus": "PayCancelComplete", "paidAt": "20261001200000",
"modifiedAt": "20261001210000"},
{"orderId": 14, "paymentId": 902, "orderStatus": "PayWaiting", "paidAt": "",
"modifiedAt": "20261001210000"}]],
"2026-10-02": [[{"orderId": 15, "paymentId": 903, "orderStatus": "BuyDecision", "paidAt": "20261002090000",
"modifiedAt": "20261002090000"}]],
}
calls = []
def get(url, params=None, headers=None, timeout=None):
calls.append((url.rsplit("/", 1)[-1], dict(params)))
if url.endswith("/v1/shopping/order"):
return httpx.Response(200, json=details[int(params["order_id"])])
pages = rows.get(params["from"][:10], [[]])
i = int(params.get("token") or 0)
body = {"contents": pages[i]}
if i + 1 < len(pages):
body["token"] = str(i + 1)
return httpx.Response(200, json=body)
st = FakeStore()
creds = CredentialService(st, lambda: ring())
creds.save(next(a for a in all_adapters() if a.code == "kakao"), {"admin_key": "ADMIN", "api_key": "SELLER"})
orig, orig_iv = httpx.get, kk.CALL_INTERVAL_SEC
httpx.get, kk.CALL_INTERVAL_SEC = get, 0
try:
r = SyncService(st, creds).sync_marketplace("kakao", date(2026, 10, 1), date(2026, 10, 2))
finally:
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
assert r["ok"], r
ev_ = {k[2]: v for k, v in st.events.items() if k[0] == "kakao"}
assert set(ev_) == {"kakao:900", "kakao:901", "kakao:903"} # 미결제 902 제외
a = ev_["kakao:900"]
assert a["amount"] == (10000 + 1000) * 2 - 2000 + 5000 and a["sales_date"] == date(2026, 10, 1)
assert a["discount_amount"] == 2000 and a["quantity"] == 3 and a["product_name"] == "미라클통"
assert ev_["kakao:901"]["amount"] == 7000 # 결제 뒤 취소도 결제일 매출(네이버와 같은 기준)
assert ev_["kakao:903"]["sales_date"] == date(2026, 10, 2)
assert not any(c[0] == "order" and c[1]["order_id"] == "14" for c in calls) # 미결제는 주문정보도 안 부름
assert [c[1].get("token") for c in calls if c[0] == "paidAt"] == [None, "1", None] # 다음 쪽 token
assert "홍길동" not in repr(st.events) and "010-1234-5678" not in repr(st.events)
# 원본 데이터 확인 — 개인정보는 값 없이 이름만, 날짜별 현재 규칙 매출
ad = kk.KakaoAdapter()
httpx.get, kk.CALL_INTERVAL_SEC = get, 0
try:
rec = ad.reconcile(AdapterContext(code="kakao", credentials=creds.accessor("kakao")), date(2026, 10, 1),
to=date(2026, 10, 2))
n = len(calls)
ad.reconcile(AdapterContext(code="kakao", credentials=creds.accessor("kakao")), date(2026, 10, 1))
assert not [c for c in calls[n:] if c[0] == "order"] # 수정일이 같으면 주문정보 캐시
finally:
httpx.get, kk.CALL_INTERVAL_SEC = orig, orig_iv
assert rec["days"][0] == {"date": "2026-10-01", "orders": 2, "amount": 25000 + 7000, "claimed": 7000, "ship": 9000}
assert rec["days"][1]["amount"] == 3000
f = {x["name"]: x for x in rec["probes"][0]["fields"]}
assert f["orderProduct.productPrice"]["sum"] == 10000 + 5000 + 7000 + 3000
assert f["orderDeliveryRequest.receiverName"]["sample"] == "" and f["orderer.phoneNumber"]["sample"] == ""
assert "홍길동" not in repr(rec) and "반품동" not in repr(rec) and "010-1234-5678" not in repr(rec)
assert "변심" not in repr(rec) and "문 앞" not in repr(rec)
def test_sync_job_cancel():
"""[업데이트 취소]: 수집 중인 쇼핑몰은 다음 API 호출 직전에 멈추고 저장하지 않는다(기존 매출 그대로),
차례가 안 온 쇼핑몰은 취소됨으로 건너뛴다. 연결 상태(오류)는 기록하지 않는다."""
+16 -1
View File
@@ -29,7 +29,7 @@
오류 클래스 = 연결 상태: `NotConfigured`(인증정보 미설정) · `AuthFailed`(인증 실패) · `TokenExpired` · `ApiError` · `NotImplementedYet`(연동 준비 중).
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑·쿠팡 = **구현됨**(쿠팡은 2026-10-12 — 매출 규칙은 WING 실데이터 대조 전), 나머지 4개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
**연동 현황**: 카페24·11번가·네이버 스마트스토어·GS샵·토스쇼핑·쿠팡·카카오 = **구현됨**(쿠팡은 2026-10-12 — 매출 규칙은 WING 실데이터 대조 전, 카카오는 2026-10-13 — 판매자센터 대조 전), 나머지 3개는 입력칸만 정의(수집은 `NotImplementedYet`). 쇼핑몰별 입력칸은
**연동 단계에서 공식 API 문서로 확정**한다.
### 카페24 (`adapters/cafe24.py`, 구현됨)
@@ -204,6 +204,21 @@
④ 취소분 뺀 값 ⑤ 로켓그로스 + 판매량 — 를 WING 판매분석의 같은 날 "매출(원)"·"판매량" 과 비교해 규칙을 확정한다(`candidates_title`).
로켓그로스만 거부돼도 판매자배송 결과는 보인다.
### 카카오 (`adapters/kakao.py`, 구현됨 — 판매자센터 대조 전, 2026-10-13)
- 카카오쇼핑 Open API(shopping-developers.kakao.com). 주소 `https://kapi.kakao.com`, 모든 호출에 헤더 3개:
`Authorization: KakaoAK {앱 어드민 키}`(카카오쇼핑 API 허락된 카카오디벨로퍼스 앱) ·
`Target-Authorization: KakaoAK {판매자 API 인증키}`(판매자센터 → 정보관리 → 판매채널 정보 → API 인증키) ·
`channel-ids: 101`(톡스토어, 선물하기 1, 둘 다 `1,101`). 입력칸 `admin_key`·`api_key`(처음 입력칸 이름 유지)·`channel_ids`(선택).
두 키가 같은 앱이면 code -2, 판매자 키 무효면 -401, 앱-판매자 연결 전이면 "대행사 매핑/권한 확인" → 모두 인증 실패로 안내.
Open API 는 카카오쇼핑 검토(“API 연동 검토 요청”)로 허락된 앱만 쓸 수 있다.
- 수집: 결제일시 기준 주문내역 `GET /v2/shopping/orders/paidAt?from=&to=&size=100`(24시간까지 — 하루씩, 다음 쪽 `token`) →
금액이 없어 결제된 주문마다 주문정보 `GET /v1/shopping/order?order_id=`(목록 `modifiedAt` 이 같으면 메모리 캐시 재사용).
- 사건: 결제(`paymentId`) 하나 = SALE `kakao:{paymentId}`, 날짜 = 결제일. 금액 = 상품 줄마다
`(productPrice + optionPrice) × quantity − sellerDiscountPrice − sellerCouponDiscountPrice − adminDiscountPrice` 합, 배송비 제외.
미결제(Created·PayRequest·PayWaiting·PayChecking·PayFailed·UnpaidCancelComplete)만 빼고 결제 뒤 취소·반품은 포함(네이버와 같은 기준).
`replace_range`. 문서에 결제금액 항목이 없어 만든 식이라 **원본 데이터 확인의 항목 합계로 판매자센터 매출과 대조해 확정**한다.
- 개인정보(`orderer`·`orderDeliveryRequest`·`orderTicketReceiver`, 클레임의 수거·교환 이름·주소·연락처·사유 글)는 받자마자 값을 지운다.
### 수동 입력(마이그레이션 002, 2026-10-12)
- 설정 → 쇼핑몰 표 **수동 입력** 토글(관리자, `perf_marketplaces.manual_input`, 기본 꺼짐). 켜면 실적 일자별 표에서 그 쇼핑몰의