앱 - 전면 광고: 판 수를 기기에 저장해 앱을 다시 켜도 이어 센다. 규칙은 "마지막 전면 뒤 3판 이상 + 세션 첫 판 제외" - 보상형 광고: 30분 전면 끄기, TIME ATTACK 이어하기(1판 1회, 기록·리더보드 미반영), 리소 스킨·흑연 보드 해금 - Play Billing 9.1: remove_ads / supporter_pack(비소모) / season_pass(소모). 승인 즉시, 시즌 패스는 서버 적용 뒤 소비, 실행 때마다 복원 - 상점 탭: 시즌 패스 트랙, 블록 스킨 7종·보드 테마 5종, 배지 장착, 상품, 구매 복원 - 광고 제거 구매 시 배너·결과·전면 끔 (보상형은 선택지로 유지) - AdMob 미디에이션 어댑터: AppLovin, Pangle - 커스텀 방 초대 링크 https://tetrig.pages.dev/r/CODE (앱 링크) + 공유, 결과 카드 PNG 공유 - 로비·리더보드·프로필에 배지 표시 서버 - 0002_shop 마이그레이션: season_xp, user_items, purchases, users.badge - 시즌 패스 XP(솔로 10/커스텀 20+10/리그 25+15), 30레벨 무료·프리미엄 트랙 - /api/pass, /api/purchase(Google Play Developer API 검증, PLAY_SA_KEY), /api/badge - 게스트 병합·계정 삭제 시 패스·아이템·구매 이전/삭제 웹 - /r/<코드> 초대 안내 페이지, scripts/build-pages.sh, 개인정보처리방침·스토어 문구 갱신 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
89 lines
3.8 KiB
JavaScript
89 lines
3.8 KiB
JavaScript
// 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-<state>-..." 토큰을 받아 준다.
|
|
*/
|
|
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");
|
|
}
|