122 lines
7.8 KiB
TypeScript
122 lines
7.8 KiB
TypeScript
// In-app products on Google Play through monetization.onetimeproducts (the legacy inappproducts API answers 403
|
|
// "Please migrate to the new publishing API" for apps on the new model).
|
|
// storebound play products [--dry] [--only id1,id2]
|
|
// Per product: convertRegionPrices (USD base -> every region at local price points, plus regionsVersion), your
|
|
// explicit overrides on top, PATCH ...?allowMissing=true (create or update), then activate the purchase option
|
|
// (new options start as DRAFT) with purchaseOptions:batchUpdateStates. Idempotent.
|
|
// Play has no non-renewing type: a `non_renewing` product is a plain one-time product here (your app consumes it
|
|
// when the access ends). Products with `platforms` that leave out android are skipped.
|
|
import { playCodes, sellsOn } from '../lib/config';
|
|
import type { Ctx } from '../lib/ctx';
|
|
import { need } from '../lib/ctx';
|
|
import { done, log, step, warn } from '../lib/log';
|
|
import { fromMoney, type Money, playRegionConfigs, type RegionConfig, toMoney } from '../lib/money';
|
|
import { playClient } from './client';
|
|
|
|
const OPTION = 'buy';
|
|
|
|
interface Converted {
|
|
convertedRegionPrices?: Record<string, { regionCode: string; price: Money }>;
|
|
convertedOtherRegionsPrice?: { usdPrice: Money; eurPrice: Money };
|
|
regionVersion?: { version: string };
|
|
}
|
|
type PlayMoney = Omit<Money, 'units'> & { units?: string };
|
|
export interface Existing {
|
|
productId: string;
|
|
listings?: { languageCode: string; title?: string; description?: string }[];
|
|
purchaseOptions?: { purchaseOptionId: string; state?: string; regionalPricingAndAvailabilityConfigs?: { regionCode: string; price?: PlayMoney; availability?: string }[];
|
|
newRegionsConfig?: { usdPrice?: PlayMoney; eurPrice?: PlayMoney; availability?: string } }[];
|
|
}
|
|
|
|
const money = (m?: PlayMoney): string => (m ? `${m.currencyCode} ${fromMoney(m).toFixed(2)}` : '-');
|
|
|
|
/**
|
|
* What a run would change on one product, from the product Play has now (oneTimeProducts list) and the body the run
|
|
* would PATCH. The PATCH replaces listings and purchase options, so a language on Play that is not in the config is
|
|
* removed. Prices are compared per region (currency and amount). Empty: nothing would change. Pure.
|
|
*/
|
|
export function productChanges(cur: Existing | undefined, want: { listings: { languageCode: string; title: string; description: string }[]; regions: RegionConfig[]; newRegions: { usdPrice: Money; eurPrice: Money } }): string[] {
|
|
if (!cur) return ['create'];
|
|
const out: string[] = [];
|
|
const have = new Map((cur.listings ?? []).map(l => [l.languageCode, l]));
|
|
const added = want.listings.filter(l => !have.has(l.languageCode)).map(l => l.languageCode);
|
|
const changed = want.listings.filter(l => { const h = have.get(l.languageCode); return h && ((h.title ?? '') !== l.title || (h.description ?? '') !== l.description); }).map(l => l.languageCode);
|
|
const removed = [...have.keys()].filter(c => !want.listings.some(l => l.languageCode === c));
|
|
if (added.length) out.push(`listings added: ${added.join(', ')}`);
|
|
if (changed.length) out.push(`listings changed: ${changed.join(', ')}`);
|
|
if (removed.length) out.push(`listings removed: ${removed.join(', ')}`);
|
|
const opt = cur.purchaseOptions?.find(o => o.purchaseOptionId === OPTION);
|
|
const now = new Map((opt?.regionalPricingAndAvailabilityConfigs ?? []).map(r => [r.regionCode, r]));
|
|
const prices = want.regions.flatMap(r => {
|
|
const h = now.get(r.regionCode)?.price;
|
|
return h && h.currencyCode === r.price.currencyCode && Math.round(fromMoney(h) * 100) === Math.round(fromMoney(r.price) * 100) ? [] : [`${r.regionCode} ${money(h)} -> ${money(r.price)}`];
|
|
});
|
|
const gone = [...now.keys()].filter(c => !want.regions.some(r => r.regionCode === c));
|
|
if (prices.length) out.push(`prices in ${prices.length} region(s): ${prices.slice(0, 6).join(', ')}${prices.length > 6 ? ', ...' : ''}`);
|
|
if (gone.length) out.push(`regions dropped: ${gone.join(', ')}`);
|
|
const nr = opt?.newRegionsConfig;
|
|
if (money(nr?.usdPrice) !== money(want.newRegions.usdPrice) || money(nr?.eurPrice) !== money(want.newRegions.eurPrice))
|
|
out.push(`other regions ${money(nr?.usdPrice)} / ${money(nr?.eurPrice)} -> ${money(want.newRegions.usdPrice)} / ${money(want.newRegions.eurPrice)}`);
|
|
if (opt?.state !== 'ACTIVE') out.push('purchase option activated');
|
|
return out;
|
|
}
|
|
|
|
export async function listOneTimeProducts(play: Awaited<ReturnType<typeof playClient>>): Promise<Existing[]> {
|
|
const out: Existing[] = [];
|
|
let page = '';
|
|
do {
|
|
// camelCase "oneTimeProducts" here; the lowercase path answers with an HTML 404
|
|
const r = await play.call<{ oneTimeProducts?: Existing[]; nextPageToken?: string }>('GET', `${play.API}/oneTimeProducts?pageSize=100${page ? '&pageToken=' + page : ''}`);
|
|
out.push(...(r.oneTimeProducts ?? []));
|
|
page = r.nextPageToken ?? '';
|
|
} while (page);
|
|
return out;
|
|
}
|
|
|
|
export async function run(ctx: Ctx): Promise<void> {
|
|
const { config, root } = ctx.loaded;
|
|
const pkg = need(config.play?.packageName, 'play.packageName');
|
|
const only = ctx.args.list('only');
|
|
const products = need(config.products, 'products').filter(p => (!only.length || only.includes(p.id)) && sellsOn(config, p, 'play'));
|
|
const dry = ctx.args.has('dry');
|
|
const play = await playClient(root, pkg);
|
|
const existing = new Map((await listOneTimeProducts(play)).map(p => [p.productId, p]));
|
|
const langs = new Map(config.languages.map(l => [l.id, l]));
|
|
|
|
for (const [i, p] of products.entries()) {
|
|
const tag = step(i + 1, products.length, p.id);
|
|
const conv = await play.call<Converted>('POST', `${play.API}/pricing:convertRegionPrices`, { price: toMoney('USD', p.usd) });
|
|
if (!conv.convertedRegionPrices || !conv.convertedOtherRegionsPrice) throw new Error(`${p.id}: convertRegionPrices returned no prices`);
|
|
const regions = playRegionConfigs(conv.convertedRegionPrices, p.overrides);
|
|
const listings = Object.entries(p.listings).flatMap(([id, l]) =>
|
|
playCodes(langs.get(id)!).map(languageCode => ({ languageCode, title: l.title, description: l.description })));
|
|
if (!listings.length) throw new Error(`${p.id}: no listing language has a Play code`);
|
|
const body = {
|
|
packageName: pkg, productId: p.id, listings,
|
|
purchaseOptions: [{
|
|
purchaseOptionId: OPTION,
|
|
buyOption: { legacyCompatible: true, multiQuantityEnabled: false },
|
|
regionalPricingAndAvailabilityConfigs: regions,
|
|
newRegionsConfig: { usdPrice: conv.convertedOtherRegionsPrice.usdPrice, eurPrice: conv.convertedOtherRegionsPrice.eurPrice, availability: 'AVAILABLE' },
|
|
}],
|
|
};
|
|
const cur = existing.get(p.id);
|
|
if (dry) {
|
|
const ch = productChanges(cur, { listings, regions, newRegions: conv.convertedOtherRegionsPrice });
|
|
log('play', `${tag}: ${!ch.length ? 'unchanged' : ch[0] === 'create' ? `would create · ${regions.length} regions · ${listings.length} listings` : 'would update ' + ch.join('; ')} (dry)`);
|
|
continue;
|
|
}
|
|
const v = encodeURIComponent(conv.regionVersion?.version ?? '2022/02');
|
|
await play.call('PATCH', `${play.API}/onetimeproducts/${encodeURIComponent(p.id)}?allowMissing=true®ionsVersion.version=${v}&updateMask=listings,purchaseOptions`, body);
|
|
log('play', `${tag}: ${cur ? 'updated' : 'created'} · ${regions.length} regions · ${listings.length} listings`);
|
|
const active = cur?.purchaseOptions?.find(o => o.purchaseOptionId === OPTION)?.state === 'ACTIVE';
|
|
if (active) continue;
|
|
try {
|
|
await play.call('POST', `${play.API}/oneTimeProducts/${encodeURIComponent(p.id)}/purchaseOptions:batchUpdateStates`, {
|
|
requests: [{ activatePurchaseOptionRequest: { packageName: pkg, productId: p.id, purchaseOptionId: OPTION } }],
|
|
});
|
|
log('play', `${tag}: purchase option activated`);
|
|
} catch (e) { warn('play', `${tag}: activate failed: ${(e as Error).message}`); }
|
|
}
|
|
done('play', dry ? 'products checked (dry run, nothing written)' : 'products done');
|
|
}
|