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
@@ -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 호출 직전에 멈추고 저장하지 않는다(기존 매출 그대로),
차례가 안 온 쇼핑몰은 취소됨으로 건너뛴다. 연결 상태(오류)는 기록하지 않는다."""