// Google Play Developer API 로 인앱 구매 영수증을 확인한다. // 비밀값 PLAY_SA_KEY = 서비스 계정 JSON 키 전체 (Play Console 에서 "재무 데이터 보기" 권한을 준 계정). export const PACKAGE_NAME = "kr.tkrmagid.tetrig"; const enc = new TextEncoder(); function b64url(data) { const bytes = typeof data === "string" ? enc.encode(data) : new Uint8Array(data); let s = ""; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function pemToDer(pem) { const body = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, ""); const bin = atob(body); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out.buffer; } let cached = null; // { token, exp, email } async function accessToken(saJson) { const sa = JSON.parse(saJson); if (cached && cached.email === sa.client_email && cached.exp > Date.now() + 60_000) return cached.token; const now = Math.floor(Date.now() / 1000); const head = b64url(JSON.stringify({ alg: "RS256", typ: "JWT" })); const claim = b64url( JSON.stringify({ iss: sa.client_email, scope: "https://www.googleapis.com/auth/androidpublisher", aud: "https://oauth2.googleapis.com/token", iat: now, exp: now + 3600, }), ); const key = await crypto.subtle.importKey( "pkcs8", pemToDer(sa.private_key), { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"], ); const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, enc.encode(`${head}.${claim}`)); const r = await fetch("https://oauth2.googleapis.com/token", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: `${head}.${claim}.${b64url(sig)}`, }), }); if (!r.ok) throw new Error(`google oauth ${r.status}`); const j = await r.json(); cached = { token: j.access_token, exp: Date.now() + (j.expires_in ?? 3600) * 1000, email: sa.client_email }; return cached.token; } /** * 반환: { valid:false } (없는/남의 앱 토큰) 또는 * { valid:true, purchaseState(0 구매·1 취소·2 대기), consumptionState(0 미소비·1 소비), orderId, purchaseTime } * 네트워크/권한 오류는 throw (클라이언트는 나중에 다시 시도한다). * * 로컬 개발(wrangler dev)에서만 PLAY_VERIFY_FAKE=1 이면 "fake--..." 토큰을 받아 준다. */ export async function verifyPlayPurchase(env, productId, token, { local = false } = {}) { if (local && env.PLAY_VERIFY_FAKE === "1" && token.startsWith("fake-")) { const state = Number(token.split("-")[1]) || 0; return { valid: true, purchaseState: state, consumptionState: 0, orderId: `GPA.FAKE-${token.slice(-6)}`, purchaseTime: Date.now() }; } if (!env.PLAY_SA_KEY) throw new Error("PLAY_SA_KEY 미설정"); const at = await accessToken(env.PLAY_SA_KEY); const url = `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${PACKAGE_NAME}` + `/purchases/products/${encodeURIComponent(productId)}/tokens/${encodeURIComponent(token)}`; const r = await fetch(url, { headers: { Authorization: `Bearer ${at}` } }); if (r.status === 400 || r.status === 404 || r.status === 410) return { valid: false }; if (!r.ok) throw new Error(`play api ${r.status}`); const j = await r.json(); return { valid: true, purchaseState: j.purchaseState ?? 0, consumptionState: j.consumptionState ?? 0, orderId: j.orderId ?? null, purchaseTime: Number(j.purchaseTimeMillis) || Date.now(), }; } export function playVerifyConfigured(env, local = false) { return !!env.PLAY_SA_KEY || (local && env.PLAY_VERIFY_FAKE === "1"); }