Merge branch 'fix/google-ads-no-dev-token'

This commit is contained in:
2026-10-15 15:20:22 +09:00
4 changed files with 30 additions and 25 deletions
+1 -1
View File
File diff suppressed because one or more lines are too long
@@ -1,11 +1,14 @@
"""구글 광고(Google Ads API) — 날짜별 광고비·ROAS·보고서 항목.
인증(2026-10-15 사용자: 서비스 계정 + 개발자 토큰 Explorer 승인)
인증(2026-10-15 사용자: 서비스 계정 Explorer 승인)
- 서비스 계정 JSON 키로 OAuth 액세스 토큰(scope adwords)을 받는다 — JWT 를 google-auth 로 서명하고 토큰 교환은 httpx.
서비스 계정 이메일을 구글 광고 계정(또는 관리자 MCC 계정) → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다
(2024-11 부터 도메인 전체 위임 없이 직접 추가 가능).
- 요청 머리글: Authorization(Bearer) · developer-token · login-customer-id(MCC 를 거쳐 들어갈 때만).
- 개발자 토큰 Explorer 등급은 운영 계정 조회(보고서)가 되고 하루 작업 수 한도가 있다 — 우리는 가져오기 한 번에 요청 1~2개.
- **개발자 토큰은 2026-09-09 폐지** — API 접근 등급(Explorer 등)은 서비스 계정을 가진 Google Cloud 프로젝트에 붙는다
(Cloud Console → Google Ads API Overview 에서 신청). developer-token 머리글은 지금은 무시되고 다음 큰 버전부터 거부되므로
보내지 않는다(입력칸도 없음, 예전에 저장한 값은 쓰지 않음).
- 요청 머리글: Authorization(Bearer) · login-customer-id(MCC 를 거쳐 들어갈 때만).
- Explorer 등급은 운영 계정 조회(보고서)가 되고 하루 작업 수 한도가 있다 — 우리는 가져오기 한 번에 요청 1~2개.
조회(REST googleAds:searchStream, GAQL)
SELECT customer.currency_code, segments.date, metrics.cost_micros, metrics.impressions, metrics.clicks,
@@ -43,9 +46,9 @@ M_COST, M_IMPR, M_CLICKS, M_CTR, M_CONV, M_VALUE, M_ROAS = "비용", "노출수"
# 구글 오류 코드 → 고칠 곳 안내(오류 문구 뒤에 붙임)
_HINTS = {
"DEVELOPER_TOKEN_NOT_APPROVED": "개발자 토큰이 테스트 계정 전용입니다. API 센터에서 Explorer 이상 승인을 받은 토큰인지 확인하세요.",
"DEVELOPER_TOKEN_PROHIBITED": "이 개발자 토큰은 이 Google Cloud 프로젝트에서 쓸 수 없습니다(토큰을 받은 MCC·프로젝트 확인).",
"DEVELOPER_TOKEN_INVALID": "개발자 토큰이 올바르지 않습니다.",
"CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION": "서비스 계정이 속한 Google Cloud 프로젝트에 운영 계정 접근 승인이 없습니다. "
"Cloud Console → Google Ads API Overview 에서 그 프로젝트의 Explorer 이상 승인을 확인하세요.",
"AUTHORIZATION_ERROR": "API 접근 승인 문제입니다. 서비스 계정이 속한 Cloud 프로젝트의 Google Ads API 승인 상태를 확인하세요.",
"USER_PERMISSION_DENIED": "서비스 계정이 이 광고 계정에 권한이 없습니다. 구글 광고 → 관리 → 액세스 및 보안에 서비스 계정 이메일을 "
"사용자로 추가했는지, 관리자(MCC) 계정에 추가했다면 [로그인 고객 ID]에 MCC 번호를 넣었는지 확인하세요.",
"CUSTOMER_NOT_ENABLED": "광고 계정이 사용 중지(취소·미완료) 상태입니다.",
@@ -123,13 +126,12 @@ class GoogleAdsSource(AdSource):
name = "구글 광고"
docs_url = "https://developers.google.com/google-ads/api/docs/oauth/service-accounts"
note = ("구글 광고 API 로 날짜별 광고비(비용)·ROAS(전환 가치 ÷ 비용)·노출수·클릭수·전환을 가져옵니다. "
"준비: ① Google Cloud 서비스 계정 JSON 키 ② 구글 광고 API 센터의 개발자 토큰(Explorer 이상) "
"③ 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 서비스 계정 이메일 추가(읽기 권한이면 충분).")
"준비: ① Google Cloud 서비스 계정 JSON 키(그 Cloud 프로젝트가 Google Ads API Explorer 이상 승인) "
"② 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 서비스 계정 이메일 추가(읽기 권한이면 충분). "
"개발자 토큰은 2026-09-09 폐지돼 필요 없습니다.")
def credential_fields(self) -> list[CredentialField]:
return [
CredentialField("developer_token", "개발자 토큰", secret=True,
help="구글 광고 관리자(MCC) → 도구 → API 센터의 개발자 토큰. Explorer 이상 승인이어야 운영 계정을 조회할 수 있습니다."),
CredentialField("customer_id", "고객 ID(광고 계정)", placeholder="123-456-7890",
help="광고비를 가져올 광고 계정 번호(구글 광고 화면 오른쪽 위). 하이픈은 있어도 됩니다."),
CredentialField("login_customer_id", "로그인 고객 ID(MCC)", required=False, placeholder="비워 두면 광고 계정에 직접 접근",
@@ -204,8 +206,7 @@ class GoogleAdsSource(AdSource):
version = (ctx.credentials.get("api_version") or "").strip() or DEFAULT_VERSION
with _http(ctx) as client:
token = self._access_token(ctx, client)
headers = {"Authorization": f"Bearer {token}", "developer-token": ctx.credentials.get("developer_token").strip(),
"Content-Type": "application/json"}
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} # 개발자 토큰 없음(2026-09-09 폐지)
login = _digits(ctx.credentials.get("login_customer_id"))
if login:
headers["login-customer-id"] = login
@@ -50,7 +50,7 @@ class Creds:
def _ctx(**over):
values = {"developer_token": "DEVTOKEN", "customer_id": "123-456-7890", "service_account_json": SA}
values = {"customer_id": "123-456-7890", "service_account_json": SA}
values.update(over)
return AdapterContext(code="google", credentials=Creds(values))
@@ -86,9 +86,10 @@ ROWS = [{"results": [
def test_validate_credentials():
src = ga.GoogleAdsSource()
ok = {"developer_token": "x", "customer_id": "123-456-7890", "service_account_json": SA}
ok = {"customer_id": "123-456-7890", "service_account_json": SA}
assert src.validate_credentials(ok) == []
assert src.validate_credentials({**ok, "service_account_json": "__stored__", "developer_token": "__stored__"}) == []
assert src.validate_credentials({**ok, "service_account_json": "__stored__"}) == []
assert "developer_token" not in {f.key for f in src.visible_fields()} # 개발자 토큰 폐지(2026-09-09) — 입력칸 없음
errs = src.validate_credentials({**ok, "customer_id": "12345", "login_customer_id": "abc", "api_version": "26",
"service_account_json": '{"type": "authorized_user"}'})
assert len(errs) == 4 and not any("BEGIN" in e for e in errs) # 키 내용은 문구에 없음
@@ -102,7 +103,7 @@ def test_fetch_days_converts_and_sends_headers(monkeypatch):
date(2026, 10, 1), date(2026, 10, 3))
api = seen[-1]
assert str(api.url) == "https://googleads.googleapis.com/v27/customers/1234567890/googleAds:searchStream"
assert api.headers["Authorization"] == "Bearer ya29.TOKEN" and api.headers["developer-token"] == "DEVTOKEN"
assert api.headers["Authorization"] == "Bearer ya29.TOKEN" and "developer-token" not in api.headers # 폐지된 머리글은 보내지 않음
assert api.headers["login-customer-id"] == "9998887777"
q = json.loads(api.content)["query"]
assert "segments.date BETWEEN '2026-10-01' AND '2026-10-03'" in q and "metrics.conversions_value" in q
@@ -174,11 +175,11 @@ def test_ad_credentials_use_own_namespace():
t = Table()
svc = CredentialService(t, lambda: ring, aad_ns=ad_sync.AD_NS)
svc.save(ga.GoogleAdsSource(), {"developer_token": "DEV", "customer_id": "1234567890"}, user="king")
assert svc.accessor("google").get("developer_token") == "DEV"
assert aad_for("google", "developer_token", "ad:") == "perf:ad:google:developer_token"
svc.save(ga.GoogleAdsSource(), {"service_account_json": SA, "customer_id": "1234567890"}, user="king")
assert svc.accessor("google").get("service_account_json") == SA
assert aad_for("google", "service_account_json", "ad:") == "perf:ad:google:service_account_json"
with pytest.raises(Exception):
crypto.decrypt(t.rows[("google", "developer_token")], aad=aad_for("google", "developer_token"), ring=ring)
crypto.decrypt(t.rows[("google", "service_account_json")], aad=aad_for("google", "service_account_json"), ring=ring)
class FakeStore:
@@ -186,7 +187,7 @@ class FakeStore:
self.replaced, self.status = [], []
def ad_credential_keys_by_code(self):
return {"google": {"developer_token", "customer_id", "service_account_json"}}
return {"google": {"customer_id", "service_account_json"}}
def ad_credential_rows(self, code):
return {}
@@ -222,11 +223,11 @@ def test_sync_service_saves_and_records(monkeypatch):
# 실패: 저장 안 하고 상태에 오류(저장된 비밀값은 가림)
def boom(ctx, s, e):
raise AuthFailed("토큰 DEVTOKEN 거부")
raise AuthFailed("거부된 값 123-456-7890")
monkeypatch.setattr(src, "fetch_days", boom)
res = svc.sync("google", date(2026, 10, 1), date(2026, 10, 1))
assert not res["ok"] and res["status"] == "auth_failed" and "DEVTOKEN" not in res["message"]
assert not res["ok"] and res["status"] == "auth_failed" and "123-456-7890" not in res["message"] # 꺼낸 인증정보 값은 가림
assert len(store.replaced) == 1 and store.status[-1][1:3] == ("auth_failed", False)
# 같은 채널 동시 실행 막기
+4 -1
View File
@@ -372,9 +372,12 @@
`perf_ad_credentials`(쇼핑몰 표는 `perf_marketplaces` 에 FK 로 묶여 있음), 암호문 AAD 이름 공간 `perf:ad:{채널}:{항목}`
(`credentials.aad_for(…, ns)` — 쇼핑몰 암호문과 바꿔 넣어도 복호화 안 됨). 비밀 원문은 화면으로 다시 보내지 않음.
[현재 키로 다시 암호화]·저장된 항목 수에 광고 인증정보도 포함. 연결 상태·마지막 가져오기는 `perf_ad_source_status`.
- **구글 광고**(`ad_sources/google_ads.py`): 입력 = 개발자 토큰(Explorer 이상, 비밀) · 고객 ID(광고 계정 10자리) ·
- **구글 광고**(`ad_sources/google_ads.py`): 입력 = 고객 ID(광고 계정 10자리) ·
로그인 고객 ID(MCC 를 거칠 때만) · 서비스 계정 키 JSON(비밀, 여러 줄) · API 버전(기본 `v26`, 구글이 종료 알리면 설정에서 올림).
서비스 계정 이메일을 구글 광고 → 관리 → 액세스 및 보안 → 사용자에 추가해 두어야 한다(도메인 위임 불필요, 2024-11~).
**개발자 토큰은 2026-09-09 폐지**(구글) — 접근 등급(Explorer 등)은 서비스 계정을 가진 Google Cloud 프로젝트에 붙고
Cloud Console → Google Ads API Overview 에서 신청. `developer-token` 머리글은 무시되며 다음 큰 버전부터 거부라 보내지 않는다(입력칸 없음).
승인 없는 프로젝트 = `CLOUD_PROJECT_NOT_APPROVED_FOR_PRODUCTION`(안내 문구 붙음).
토큰 = 서비스 계정 JWT(google-auth 서명) → `oauth2.googleapis.com/token`(httpx), 프로세스 안 캐시(만료 2분 전까지).
조회 = REST `googleAds:searchStream` GAQL `FROM customer` + `segments.date BETWEEN`(계정 시간대), 요청 1번.
금액 = `cost_micros ÷ 10⁶` 원 반올림(**부가세 별도** — 쿠팡은 부가세 포함이라 기준이 다름), ROAS = 전환 가치 ÷ 비용 × 100(소수 둘째),