o2o-site-AEO/solution/backend/services/external/threads.py
hbyang 6badd5c9f0 [fix] solution/backend: 플랫폼 거절에 사유를 붙인다 — THREADS_REJECTED_400 만으로는 못 고친다
연동이 실패했는데 로그에 `THREADS_REJECTED_400` 만 남았다. 코드가 만료됐는지, 리디렉션
URI 가 안 맞는지, 권한이 모자란지 구별이 안 돼 원인을 세 번 헛짚었다(실측 2026-09-18).
Meta 는 응답 본문에 `error.message` 와 `error_subcode` 로 이유를 정확히 말해 주는데,
우리가 그걸 읽고 버리고 있었다.

- external/threads._read: 거절 코드 뒤에 `[subcode] message` 를 붙인다
- ★ 담는 것은 message·subcode 뿐이다. 토큰·시크릿·인가 code 는 담지 않는다 —
  이 문자열은 로그로 가고 로그는 우리가 아닌 사람도 본다. message 는 160자에서 끊는다

검증: SNS 테스트 14건 통과. 실제 호출로 엔드포인트·자격증명이 정상임을 먼저 확인했다
(더미 code 로 `Invalid verification code` 응답 · debug_token·장기토큰 교환 호출 모양 정상)

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-18 13:26:38 +09:00

190 lines
6.9 KiB
Python

"""Meta 공식 Threads API. 장기 액세스 토큰을 갱신하며 X의 refresh-token 계약을 요구하지 않는다."""
from config import social_config as config
from urllib.parse import urlencode, urlparse
import httpx
from services.external.social import SocialError, SocialOutcomeUnknown, weighted_length
BASE = "https://graph.threads.net/v1.0"
SCOPES = {"threads_basic", "threads_content_publish"}
def is_configured():
return all(
config.get(k)
for k in ("THREADS_APP_ID", "THREADS_APP_SECRET", "THREADS_REDIRECT_URI")
)
def weighted_limit():
return 500
def authorize_url(state, verifier):
# Threads는 서버측 코드 교환이다. X 전용 PKCE 파라미터를 전송하지 않는다.
return "https://threads.net/oauth/authorize?" + urlencode(
dict(
client_id=config.required("THREADS_APP_ID"),
redirect_uri=config.required("THREADS_REDIRECT_URI"),
response_type="code",
scope=",".join(sorted(SCOPES)),
state=state,
)
)
def _read(res):
try:
data = res.json()
except ValueError as ex:
raise SocialError("THREADS_INVALID_RESPONSE") from ex
if res.status_code >= 400 or data.get("error"):
error = data.get("error") or {}
# ★ 플랫폼이 준 사유를 코드에 붙인다. `THREADS_REJECTED_400` 만으로는 무엇이 틀렸는지
# 알 수 없어서 — 코드가 만료됐는지, 리디렉션 URI 가 안 맞는지, 권한이 모자란지 —
# 실제로 원인을 좁히지 못했다(실측 2026-09-18: 연결 실패가 400 이라는 것만 알고
# Meta 가 뭐라고 했는지는 어디에도 안 남아 세 번을 헛짚었다).
# ★ 남기는 것은 message·subcode 뿐이다. 토큰·시크릿·code 는 담지 않는다 —
# 이 문자열은 로그로 가고, 로그는 우리가 아닌 사람도 본다.
detail = str(error.get("message") or "")[:160]
subcode = error.get("error_subcode") or error.get("code")
raise SocialError(
f"THREADS_REJECTED_{res.status_code}"
+ (f"[{subcode}]" if subcode else "")
+ (f" {detail}" if detail else ""),
reauth=error.get("code") == 190 or res.status_code == 401,
)
return data
async def exchange(code, verifier, *, client):
short = _read(
await client.post(
f"{BASE}/oauth/access_token",
data={
"client_id": config.required("THREADS_APP_ID"),
"client_secret": config.required("THREADS_APP_SECRET"),
"grant_type": "authorization_code",
"redirect_uri": config.required("THREADS_REDIRECT_URI"),
"code": code,
},
)
)
result = _read(
await client.get(
f"{BASE}/access_token",
params={
"grant_type": "th_exchange_token",
"client_secret": config.required("THREADS_APP_SECRET"),
},
headers={"Authorization": f"Bearer {short['access_token']}"},
)
)
token = result["access_token"]
debug = _read(
await client.get(
f"{BASE}/debug_token",
params={"input_token": token},
headers={
"Authorization": f"Bearer TH|{config.required('THREADS_APP_ID')}|{config.required('THREADS_APP_SECRET')}"
},
)
)["data"]
if (
not debug.get("is_valid")
or str(debug.get("app_id")) != config.required("THREADS_APP_ID")
or not SCOPES.issubset(set(debug.get("scopes", [])))
):
raise SocialError("THREADS_SCOPES_REQUIRED", reauth=True)
if int(result.get("expires_in", 0)) < 86400:
raise SocialError("THREADS_LONG_LIVED_TOKEN_REQUIRED", reauth=True)
result["scope"] = " ".join(sorted(SCOPES))
return result
async def refresh(token, *, client):
result = _read(
await client.get(
f"{BASE}/refresh_access_token",
params={"grant_type": "th_refresh_token"},
headers={"Authorization": f"Bearer {token}"},
)
)
if not result.get("access_token") or int(result.get("expires_in", 0)) <= 0:
raise SocialError("THREADS_REFRESH_FAILED", reauth=True)
result["scope"] = " ".join(sorted(SCOPES))
return result
async def me(token, *, client):
data = _read(
await client.get(
f"{BASE}/me",
params={"fields": "id,username"},
headers={"Authorization": f"Bearer {token}"},
)
)
return {
"id": data["id"],
"handle": data["username"],
"profile_url": f"https://www.threads.com/@{data['username']}",
}
async def publish(text, token, *, client):
if weighted_length(text, 2) > weighted_limit():
raise SocialError("TEXT_TOO_LONG")
headers = {"Authorization": f"Bearer {token}"}
# 컨테이너 생성은 아직 게시가 아니다. auto_publish_text를 켜면 이 구분이 사라진다.
try:
container = _read(
await client.post(
f"{BASE}/me/threads",
headers=headers,
data={"media_type": "TEXT", "text": text, "auto_publish_text": "false"},
)
)
container_id = container["id"]
except (httpx.TransportError, KeyError, TypeError) as ex:
raise SocialError("THREADS_CONTAINER_FAILED") from ex
try:
res = await client.post(
f"{BASE}/me/threads_publish",
headers=headers,
data={"creation_id": container_id},
)
if res.status_code >= 500 or res.status_code == 408:
raise SocialOutcomeUnknown("POST_RESULT_UNKNOWN")
# 성공 응답 파싱 실패·permalink 조회 실패도 이미 게시했을 수 있으므로 재전송 금지.
if res.status_code >= 400:
_read(res)
data = res.json()
post_id = str(data["id"])
if not post_id.isdigit():
raise ValueError()
except SocialError:
raise
except (httpx.TransportError, ValueError, KeyError, TypeError) as ex:
raise SocialOutcomeUnknown("POST_RESULT_UNKNOWN") from ex
try:
detail = _read(
await client.get(
f"{BASE}/{post_id}", params={"fields": "permalink"}, headers=headers
)
)
permalink = detail["permalink"]
parsed = urlparse(permalink)
if parsed.scheme != "https" or parsed.hostname not in (
"www.threads.net",
"threads.net",
"www.threads.com",
"threads.com",
):
raise ValueError()
except (httpx.TransportError, SocialError, ValueError, KeyError, TypeError):
# 게시 ID는 확보했다. 링크 조회 실패를 게시 실패로 취급하면 사장님이 다시 올린다.
permalink = None
return {"id": post_id, "permalink": permalink}