Subscriptions on both stores: Apple groups, levels, equalized prices, intro and promotional offers, offer codes; Play base plans, regional prices, offers

This commit is contained in:
CRTkafa 2026-10-11 01:47:08 +08:00
parent 20c0221b1d
commit 162834444a
5 changed files with 873 additions and 4 deletions

182
cli/apple/subscriptions.ts Normal file
View file

@ -0,0 +1,182 @@
// Auto-renewable subscriptions on App Store Connect from `subscriptions` in the config: groups and their display names,
// subscriptions (period, level, family sharing, review note), localizations, availability (every territory + new
// ones), prices (USA price point + its equalizations, your overrides, optional CSV rows from the prices sheet incl.
// future-dated changes), introductory offers per territory and the review screenshot. Idempotent: what exists is
// left alone, prices are compared per territory and only differences are sent.
// storebound apple subscriptions [--dry] [--only id1,id2] [--csv store/prices.csv] [--codes] [--yes]
// Also promotional offers (`offers`, signed by your server at purchase time) and offer code campaigns
// (`offerCodes`). Custom codes of a campaign (redeemable by anyone who has the code) are only created with --codes
// from a terminal that confirms; one-time-use codes are generated by the owner in App Store Connect.
// Prints the plan first. In a terminal it asks before writing anything. Without a terminal (MCP, CI) and without
// --yes it still creates what is new (nothing is public before App Review), but never changes prices of a
// subscription that already has them: that waits for the owner in a terminal. preserveCurrentPrice is always true
// (existing subscribers keep their price; raising theirs is a separate step in App Store Connect).
// First subscriptions are submitted with an app version, like first in-app purchases (store-subscriptions skill).
// Pure parts and sources: lib/subscriptions.ts.
import { existsSync, readFileSync } from 'node:fs';
import { type OfferCodeDef, sellsOn, type Subscription, type SubscriptionGroup } from '../lib/config';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, step, warn } from '../lib/log';
import { parsePriceCsv, type PriceRow } from '../lib/prices';
import {
allSubscriptions, appleAvailabilityBody, appleCustomCodeBody, appleOfferCodeBody, applePromoOfferBody, appleGroupBody, appleGroupLocBody, appleIntroPatch, applePoints, applePriceChanges,
applePricesPatch, appleSubLocBody, appleSubPrices, appleSubscriptionBody, appleSubscriptionPlan, type AppleSubState, appleWantedPrices,
type ApplePoint, pickPoint,
} from '../lib/subscriptions';
import { pages } from '../prices';
import { type Asc, ascClient, type J } from './asc';
const TAG = 'apple';
/** CSV rows (prices sheet) of the configured subscriptions, when --csv is given. */
export function subscriptionCsv(ctx: Ctx, store: 'apple' | 'play'): PriceRow[] {
const path = ctx.args.get('csv');
if (!path) return [];
const file = ctx.loaded.resolve(path);
if (!existsSync(file)) throw new Error(`no prices CSV at ${file}`);
const { config } = ctx.loaded;
const subIds = allSubscriptions(config.subscriptions).map(x => x.sub.id);
const ids = [...(config.products ?? []).map(p => p.id), ...subIds];
return parsePriceCsv(readFileSync(file, 'utf8'), { products: ids }).filter(r => subIds.includes(r.product) && r.store === store);
}
async function readState(c: Asc, appId: string): Promise<AppleSubState> {
const state: AppleSubState = { groups: [], subscriptions: [] };
for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`)) {
const locales = (await c.all(`/v1/subscriptionGroups/${g.id}/subscriptionGroupLocalizations?limit=200`)).map((l: J) => l.attributes.locale);
state.groups.push({ id: g.id, referenceName: g.attributes.referenceName, locales });
for (const s of await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`)) {
const locs = (await c.all(`/v1/subscriptions/${s.id}/subscriptionLocalizations?limit=200`)).map((l: J) => l.attributes.locale);
const prices = (await c.asc('GET', `/v1/subscriptions/${s.id}/prices?limit=1`)).data?.length ?? 0;
const intro = (await c.asc('GET', `/v1/subscriptions/${s.id}/introductoryOffers?limit=1`)).data?.length ?? 0;
const avail = !!(await c.maybe(`/v1/subscriptions/${s.id}/subscriptionAvailability`))?.data;
const shot = !!(await c.maybe(`/v1/subscriptions/${s.id}/appStoreReviewScreenshot`))?.data;
const promoOffers = (await c.all(`/v1/subscriptions/${s.id}/promotionalOffers?limit=200`)).map((o: J) => o.attributes.offerCode);
const offerCodes = (await c.all(`/v1/subscriptions/${s.id}/offerCodes?limit=200`)).map((o: J) => o.attributes.name);
state.subscriptions.push({ id: s.id, productId: s.attributes.productId, groupId: g.id, state: s.attributes.state, locales: locs,
hasPrices: prices > 0, introTerritories: intro, availability: avail, reviewScreenshot: shot, promoOffers, offerCodes });
}
}
return state;
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const only = ctx.args.list('only');
const groups: SubscriptionGroup[] = need(config.subscriptions, 'subscriptions')
.map(g => ({ ...g, subscriptions: g.subscriptions.filter(s => (!only.length || only.includes(s.id)) && sellsOn(config, s, 'apple')) })).filter(g => g.subscriptions.length);
const dry = ctx.args.has('dry');
const csv = subscriptionCsv(ctx, 'apple');
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app();
log(TAG, 'reading subscription groups, subscriptions, localizations, prices, offers');
const state = await readState(c, appId);
const plan = appleSubscriptionPlan(groups, config.languages, state);
for (const [i, s] of plan.entries()) log(TAG, `${step(i + 1, plan.length, s.what)}`);
if (dry) { done(TAG, `subscriptions planned (dry run, nothing written; prices are compared per territory on a real run${csv.length ? `, ${csv.length} CSV rows` : ''})`); return; }
const yes = ctx.args.has('yes');
let liveOk = yes;
if (process.stdin.isTTY && !yes) {
if (!(await confirm(ctx, 'Create / update these subscriptions on App Store Connect? Nothing is public before App Review, but price changes of existing subscriptions apply to new subscribers right away.'))) return;
liveOk = true;
} else if (!yes) log(TAG, 'not a terminal: creating what is new only; price changes of existing subscriptions wait for a terminal run');
const locale = new Map(config.languages.map(l => [l.id, l.apple] as const));
const territories: string[] = (await c.all('/v1/territories?limit=200')).map((t: J) => t.id);
for (const g of groups) {
let gid = state.groups.find(x => x.referenceName === g.name)?.id;
if (!gid) { gid = (await c.asc('POST', '/v1/subscriptionGroups', appleGroupBody(appId, g))).data.id as string; log(TAG, `group "${g.name}" created`); }
const gLocs = state.groups.find(x => x.id === gid)?.locales ?? [];
for (const [lang, l] of Object.entries(g.listings)) {
const loc = locale.get(lang);
if (!loc || gLocs.includes(loc)) continue;
await c.asc('POST', '/v1/subscriptionGroupLocalizations', appleGroupLocBody(gid, loc, l));
log(TAG, ` group ${loc}`);
}
for (const [i, s] of g.subscriptions.entries()) {
const tag = step(i + 1, g.subscriptions.length, s.id);
const cur = state.subscriptions.find(x => x.productId === s.id);
let id = cur?.id;
if (!id) { id = (await c.asc('POST', '/v1/subscriptions', appleSubscriptionBody(gid, s))).data.id as string; log(TAG, `${tag}: created`); }
for (const [lang, l] of Object.entries(s.listings)) {
const loc = locale.get(lang);
if (!loc || cur?.locales.includes(loc)) continue;
await c.asc('POST', '/v1/subscriptionLocalizations', appleSubLocBody(id, loc, l));
log(TAG, ` ${loc}`);
}
if (!cur?.availability) { await c.asc('POST', '/v1/subscriptionAvailabilities', appleAvailabilityBody(id, territories)); log(TAG, ` available in ${territories.length} territories + new ones`); }
// prices: USA point -> equalizations -> overrides / CSV; only what differs from today's prices
const usaPoints = applePoints(await pages(c, `/v1/subscriptions/${id}/pricePoints?filter[territory]=USA&include=territory&limit=200`));
const usa = pickPoint(usaPoints, 'USA', s.usd);
const equalized = applePoints(await pages(c, `/v1/subscriptionPricePoints/${usa.id}/equalizations?include=territory&limit=200`));
const known: ApplePoint[] = [usa, ...equalized];
const current = cur?.hasPrices ? appleSubPrices(await pages(c, `/v1/subscriptions/${id}/prices?include=subscriptionPricePoint,territory&limit=200`)) : [];
const changes = applePriceChanges(current, appleWantedPrices(s, equalized, csv), csv.filter(r => r.product === s.id));
if (!changes.length) log(TAG, ' prices up to date');
else if (current.length && !liveOk) warn(TAG, ` ${changes.length} price change(s) skipped: run in a terminal to confirm`);
else {
const resolved: { territory: string; pointId: string; startDate?: string | null }[] = [];
for (const ch of changes) {
let pt = known.find(p => p.territory === ch.territory && Math.round(p.price * 100) === Math.round(ch.to * 100));
if (!pt) {
const tp = applePoints(await pages(c, `/v1/subscriptions/${id}/pricePoints?filter[territory]=${ch.territory}&include=territory&limit=200`));
known.push(...tp);
pt = pickPoint(tp, ch.territory, ch.to);
}
resolved.push({ territory: ch.territory, pointId: pt.id, startDate: ch.startDate ?? null });
}
await c.asc('PATCH', `/v1/subscriptions/${id}`, applePricesPatch(id, resolved));
log(TAG, ` prices: ${changes.length} territor${changes.length === 1 ? 'y' : 'ies'}${current.length ? ' changed' : ' set'} (${changes.slice(0, 4).map(x => `${x.territory} ${x.to}${x.startDate ? ` from ${x.startDate}` : ''}`).join(', ')}${changes.length > 4 ? ', ...' : ''})`);
}
// offer prices: free = every territory without a price point; paid = the USA point of the offer price and its
// equalizations (one price per territory)
const offerPrices = async (o: { type: string; usd?: number }): Promise<{ territory: string; pointId?: string }[]> => {
if (o.type === 'free') return territories.map(territory => ({ territory }));
const ip = pickPoint(usaPoints, 'USA', o.usd!);
const eq = applePoints(await pages(c, `/v1/subscriptionPricePoints/${ip.id}/equalizations?include=territory&limit=200`));
return [{ territory: 'USA', pointId: ip.id }, ...eq.filter(p => p.territory !== 'USA').map(p => ({ territory: p.territory, pointId: p.id }))];
};
if (s.intro && !cur?.introTerritories) {
const offers = await offerPrices(s.intro);
await c.asc('PATCH', `/v1/subscriptions/${id}`, appleIntroPatch(id, s, offers));
log(TAG, ` introductory offer in ${offers.length} territories`);
}
for (const o of s.offers ?? []) {
if (cur?.promoOffers?.includes(o.id)) continue;
await c.asc('POST', '/v1/subscriptionPromotionalOffers', applePromoOfferBody(id, s, o, await offerPrices(o)));
log(TAG, ` promotional offer ${o.id}`);
}
for (const oc of s.offerCodes ?? []) {
let ocId: string | undefined;
if (!cur?.offerCodes?.includes(oc.name)) {
ocId = (await c.asc('POST', '/v1/subscriptionOfferCodes', appleOfferCodeBody(id, s, oc, await offerPrices(oc)))).data.id as string;
log(TAG, ` offer code campaign "${oc.name}"`);
}
if (oc.customCodes?.length) await customCodes(c, ctx, id, s, oc, ocId);
}
if (s.reviewScreenshot && !cur?.reviewScreenshot) {
await c.uploadAsset('subscriptionAppStoreReviewScreenshots', { subscription: { data: { type: 'subscriptions', id } } }, resolve(s.reviewScreenshot));
log(TAG, ` review screenshot ${s.reviewScreenshot}`);
}
}
}
done(TAG, 'subscriptions done (first ones are submitted with an app version: store-subscriptions skill)');
}
/** Custom codes of one offer code campaign: only with --codes, only after a confirmation in a terminal (anyone with
* the code can redeem it). Existing codes (same customCode) are left alone. */
async function customCodes(c: Asc, ctx: Ctx, subId: string, s: Subscription, oc: OfferCodeDef, ocId: string | undefined): Promise<void> {
if (!ctx.args.has('codes')) { log(TAG, ` ${oc.customCodes!.length} custom code(s) of "${oc.name}" not created (pass --codes from a terminal)`); return; }
if (!process.stdin.isTTY) { warn(TAG, ` custom codes of "${oc.name}" need a terminal confirmation`); return; }
const id = ocId ?? (await c.all(`/v1/subscriptions/${subId}/offerCodes?limit=200`)).find((x: J) => x.attributes.name === oc.name)?.id;
if (!id) throw new Error(`${s.id}: offer code campaign "${oc.name}" not found`);
const have = new Set((await c.all(`/v1/subscriptionOfferCodes/${id}/customCodes?limit=200`)).map((x: J) => x.attributes.customCode));
const todo = oc.customCodes!.filter(cc => !have.has(cc.code));
if (!todo.length) return;
if (!(await confirm({ ...ctx, args: { ...ctx.args, has: (n: string) => n !== 'yes' && ctx.args.has(n) } }, `Create ${todo.length} custom offer code(s) for ${s.id} (${todo.map(x => `${x.code} x${x.count}`).join(', ')})? Anyone with a code can redeem it.`))) return;
for (const cc of todo) { await c.asc('POST', '/v1/subscriptionOfferCodeCustomCodes', appleCustomCodeBody(id, cc)); log(TAG, ` custom code ${cc.code} (${cc.count})`); }
}

507
cli/lib/subscriptions.ts Normal file
View file

@ -0,0 +1,507 @@
// Auto-renewable subscriptions on both stores, as pure parts: config checks, the period / offer mappings, the App
// Store Connect request bodies and plan, and the Google Play subscription / base plan / offer bodies and diff.
// The commands (cli/apple/subscriptions.ts, cli/play/subscriptions.ts) read the current state, call these, print the
// plan and only then write.
// Sources (checked October 2026):
// Apple: subscription groups, group localizations, subscriptions, subscription localizations, price points and their
// equalizations, subscription prices, introductory offers, availability, review screenshots.
// https://developer.apple.com/documentation/appstoreconnectapi/subscription-groups
// https://developer.apple.com/documentation/appstoreconnectapi/subscriptions
// https://developer.apple.com/documentation/appstoreconnectapi/subscription-prices
// https://developer.apple.com/documentation/appstoreconnectapi/subscription-price-points
// https://developer.apple.com/documentation/appstoreconnectapi/subscription-introductory-offers
// https://developer.apple.com/documentation/appstoreconnectapi/subscription-availabilities
// Google Play: monetization.subscriptions (create / patch / list), basePlans:activate, basePlans.offers (create,
// activate), pricing:convertRegionPrices.
// https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions
// https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions.basePlans
// https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions.basePlans.offers
import type { IntroOffer, Language, OfferCodeDef, PriceOverride, Subscription, SubscriptionGroup, SubscriptionOfferDef, SubscriptionPeriod } from './config';
import { playCodes } from './config';
import { ALPHA3, type Money, toMoney } from './money';
import type { PriceRow } from './prices';
// ---- mappings ----
export const PERIODS: readonly SubscriptionPeriod[] = ['P1W', 'P1M', 'P2M', 'P3M', 'P6M', 'P1Y'];
/** Subscription.subscriptionPeriod on App Store Connect. */
export const APPLE_PERIOD: Record<SubscriptionPeriod, string> = {
P1W: 'ONE_WEEK', P1M: 'ONE_MONTH', P2M: 'TWO_MONTHS', P3M: 'THREE_MONTHS', P6M: 'SIX_MONTHS', P1Y: 'ONE_YEAR',
};
/** SubscriptionOfferDuration on App Store Connect (introductory offers). */
export const APPLE_OFFER_DURATION: Record<string, string> = {
P3D: 'THREE_DAYS', P1W: 'ONE_WEEK', P2W: 'TWO_WEEKS', P1M: 'ONE_MONTH', P2M: 'TWO_MONTHS', P3M: 'THREE_MONTHS', P6M: 'SIX_MONTHS', P1Y: 'ONE_YEAR',
};
/** SubscriptionOfferMode on App Store Connect. */
export const APPLE_OFFER_MODE = { 'free': 'FREE_TRIAL', 'pay-as-you-go': 'PAY_AS_YOU_GO', 'pay-up-front': 'PAY_UP_FRONT' } as const;
/** Default Play base plan id per period. */
export const DEFAULT_BASE_PLAN: Record<SubscriptionPeriod, string> = {
P1W: 'weekly', P1M: 'monthly', P2M: 'every-2-months', P3M: 'quarterly', P6M: 'every-6-months', P1Y: 'yearly',
};
/** Play subscription listing limits: description 200 and at most 4 benefits (Subscription resource reference);
* 40 characters per benefit is the Play Console field limit (not in the API reference). */
export const PLAY_SUB_LIMITS = { description: 200, benefits: 4, benefit: 40 } as const;
/** Apple subscription display name / description (same limits as other in-app purchases: 30 / 45). */
export const APPLE_SUB_LIMITS = { name: 30, description: 45 } as const;
const PRODUCT_RE = /^[a-z0-9][a-z0-9._]*$/;
const PLAY_ID_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;
const GRACE = ['P3D', 'P7D', 'P14D', 'P30D'];
const len = (s: string): number => [...s].length;
export const basePlanId = (s: Subscription): string => s.basePlanId ?? DEFAULT_BASE_PLAN[s.period];
export const offerId = (s: Subscription): string => s.intro?.playOfferId ?? 'intro';
/** Any offer's phase length: free / pay-up-front as configured, pay-as-you-go = one subscription period. */
export const offerDuration = (s: Subscription, o: { type: string; duration?: string } | undefined): string =>
(o?.type === 'pay-as-you-go' ? o.duration ?? s.period : o?.duration ?? '');
/** Intro offer duration. */
export const introDuration = (s: Subscription): string => offerDuration(s, s.intro);
type OfferLike = Pick<IntroOffer, 'type' | 'duration' | 'periods' | 'usd'>;
/** Checks shared by intro offers, promotional offers and offer codes. */
function validateOffer(at: string, s: Subscription, o: OfferLike): string[] {
const e: string[] = [];
if (!(o.type in APPLE_OFFER_MODE)) e.push(`${at}.type: free | pay-as-you-go | pay-up-front`);
if (o.type === 'pay-as-you-go') {
if (!(Number.isInteger(o.periods) && o.periods! >= 1 && o.periods! <= 12)) e.push(`${at}.periods: 1-12 discounted periods`);
if (o.duration !== undefined && o.duration !== s.period) e.push(`${at}.duration: pay-as-you-go runs in the subscription period (${s.period}); leave it out`);
} else if (!o.duration || !APPLE_OFFER_DURATION[o.duration]) e.push(`${at}.duration: one of ${Object.keys(APPLE_OFFER_DURATION).join(', ')}`);
if (o.type === 'free' && o.usd !== undefined) e.push(`${at}.usd: a free offer has no price`);
if (o.type !== 'free') {
if (!(typeof o.usd === 'number' && o.usd > 0)) e.push(`${at}.usd: positive number`);
else if (o.type === 'pay-as-you-go' && o.usd >= s.usd) e.push(`${at}.usd: must be below the regular price ${s.usd}`);
}
return e;
}
/** Every subscription of every group, with its group. */
export const allSubscriptions = (groups: SubscriptionGroup[] | undefined): { group: SubscriptionGroup; sub: Subscription }[] =>
(groups ?? []).flatMap(group => group.subscriptions.map(sub => ({ group, sub })));
/** Problems with `subscriptions` in the config (empty = fine). `langIds` = language ids, `productIds` = one-time
* product ids (a subscription may not reuse one). */
export function validateSubscriptions(groups: unknown, langIds: Set<string>, productIds: Set<string>): string[] {
const e: string[] = [];
if (groups === undefined) return e;
if (!Array.isArray(groups)) return ['subscriptions: a list of groups'];
const seen = new Set<string>();
const groupNames = new Set<string>();
for (const [gi, g] of (groups as SubscriptionGroup[]).entries()) {
const at = `subscriptions[${gi}]`;
if (!g?.name) e.push(`${at}.name: missing (Apple subscription group reference name)`);
else if (groupNames.has(g.name)) e.push(`${at}.name: duplicate "${g.name}"`);
groupNames.add(g?.name);
if (!g?.listings || !Object.keys(g.listings).length) e.push(`${at}.listings: at least one language (group display name)`);
for (const [lang, l] of Object.entries(g?.listings ?? {})) {
if (!langIds.has(lang)) e.push(`${at}.listings.${lang}: not in languages`);
if (!l?.name) e.push(`${at}.listings.${lang}.name: missing`);
}
if (!Array.isArray(g?.subscriptions) || !g.subscriptions.length) { e.push(`${at}.subscriptions: at least one`); continue; }
const levels = new Set<number>();
for (const [si, s] of g.subscriptions.entries()) {
const sat = `${at}.subscriptions[${si}]`;
if (!PRODUCT_RE.test(s.id ?? '') || s.id.length > 40) e.push(`${sat}.id: 1-40 lowercase letters, digits, "." and "_", starting with a letter or digit (Play rule)`);
if (seen.has(s.id)) e.push(`${sat}.id: duplicate "${s.id}"`);
if (productIds.has(s.id)) e.push(`${sat}.id: "${s.id}" is already a one-time product`);
seen.add(s.id);
if (!PERIODS.includes(s.period)) e.push(`${sat}.period: one of ${PERIODS.join(', ')}`);
if (!(Number.isInteger(s.level) && s.level >= 1)) e.push(`${sat}.level: integer from 1 (1 = highest level of service)`);
else if (levels.has(s.level)) e.push(`${sat}.level: ${s.level} used twice in the group`);
levels.add(s.level);
if (!(typeof s.usd === 'number' && s.usd > 0)) e.push(`${sat}.usd: positive number`);
if (s.basePlanId !== undefined && !PLAY_ID_RE.test(s.basePlanId)) e.push(`${sat}.basePlanId: lowercase letters, digits and "-", max 63`);
if (s.gracePeriod !== undefined && !GRACE.includes(s.gracePeriod)) e.push(`${sat}.gracePeriod: one of ${GRACE.join(', ')}`);
for (const o of s.overrides ?? []) {
if (!/^[A-Z]{2}$/.test(o.region)) e.push(`${sat}.overrides: region "${o.region}" must be ISO alpha-2 (TR)`);
if (!/^[A-Z]{3}$/.test(o.currency)) e.push(`${sat}.overrides: currency "${o.currency}" must be ISO 4217 (TRY)`);
if (!(o.price > 0)) e.push(`${sat}.overrides: price must be positive`);
}
if (!s.listings || !Object.keys(s.listings).length) e.push(`${sat}.listings: at least one language`);
for (const [lang, l] of Object.entries(s.listings ?? {})) {
const lat = `${sat}.listings.${lang}`;
if (!langIds.has(lang)) e.push(`${lat}: not in languages`);
if (!l?.title) e.push(`${lat}.title: missing`);
else if (len(l.title) > APPLE_SUB_LIMITS.name) e.push(`${lat}.title: over ${APPLE_SUB_LIMITS.name} characters (App Store limit)`);
if (!l?.description) e.push(`${lat}.description: missing`);
else if (len(l.description) > APPLE_SUB_LIMITS.description) e.push(`${lat}.description: over ${APPLE_SUB_LIMITS.description} characters (App Store limit)`);
if ((l?.benefits?.length ?? 0) > PLAY_SUB_LIMITS.benefits) e.push(`${lat}.benefits: at most ${PLAY_SUB_LIMITS.benefits} (Play)`);
for (const b of l?.benefits ?? []) if (len(b) > PLAY_SUB_LIMITS.benefit) e.push(`${lat}.benefits: "${b.slice(0, 20)}..." over ${PLAY_SUB_LIMITS.benefit} characters (Play)`);
}
if (s.intro) {
e.push(...validateOffer(`${sat}.intro`, s, s.intro));
if (s.intro.playOfferId !== undefined && !PLAY_ID_RE.test(s.intro.playOfferId)) e.push(`${sat}.intro.playOfferId: lowercase letters, digits and "-", max 63`);
}
const offerIds = new Set<string>(s.intro ? [offerId(s)] : []);
for (const [oi, o] of (s.offers ?? []).entries()) {
const oat = `${sat}.offers[${oi}]`;
if (!PLAY_ID_RE.test(o.id ?? '')) e.push(`${oat}.id: lowercase letters, digits and "-", max 63 (Play offer id, Apple offer code)`);
if (offerIds.has(o.id)) e.push(`${oat}.id: duplicate offer id "${o.id}"`);
offerIds.add(o.id);
e.push(...validateOffer(oat, s, o));
}
const codeNames = new Set<string>();
for (const [ci, oc] of (s.offerCodes ?? []).entries()) {
const cat = `${sat}.offerCodes[${ci}]`;
if (!oc.name) e.push(`${cat}.name: missing`);
if (codeNames.has(oc.name)) e.push(`${cat}.name: duplicate "${oc.name}"`);
codeNames.add(oc.name);
if (!Array.isArray(oc.eligibility) || !oc.eligibility.length || !oc.eligibility.every(x => ['NEW', 'EXISTING', 'EXPIRED'].includes(x))) e.push(`${cat}.eligibility: a list of NEW | EXISTING | EXPIRED`);
e.push(...validateOffer(cat, s, oc));
for (const cc of oc.customCodes ?? []) {
if (!/^[A-Z0-9]{1,64}$/.test(cc.code ?? '')) e.push(`${cat}.customCodes: "${cc.code}" must be upper-case letters and digits`);
if (!(Number.isInteger(cc.count) && cc.count >= 1)) e.push(`${cat}.customCodes ${cc.code}: count must be a positive integer`);
if (cc.expires !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(cc.expires)) e.push(`${cat}.customCodes ${cc.code}: expires YYYY-MM-DD`);
}
}
if (s.platforms !== undefined && !(Array.isArray(s.platforms) && s.platforms.length && s.platforms.every(x => x === 'ios' || x === 'android'))) e.push(`${sat}.platforms: a list of ios | android`);
}
}
return e;
}
// ---- Apple: request bodies ----
const rel = (type: string, id: string) => ({ data: { type, id } });
export const appleGroupBody = (appId: string, g: SubscriptionGroup) =>
({ data: { type: 'subscriptionGroups', attributes: { referenceName: g.name }, relationships: { app: rel('apps', appId) } } });
export const appleGroupLocBody = (groupId: string, locale: string, l: { name: string; customAppName?: string }) =>
({ data: { type: 'subscriptionGroupLocalizations', attributes: { locale, name: l.name, ...(l.customAppName ? { customAppName: l.customAppName } : {}) },
relationships: { subscriptionGroup: rel('subscriptionGroups', groupId) } } });
export function appleSubscriptionBody(groupId: string, s: Subscription) {
const first = Object.values(s.listings)[0]!;
return { data: { type: 'subscriptions', attributes: {
name: s.referenceName ?? first.title, productId: s.id, subscriptionPeriod: APPLE_PERIOD[s.period], groupLevel: s.level,
familySharable: s.familySharable ?? false, ...(s.reviewNote ? { reviewNote: s.reviewNote } : {}),
}, relationships: { group: rel('subscriptionGroups', groupId) } } };
}
export const appleSubLocBody = (subId: string, locale: string, l: { title: string; description: string }) =>
({ data: { type: 'subscriptionLocalizations', attributes: { locale, name: l.title, description: l.description },
relationships: { subscription: rel('subscriptions', subId) } } });
export const appleAvailabilityBody = (subId: string, territories: string[]) =>
({ data: { type: 'subscriptionAvailabilities', attributes: { availableInNewTerritories: true },
relationships: { subscription: rel('subscriptions', subId), availableTerritories: { data: territories.map(id => ({ type: 'territories', id })) } } } });
/**
* Prices for many territories in one request: PATCH /v1/subscriptions/{id} with `prices` and the inline-created
* subscriptionPrices in `included` (SubscriptionUpdateRequest). startDate null = now, a date = a scheduled change;
* preserveCurrentPrice true keeps existing subscribers on their current price (a price increase for them is a
* separate, consent-bound step in App Store Connect).
*/
export function applePricesPatch(subId: string, prices: { territory: string; pointId: string; startDate?: string | null }[], o: { preserveCurrentPrice?: boolean } = {}) {
const ids = prices.map((_, i) => `\${price-${i}}`);
return {
data: { type: 'subscriptions', id: subId, relationships: { prices: { data: ids.map(id => ({ type: 'subscriptionPrices', id })) } } },
included: prices.map((p, i) => ({ type: 'subscriptionPrices', id: ids[i], attributes: { startDate: p.startDate ?? null, preserveCurrentPrice: o.preserveCurrentPrice ?? true },
relationships: { subscriptionPricePoint: rel('subscriptionPricePoints', p.pointId), territory: rel('territories', p.territory) } })),
};
}
/** Introductory offers for many territories in one request (PATCH /v1/subscriptions/{id}, `introductoryOffers` +
* inline creates). A free trial has no price point; a paid offer needs one per territory. */
export function appleIntroPatch(subId: string, s: Subscription, territories: { territory: string; pointId?: string }[]) {
const o = s.intro!;
const ids = territories.map((_, i) => `\${intro-${i}}`);
return {
data: { type: 'subscriptions', id: subId, relationships: { introductoryOffers: { data: ids.map(id => ({ type: 'subscriptionIntroductoryOffers', id })) } } },
included: territories.map((t, i) => {
if (o.type !== 'free' && !t.pointId) throw new Error(`${s.id}: paid introductory offer in ${t.territory} needs a price point`);
return { type: 'subscriptionIntroductoryOffers', id: ids[i], attributes: {
duration: APPLE_OFFER_DURATION[introDuration(s)], offerMode: APPLE_OFFER_MODE[o.type],
numberOfPeriods: o.type === 'pay-as-you-go' ? o.periods! : 1, startDate: null, endDate: null,
}, relationships: { territory: rel('territories', t.territory), ...(o.type !== 'free' ? { subscriptionPricePoint: rel('subscriptionPricePoints', t.pointId!) } : {}) } };
}),
};
}
/** Promotional offer (Apple subscriptionPromotionalOffers): one price entry per territory; a free offer sends the
* territory without a price point (the schema marks the price point optional; not verified against a live account). */
export function applePromoOfferBody(subId: string, s: Subscription, o: SubscriptionOfferDef, prices: { territory: string; pointId?: string }[]) {
const ids = prices.map((_, i) => `\${promo-${i}}`);
return {
data: { type: 'subscriptionPromotionalOffers', attributes: { name: o.name ?? o.id, offerCode: o.id, duration: APPLE_OFFER_DURATION[offerDuration(s, o)],
offerMode: APPLE_OFFER_MODE[o.type], numberOfPeriods: o.type === 'pay-as-you-go' ? o.periods! : 1 },
relationships: { subscription: rel('subscriptions', subId), prices: { data: ids.map(id => ({ type: 'subscriptionPromotionalOfferPrices', id })) } } },
included: prices.map((p, i) => offerPrice('subscriptionPromotionalOfferPrices', ids[i]!, o, p, s.id)),
};
}
/** Offer code campaign (Apple subscriptionOfferCodes) with its per-territory prices. */
export function appleOfferCodeBody(subId: string, s: Subscription, oc: OfferCodeDef, prices: { territory: string; pointId?: string }[]) {
const ids = prices.map((_, i) => `\${code-${i}}`);
return {
data: { type: 'subscriptionOfferCodes', attributes: { name: oc.name, customerEligibilities: oc.eligibility,
offerEligibility: oc.stackWithIntro ? 'STACK_WITH_INTRO_OFFERS' : 'REPLACE_INTRO_OFFERS', duration: APPLE_OFFER_DURATION[offerDuration(s, oc)],
offerMode: APPLE_OFFER_MODE[oc.type], numberOfPeriods: oc.type === 'pay-as-you-go' ? oc.periods! : 1 },
relationships: { subscription: rel('subscriptions', subId), prices: { data: ids.map(id => ({ type: 'subscriptionOfferCodePrices', id })) } } },
included: prices.map((p, i) => offerPrice('subscriptionOfferCodePrices', ids[i]!, oc, p, s.id)),
};
}
function offerPrice(type: string, id: string, o: OfferLike, p: { territory: string; pointId?: string }, product: string) {
if (o.type !== 'free' && !p.pointId) throw new Error(`${product}: paid offer in ${p.territory} needs a price point`);
return { type, id, relationships: { territory: rel('territories', p.territory), ...(p.pointId ? { subscriptionPricePoint: rel('subscriptionPricePoints', p.pointId) } : {}) } };
}
/** Custom code of an offer code campaign (POST /v1/subscriptionOfferCodeCustomCodes). */
export const appleCustomCodeBody = (offerCodeId: string, cc: { code: string; count: number; expires?: string }) =>
({ data: { type: 'subscriptionOfferCodeCustomCodes', attributes: { customCode: cc.code, numberOfCodes: cc.count, ...(cc.expires ? { expirationDate: cc.expires } : {}) },
relationships: { offerCode: rel('subscriptionOfferCodes', offerCodeId) } } });
// ---- Apple: prices ----
export interface ApplePoint { id: string; territory: string; price: number }
/**
* The manual price per territory: the USA point's equalizations for every territory, then the config overrides, then
* CSV rows without start_date (CSV wins). Returns territory -> wanted price. Pure; points are looked up by the caller.
*/
export function appleWantedPrices(s: Subscription, equalized: ApplePoint[], csv: PriceRow[] = []): Map<string, number> {
const out = new Map<string, number>([['USA', s.usd]]);
for (const p of equalized) if (p.territory !== 'USA') out.set(p.territory, p.price);
for (const o of s.overrides ?? []) out.set(territoryOf(o), o.price);
for (const r of csv) if (r.product === s.id && r.store === 'apple' && !r.startDate && r.kind !== 'auto') out.set(r.territory ?? ALPHA3[r.region] ?? r.region, r.price);
return out;
}
function territoryOf(o: PriceOverride): string {
const t = o.territory ?? ALPHA3[o.region];
if (!t) throw new Error(`no App Store territory known for region ${o.region}; set "territory" (alpha-3)`);
return t;
}
const cents = (n: number): number => Math.round(n * 100);
export interface PriceChange { territory: string; from: number | null; to: number; startDate?: string }
/** Wanted prices (now) + CSV scheduled rows vs the current prices: only what differs. `current` = prices in effect now
* (startDate null or in the past) and scheduled ones (future startDate). */
export function applePriceChanges(current: { territory: string; price: number; startDate?: string | null }[], wanted: Map<string, number>,
scheduled: PriceRow[] = []): PriceChange[] {
const now = new Map(current.filter(c => !c.startDate).map(c => [c.territory, c.price] as const));
const future = new Set(current.filter(c => c.startDate).map(c => `${c.territory}|${c.startDate}|${cents(c.price)}`));
const out: PriceChange[] = [];
for (const [territory, to] of [...wanted.entries()].sort(([a], [b]) => (a === 'USA' ? -1 : b === 'USA' ? 1 : a.localeCompare(b)))) {
const from = now.get(territory) ?? null;
if (from === null || cents(from) !== cents(to)) out.push({ territory, from, to });
}
for (const r of scheduled.filter(x => x.store === 'apple' && x.startDate)) {
const territory = r.territory ?? ALPHA3[r.region] ?? r.region;
if (!future.has(`${territory}|${r.startDate}|${cents(r.price)}`)) out.push({ territory, from: now.get(territory) ?? null, to: r.price, startDate: r.startDate });
}
return out;
}
// ---- Apple: plan ----
export interface AppleSubState {
groups: { id: string; referenceName: string; locales: string[] }[];
subscriptions: { id: string; productId: string; groupId: string; state?: string; locales: string[]; hasPrices: boolean; introTerritories: number; availability: boolean; reviewScreenshot: boolean;
/** offerCode of each promotional offer; name of each offer code campaign (optional for older fixtures). */
promoOffers?: string[]; offerCodes?: string[] }[];
}
export interface AppleStep { group: string; product?: string; kind: 'group' | 'group-loc' | 'sub' | 'sub-loc' | 'availability' | 'prices' | 'intro' | 'promo' | 'offer-code' | 'review-shot'; what: string }
/** What `apple subscriptions` would do, in order (prices are refined by the command once the price points are known). */
export function appleSubscriptionPlan(groups: SubscriptionGroup[], langs: Language[], state: AppleSubState): AppleStep[] {
const steps: AppleStep[] = [];
const locale = new Map(langs.map(l => [l.id, l.apple] as const));
for (const g of groups) {
const cur = state.groups.find(x => x.referenceName === g.name);
if (!cur) steps.push({ group: g.name, kind: 'group', what: `create subscription group "${g.name}"` });
for (const [lang, l] of Object.entries(g.listings)) {
const loc = locale.get(lang);
if (loc && !cur?.locales.includes(loc)) steps.push({ group: g.name, kind: 'group-loc', what: `group ${loc}: "${l.name}"` });
}
for (const s of [...g.subscriptions].sort((a, b) => a.level - b.level)) {
const sc = state.subscriptions.find(x => x.productId === s.id);
if (sc && cur && sc.groupId !== cur.id) throw new Error(`${s.id} exists in another subscription group on App Store Connect (a subscription cannot move between groups)`);
const p = { group: g.name, product: s.id };
if (!sc) steps.push({ ...p, kind: 'sub', what: `create ${s.id} (${APPLE_PERIOD[s.period]}, level ${s.level})` });
for (const [lang, l] of Object.entries(s.listings)) {
const loc = locale.get(lang);
if (loc && !sc?.locales.includes(loc)) steps.push({ ...p, kind: 'sub-loc', what: `${s.id} ${loc}: "${l.title}"` });
}
if (!sc?.availability) steps.push({ ...p, kind: 'availability', what: `${s.id}: available in every territory + new ones` });
steps.push({ ...p, kind: 'prices', what: sc?.hasPrices ? `${s.id}: compare prices (USA ${s.usd} base)` : `${s.id}: prices from USA ${s.usd} (equalized) + ${(s.overrides ?? []).length} override(s)` });
if (s.intro && !(sc?.introTerritories)) steps.push({ ...p, kind: 'intro', what: `${s.id}: introductory offer ${APPLE_OFFER_MODE[s.intro.type]} ${introDuration(s)}${s.intro.type === 'pay-as-you-go' ? ` x${s.intro.periods}` : ''}${s.intro.usd ? ` at USA ${s.intro.usd}` : ''}` });
for (const o of s.offers ?? []) if (!sc?.promoOffers?.includes(o.id)) steps.push({ ...p, kind: 'promo', what: `${s.id}: promotional offer ${o.id} (${APPLE_OFFER_MODE[o.type]} ${offerDuration(s, o)})` });
for (const oc of s.offerCodes ?? []) if (!sc?.offerCodes?.includes(oc.name)) steps.push({ ...p, kind: 'offer-code', what: `${s.id}: offer code campaign "${oc.name}" (${oc.eligibility.join('/')}, ${APPLE_OFFER_MODE[oc.type]})${oc.customCodes?.length ? ` + ${oc.customCodes.length} custom code(s) with --codes` : ''}` });
if (s.reviewScreenshot && !sc?.reviewScreenshot) steps.push({ ...p, kind: 'review-shot', what: `${s.id}: review screenshot ${s.reviewScreenshot}` });
}
}
return steps;
}
// ---- Play ----
export interface PlayRegionPrice { regionCode: string; price: Money }
/** Regional base plan prices: converted (convertRegionPrices of the USD price), then overrides, then CSV rows. */
export function playSubRegions(s: Subscription, converted: Record<string, { regionCode: string; price: Money }>, csv: PriceRow[] = []): PlayRegionPrice[] {
const by = new Map(Object.values(converted).map(r => [r.regionCode, r.price] as const));
for (const o of s.overrides ?? []) {
if (!by.has(o.region)) throw new Error(`${s.id}: Play does not sell in region ${o.region}`);
by.set(o.region, toMoney(o.currency, o.price));
}
for (const r of csv) {
if (r.product !== s.id || r.store !== 'play' || r.kind === 'auto') continue;
const known = by.get(r.region);
if (!known) throw new Error(`${s.id}: Play does not sell in region ${r.region}`);
if (known.currencyCode !== r.currency) throw new Error(`${s.id} ${r.region}: Play prices this region in ${known.currencyCode}, the CSV says ${r.currency}`);
by.set(r.region, toMoney(r.currency, r.price));
}
return [...by.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([regionCode, price]) => ({ regionCode, price }));
}
export interface PlaySubscription {
packageName?: string;
productId: string;
listings?: { languageCode: string; title: string; description?: string; benefits?: string[] }[];
basePlans?: {
basePlanId: string; state?: string;
autoRenewingBasePlanType?: { billingPeriodDuration: string; gracePeriodDuration?: string; resubscribeState?: string; legacyCompatible?: boolean; [k: string]: unknown };
regionalConfigs?: { regionCode: string; newSubscriberAvailability?: boolean; price?: Money }[];
otherRegionsConfig?: { usdPrice: Money; eurPrice: Money; newSubscriberAvailability?: boolean };
[k: string]: unknown;
}[];
[k: string]: unknown;
}
/** Subscription resource for create / patch: listings per Play language, one auto-renewing base plan. */
export function playSubscriptionBody(pkg: string, s: Subscription, langs: Language[], regions: PlayRegionPrice[], other: { usdPrice: Money; eurPrice: Money }): PlaySubscription {
const byId = new Map(langs.map(l => [l.id, l] as const));
const listings = Object.entries(s.listings).flatMap(([id, l]) => {
const lang = byId.get(id);
return lang ? playCodes(lang).map(languageCode => ({ languageCode, title: l.title, description: l.description, ...(l.benefits?.length ? { benefits: l.benefits } : {}) })) : [];
});
if (!listings.length) throw new Error(`${s.id}: no listing language has a Play code`);
return {
packageName: pkg, productId: s.id, listings,
basePlans: [{
basePlanId: basePlanId(s),
autoRenewingBasePlanType: { billingPeriodDuration: s.period, ...(s.gracePeriod ? { gracePeriodDuration: s.gracePeriod } : {}), resubscribeState: 'RESUBSCRIBE_STATE_ACTIVE', legacyCompatible: true },
regionalConfigs: regions.map(r => ({ regionCode: r.regionCode, newSubscriberAvailability: true, price: r.price })),
otherRegionsConfig: { usdPrice: other.usdPrice, eurPrice: other.eurPrice, newSubscriberAvailability: true },
}],
};
}
/**
* An offer on the base plan: the introductory offer (for people who never had this subscription), or with `extra`
* one of `offers` (no acquisition targeting, offer tag = its id; your app decides who gets it). free = free trial phase;
* pay-as-you-go = `periods` phases at a relative discount (so it follows every regional price, overrides included);
* pay-up-front = one phase priced from convertRegionPrices of the offer price (`offerRegions`).
*/
export function playOfferBody(pkg: string, s: Subscription, regions: PlayRegionPrice[], offerRegions?: { regions: PlayRegionPrice[]; other: { usdPrice: Money; eurPrice: Money } },
extra?: SubscriptionOfferDef) {
const o: OfferLike = extra ?? s.intro!;
const codes = regions.map(r => r.regionCode);
let regionalConfigs: Record<string, unknown>[];
let otherRegionsConfig: Record<string, unknown>;
if (o.type === 'free') {
regionalConfigs = codes.map(regionCode => ({ regionCode, free: {} }));
otherRegionsConfig = { free: {} };
} else if (o.type === 'pay-as-you-go') {
const relativeDiscount = Math.round((1 - o.usd! / s.usd) * 100) / 100;
regionalConfigs = codes.map(regionCode => ({ regionCode, relativeDiscount }));
otherRegionsConfig = { relativeDiscount };
} else {
if (!offerRegions) throw new Error(`${s.id}: pay-up-front offer needs converted offer prices`);
const by = new Map(offerRegions.regions.map(r => [r.regionCode, r.price] as const));
regionalConfigs = codes.filter(c => by.has(c)).map(regionCode => ({ regionCode, price: by.get(regionCode) }));
otherRegionsConfig = { otherRegionsPrices: { usdPrice: offerRegions.other.usdPrice, eurPrice: offerRegions.other.eurPrice } };
}
return {
packageName: pkg, productId: s.id, basePlanId: basePlanId(s), offerId: extra ? extra.id : offerId(s),
phases: [{ recurrenceCount: o.type === 'pay-as-you-go' ? o.periods! : 1, duration: offerDuration(s, o), regionalConfigs, otherRegionsConfig }],
// intro: people who never had this subscription; extra offers: no targeting, your app picks them by offer tag
...(extra ? { offerTags: [{ tag: extra.id }] } : { targeting: { acquisitionRule: { scope: { thisSubscription: {} } } } }),
regionalConfigs: codes.map(regionCode => ({ regionCode, newSubscriberAvailability: true })),
otherRegionsConfig: { otherRegionsNewSubscriberAvailability: true },
};
}
const moneyKey = (m?: Money): string => (m ? `${m.currencyCode} ${cents(Number(m.units) + (m.nanos ?? 0) / 1e9)}` : '-');
export interface PlaySubDiff { create: boolean; listings: string[]; basePlan: 'new' | 'same' | 'changed'; priceChanges: { regionCode: string; from: string; to: string }[]; activate: boolean }
/** Current Play subscription (or null) vs the wanted body: what a patch would change. Price changes on an existing
* base plan apply to new subscribers; existing ones keep their price until you run a price migration in the Console. */
export function playSubDiff(cur: PlaySubscription | null, want: PlaySubscription): PlaySubDiff {
const wb = want.basePlans![0]!;
if (!cur) return { create: true, listings: (want.listings ?? []).map(l => l.languageCode), basePlan: 'new', priceChanges: [], activate: true };
const curL = new Map((cur.listings ?? []).map(l => [l.languageCode, l] as const));
const listings = (want.listings ?? []).filter(l => {
const c = curL.get(l.languageCode);
return !c || c.title !== l.title || (c.description ?? '') !== (l.description ?? '') || JSON.stringify(c.benefits ?? []) !== JSON.stringify(l.benefits ?? []);
}).map(l => l.languageCode);
const cb = cur.basePlans?.find(b => b.basePlanId === wb.basePlanId);
if (!cb) return { create: false, listings, basePlan: 'new', priceChanges: [], activate: true };
const cr = new Map((cb.regionalConfigs ?? []).map(r => [r.regionCode, r.price] as const));
const priceChanges = (wb.regionalConfigs ?? []).filter(r => moneyKey(cr.get(r.regionCode)) !== moneyKey(r.price))
.map(r => ({ regionCode: r.regionCode, from: moneyKey(cr.get(r.regionCode)), to: moneyKey(r.price) }));
const typeSame = cb.autoRenewingBasePlanType?.billingPeriodDuration === wb.autoRenewingBasePlanType?.billingPeriodDuration
&& (cb.autoRenewingBasePlanType?.gracePeriodDuration ?? '') === (wb.autoRenewingBasePlanType?.gracePeriodDuration ?? cb.autoRenewingBasePlanType?.gracePeriodDuration ?? '');
if (cb.autoRenewingBasePlanType && cb.autoRenewingBasePlanType.billingPeriodDuration !== wb.autoRenewingBasePlanType?.billingPeriodDuration)
throw new Error(`${want.productId}: base plan ${wb.basePlanId} bills every ${cb.autoRenewingBasePlanType.billingPeriodDuration} on Play, the config says ${wb.autoRenewingBasePlanType?.billingPeriodDuration} (a billing period cannot change; use a new basePlanId)`);
return { create: false, listings, basePlan: priceChanges.length || !typeSame ? 'changed' : 'same', priceChanges, activate: cb.state !== 'ACTIVE' };
}
/** The patch body keeps base plans the config does not manage (Play would otherwise drop them) and output-only fields out. */
export function playPatchSubscription(cur: PlaySubscription, want: PlaySubscription): PlaySubscription {
const wb = want.basePlans![0]!;
const keep = (cur.basePlans ?? []).filter(b => b.basePlanId !== wb.basePlanId).map(({ state: _s, ...b }) => b);
const curMine = cur.basePlans?.find(b => b.basePlanId === wb.basePlanId);
const { state: _st, ...mine } = { ...(curMine ?? {}), ...wb, autoRenewingBasePlanType: { ...(curMine?.autoRenewingBasePlanType ?? {}), ...wb.autoRenewingBasePlanType! } };
return { ...want, basePlans: [...keep, mine as NonNullable<PlaySubscription['basePlans']>[number]] };
}
// ---- Apple: reading responses ----
interface JsonApi { data?: { id: string; type?: string; attributes?: Record<string, unknown>; relationships?: Record<string, { data?: { id: string; type?: string } | null }> }[]; included?: { id: string; type: string; attributes?: Record<string, unknown> }[] }
/** Price points (GET /v1/subscriptions/{id}/pricePoints or .../equalizations, include=territory) -> points. */
export function applePoints(resp: JsonApi): ApplePoint[] {
return (resp.data ?? []).flatMap(p => {
const territory = p.relationships?.territory?.data?.id;
const price = Number(p.attributes?.customerPrice);
return territory && !Number.isNaN(price) ? [{ id: p.id, territory, price }] : [];
});
}
/** GET /v1/subscriptions/{id}/prices?include=subscriptionPricePoint,territory -> per territory the price in effect
* today (the latest start date not after `today`; startDate null) plus scheduled future prices (startDate set). */
export function appleSubPrices(resp: JsonApi, today = new Date().toISOString().slice(0, 10)): { territory: string; price: number; startDate: string | null; pointId: string; currency?: string }[] {
const points = new Map((resp.included ?? []).filter(x => x.type === 'subscriptionPricePoints').map(x => [x.id, Number(x.attributes?.customerPrice)] as const));
const currency = new Map((resp.included ?? []).filter(x => x.type === 'territories').map(x => [x.id, x.attributes?.currency as string | undefined] as const));
const now = new Map<string, { territory: string; price: number; startDate: string | null; pointId: string; since: string; currency?: string }>();
const future: { territory: string; price: number; startDate: string | null; pointId: string; currency?: string }[] = [];
for (const p of resp.data ?? []) {
const territory = p.relationships?.territory?.data?.id;
const pointId = p.relationships?.subscriptionPricePoint?.data?.id ?? '';
const price = points.get(pointId);
const start = (p.attributes?.startDate as string | null | undefined) ?? '';
if (!territory || price === undefined || Number.isNaN(price)) continue;
const cc = currency.get(territory);
if (start > today) { future.push({ territory, price, pointId, startDate: start, ...(cc ? { currency: cc } : {}) }); continue; }
const cur = now.get(territory);
if (!cur || start >= cur.since) now.set(territory, { territory, price, pointId, startDate: null, since: start, ...(cc ? { currency: cc } : {}) });
}
return [...[...now.values()].map(({ since: _s, ...x }) => x), ...future];
}
/** Price point with exactly this customer price (cents), or a helpful error with the nearest ones. */
export function pickPoint(points: ApplePoint[], territory: string, price: number): ApplePoint {
const inT = points.filter(p => p.territory === territory);
const hit = inT.find(p => cents(p.price) === cents(price));
if (hit) return hit;
const near = [...inT].sort((a, b) => Math.abs(a.price - price) - Math.abs(b.price - price)).slice(0, 3).map(p => p.price);
throw new Error(`${territory} has no subscription price point ${price}${near.length ? ` (nearest ${near.join(', ')})` : ''}`);
}

119
cli/play/subscriptions.ts Normal file
View file

@ -0,0 +1,119 @@
// Auto-renewable subscriptions on Google Play through monetization.subscriptions, from `subscriptions` in the
// config: one Play subscription per entry with listings per Play language (title, description, benefits), one
// auto-renewing base plan (billing period, grace period, regional prices from convertRegionPrices + overrides + optional
// CSV rows), activated, and the introductory offer (free trial, pay as you go, pay up front) for people who never had
// the subscription, activated, plus `offers` (no acquisition targeting, offer tag = id: your app decides who sees
// them). Play has no subscription groups (an Apple concept) and no API for promo codes (Play Console > Monetize >
// Promo codes). Idempotent: compares first.
// storebound play subscriptions [--dry] [--only id1,id2] [--csv store/prices.csv] [--yes]
// Prints the plan first. In a terminal it asks before writing. Without a terminal (MCP, CI) and without --yes it
// creates what is new only and leaves price changes of existing base plans to a terminal run. A base plan price
// change applies to new subscribers; existing ones keep their price until you run a price migration in Play Console.
// Pure parts and sources: lib/subscriptions.ts.
import { sellsOn } from '../lib/config';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, step, warn } from '../lib/log';
import { type Money, toMoney } from '../lib/money';
import {
allSubscriptions, basePlanId, offerId, playOfferBody, playPatchSubscription, type PlaySubscription, playSubDiff, playSubRegions,
playSubscriptionBody,
} from '../lib/subscriptions';
import { subscriptionCsv } from '../apple/subscriptions';
import { playClient } from './client';
const TAG = 'play';
interface Converted { convertedRegionPrices?: Record<string, { regionCode: string; price: Money }>; convertedOtherRegionsPrice?: { usdPrice: Money; eurPrice: Money }; regionVersion?: { version: string } }
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 subs = allSubscriptions(need(config.subscriptions, 'subscriptions')).map(x => x.sub).filter(s => (!only.length || only.includes(s.id)) && sellsOn(config, s, 'play'));
const dry = ctx.args.has('dry');
const csv = subscriptionCsv(ctx, 'play');
const play = await playClient(root, pkg);
const existing = new Map<string, PlaySubscription>();
let page = '';
do {
const r = await play.call<{ subscriptions?: PlaySubscription[]; nextPageToken?: string }>('GET', `${play.API}/subscriptions?pageSize=100${page ? '&pageToken=' + page : ''}`);
for (const s of r.subscriptions ?? []) existing.set(s.productId, s);
page = r.nextPageToken ?? '';
} while (page);
const convert = async (usd: number): Promise<Required<Converted>> => {
const conv = await play.call<Converted>('POST', `${play.API}/pricing:convertRegionPrices`, { price: toMoney('USD', usd) });
if (!conv.convertedRegionPrices || !conv.convertedOtherRegionsPrice) throw new Error(`convertRegionPrices returned no prices for USD ${usd}`);
return { convertedRegionPrices: conv.convertedRegionPrices, convertedOtherRegionsPrice: conv.convertedOtherRegionsPrice, regionVersion: conv.regionVersion ?? { version: '2022/02' } };
};
const work: { s: typeof subs[number]; body: PlaySubscription; diff: ReturnType<typeof playSubDiff>; version: string; offerMissing: boolean; extraMissing: string[] }[] = [];
for (const [i, s] of subs.entries()) {
const conv = await convert(s.usd);
const regions = playSubRegions(s, conv.convertedRegionPrices, csv);
const body = playSubscriptionBody(pkg, s, config.languages, regions, conv.convertedOtherRegionsPrice);
const cur = existing.get(s.id) ?? null;
const diff = playSubDiff(cur, body);
let offerMissing = !!s.intro;
let extraMissing = (s.offers ?? []).map(o => o.id);
if ((s.intro || s.offers?.length) && cur?.basePlans?.some(b => b.basePlanId === basePlanId(s))) {
const offers = await play.call<{ subscriptionOffers?: { offerId: string }[] }>('GET', `${play.API}/subscriptions/${encodeURIComponent(s.id)}/basePlans/${basePlanId(s)}/offers`);
const have = new Set((offers.subscriptionOffers ?? []).map(o => o.offerId));
offerMissing = !!s.intro && !have.has(offerId(s));
extraMissing = extraMissing.filter(x => !have.has(x));
}
const what = diff.create ? `create, base plan ${basePlanId(s)} (${s.period}) in ${regions.length} regions`
: [diff.listings.length ? `listings ${diff.listings.join(', ')}` : '', diff.basePlan === 'new' ? `new base plan ${basePlanId(s)}` : diff.basePlan === 'changed' ? `base plan ${basePlanId(s)}: ${diff.priceChanges.length} regional price change(s)` : '',
diff.activate ? 'activate base plan' : ''].filter(Boolean).join(' · ') || 'up to date';
log(TAG, `${step(i + 1, subs.length, s.id)}: ${what}${offerMissing ? ` · intro offer ${offerId(s)} (${s.intro!.type})` : ''}${extraMissing.length ? ` · offers ${extraMissing.join(', ')}` : ''}`);
for (const p of diff.priceChanges.slice(0, 5)) log(TAG, ` ${p.regionCode}: ${p.from} -> ${p.to}`);
if (diff.priceChanges.length > 5) log(TAG, ` ... ${diff.priceChanges.length - 5} more`);
work.push({ s, body, diff, version: conv.regionVersion.version, offerMissing, extraMissing });
}
if (dry) { done(TAG, 'subscriptions planned (dry run, nothing written)'); return; }
const todo = work.filter(w => w.diff.create || w.diff.listings.length || w.diff.basePlan !== 'same' || w.diff.activate || w.offerMissing || w.extraMissing.length);
if (!todo.length) { done(TAG, 'subscriptions up to date'); return; }
const yes = ctx.args.has('yes');
let liveOk = yes;
if (process.stdin.isTTY && !yes) {
if (!(await confirm(ctx, `Write ${todo.length} subscription(s) to Google Play? Activated base plans and offers can be bought as soon as the app is published; price changes apply to new subscribers.`))) return;
liveOk = true;
} else if (!yes) log(TAG, 'not a terminal: creating what is new only; price changes of existing base plans wait for a terminal run');
for (const { s, body, diff, version, offerMissing, extraMissing } of todo) {
const v = encodeURIComponent(version);
const id = encodeURIComponent(s.id);
const cur = existing.get(s.id);
if (diff.create) {
await play.call('POST', `${play.API}/subscriptions?productId=${id}&regionsVersion.version=${v}`, body);
log(TAG, `${s.id}: created`);
} else if (diff.listings.length || diff.basePlan !== 'same') {
if (diff.basePlan === 'changed' && diff.priceChanges.length && !liveOk) warn(TAG, `${s.id}: ${diff.priceChanges.length} price change(s) skipped (run in a terminal to confirm)`);
else {
await play.call('PATCH', `${play.API}/subscriptions/${id}?updateMask=listings,basePlans&regionsVersion.version=${v}`, playPatchSubscription(cur!, body));
log(TAG, `${s.id}: updated`);
}
}
if (diff.activate) {
await play.call('POST', `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}:activate`, { packageName: pkg, productId: s.id, basePlanId: basePlanId(s) });
log(TAG, `${s.id}: base plan ${basePlanId(s)} activated`);
}
const regions = body.basePlans![0]!.regionalConfigs!.map(r => ({ regionCode: r.regionCode, price: r.price! }));
const createOffer = async (o: { type: string; usd?: number }, extra?: NonNullable<typeof s.offers>[number]) => {
let offerRegions;
if (o.type === 'pay-up-front') {
const oc = await convert(o.usd!);
offerRegions = { regions: Object.values(oc.convertedRegionPrices).map(r => ({ regionCode: r.regionCode, price: r.price })), other: oc.convertedOtherRegionsPrice };
}
const ob = playOfferBody(pkg, s, regions, offerRegions, extra);
await play.call('POST', `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers?offerId=${encodeURIComponent(ob.offerId)}&regionsVersion.version=${v}`, ob);
await play.call('POST', `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers/${encodeURIComponent(ob.offerId)}:activate`,
{ packageName: pkg, productId: s.id, basePlanId: basePlanId(s), offerId: ob.offerId });
log(TAG, `${s.id}: offer ${ob.offerId} created and activated`);
};
if (s.intro && offerMissing) await createOffer(s.intro);
for (const o of (s.offers ?? []).filter(x => extraMissing.includes(x.id))) await createOffer(o, o);
}
done(TAG, 'subscriptions done');
}

View file

@ -27,7 +27,7 @@ async function iapId(c: Asc, appId: string, productId: string): Promise<string |
return (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(productId)}`)).data?.[0]?.id ?? null; return (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(productId)}`)).data?.[0]?.id ?? null;
} }
async function appleCurrent(c: Asc, id: string, product: string, withAuto: boolean): Promise<{ rows: PriceRow[]; base: string | null }> { export async function appleCurrent(c: Asc, id: string, product: string, withAuto: boolean): Promise<{ rows: PriceRow[]; base: string | null }> {
const q = 'include=inAppPurchasePricePoint,territory&limit=200'; const q = 'include=inAppPurchasePricePoint,territory&limit=200';
const rows = applePriceRows(product, await pages(c, `/v1/inAppPurchasePriceSchedules/${id}/manualPrices?${q}`)); const rows = applePriceRows(product, await pages(c, `/v1/inAppPurchasePriceSchedules/${id}/manualPrices?${q}`));
if (withAuto) rows.push(...applePriceRows(product, await pages(c, `/v1/inAppPurchasePriceSchedules/${id}/automaticPrices?${q}`), 'auto')); if (withAuto) rows.push(...applePriceRows(product, await pages(c, `/v1/inAppPurchasePriceSchedules/${id}/automaticPrices?${q}`), 'auto'));
@ -36,14 +36,14 @@ async function appleCurrent(c: Asc, id: string, product: string, withAuto: boole
} }
/** data + included of every page of a paged GET (c.all keeps only data). */ /** data + included of every page of a paged GET (c.all keeps only data). */
async function pages(c: Asc, path: string): Promise<{ data: J[]; included: J[] }> { export async function pages(c: Asc, path: string): Promise<{ data: J[]; included: J[] }> {
const out = { data: [] as J[], included: [] as J[] }; const out = { data: [] as J[], included: [] as J[] };
let url: string | null = path; let url: string | null = path;
while (url) { const page: J = await c.asc('GET', url); out.data.push(...(page.data ?? [])); out.included.push(...(page.included ?? [])); url = page.links?.next ?? null; } while (url) { const page: J = await c.asc('GET', url); out.data.push(...(page.data ?? [])); out.included.push(...(page.included ?? [])); url = page.links?.next ?? null; }
return out; return out;
} }
async function playProduct(play: PlayClient, id: string): Promise<PlayProduct | null> { export async function playProduct(play: PlayClient, id: string): Promise<PlayProduct | null> {
try { return await play.call<PlayProduct>('GET', `${play.API}/oneTimeProducts/${encodeURIComponent(id)}`); } try { return await play.call<PlayProduct>('GET', `${play.API}/oneTimeProducts/${encodeURIComponent(id)}`); }
catch (e) { if (/-> 404/.test(String(e))) return null; throw e; } catch (e) { if (/-> 404/.test(String(e))) return null; throw e; }
} }
@ -103,7 +103,7 @@ export async function run(ctx: Ctx): Promise<void> {
if (!changed.size) { done(TAG, 'prices up to date'); return; } if (!changed.size) { done(TAG, 'prices up to date'); return; }
log(TAG, `${changed.size} product / store pair(s) to update`); log(TAG, `${changed.size} product / store pair(s) to update`);
if (dry) { done(TAG, 'dry run: nothing written'); return; } if (dry) { done(TAG, 'dry run: nothing written'); return; }
if (!(await confirm(ctx, `Write the new prices for ${changed.size} product / store pair(s)? Players see them as soon as the stores apply them; an App Store price increase cannot be undone once it starts.`))) return; if (!(await confirm(ctx, `Write the new prices for ${changed.size} product / store pair(s)? Users see them as soon as the stores apply them; an App Store price increase cannot be undone once it starts.`))) return;
for (const p of products) { for (const p of products) {
const wanted = wantedAll.filter(r => r.product === p.id); const wanted = wantedAll.filter(r => r.product === p.id);

View file

@ -0,0 +1,61 @@
---
name: store-subscriptions
description: Set up auto-renewable subscriptions on the App Store and Google Play from one config - Apple subscription groups, levels, localizations, equalized prices with overrides and a price CSV, introductory offers, promotional offers, offer codes and custom codes; Play subscriptions with base plans, regional prices, intro and developer-chosen offers; first submission with a version, the disclosure Apple 3.1.2 and Play's subscription policy require, Terms of Use (EULA) links, price changes and the catalog parity report. Use when the user sells subscriptions, adds a free trial, changes subscription prices, or gets a 3.1.2 / subscription policy rejection.
---
# Subscriptions on both stores
CLI: `storebound apple subscriptions`, `storebound play subscriptions` (both `--dry` first; they print the plan and
ask before writing), `storebound catalog diff` (read-only parity of the whole catalog), `storebound validate`.
Config: `subscriptions: [{ name, listings, subscriptions: [{ id, period, level, usd, overrides, listings, intro,
offers, offerCodes, reviewScreenshot, basePlanId, gracePeriod, platforms }] }]`, `app.termsUrl`.
## Model
- **Apple**: a subscription group per product line (people hold one subscription per group); `level` 1 = highest
service (upgrades and downgrades follow it). Prices: the USA price point for `usd`, its equalizations for every
territory, then `overrides` and rows from `--csv store/prices.csv` (same CSV as `storebound prices`, rows with a
future `start_date` become scheduled price changes). `preserveCurrentPrice` is always true: existing subscribers keep
their price; raising it for them is a separate, consent-bound step in App Store Connect.
- **Google Play**: no groups. Each entry is a Play subscription with one auto-renewing base plan (`basePlanId`
default from the period: monthly, yearly, ...), prices from `convertRegionPrices` + overrides + CSV. A base plan price
change applies to new subscribers; existing ones keep their price until you run a price migration in the Console.
- **Intro offer** (`intro`): free trial, pay as you go (`periods` at `usd`), or pay up front. Apple: per territory,
first-time subscribers of the group. Play: an offer for people who never had this subscription (pay as you go is a
relative discount, so it follows every regional price).
- **Promotional offers** (`offers`, Apple + Play): Apple promotional offers (your server signs them at purchase
time); Play offers with an offer tag and no acquisition targeting (your app decides who sees them).
- **Offer codes** (`offerCodes`, Apple): a campaign (eligibility NEW / EXISTING / EXPIRED, replace or stack with the
intro offer). Custom codes are created only with `--codes` from a terminal that confirms (anyone with the code can
redeem it). One-time-use codes: the owner generates them in App Store Connect. **Play promo codes have no API**:
Play Console > Monetize > Promo codes.
## Steps
1. Prerequisites: Apple Paid Applications agreement, banking and tax; Play payments profile and a build with the
billing library on a track.
2. `storebound check` (limits: Apple name 30 / description 45; Play description 200, up to 4 benefits).
3. `storebound apple subscriptions --dry` and `storebound play subscriptions --dry`; read the plan with the owner; then
run them in a terminal (they ask). Through MCP (no terminal) they only create what is new; price changes of
existing subscriptions wait for the owner.
4. Review screenshot of the paywall per subscription (`reviewScreenshot`), uploaded by `apple subscriptions`.
5. **First subscriptions go with an app version**: on the version page in App Store Connect, add them under
"In-App Purchases and Subscriptions" before Submit for Review (no API; the owner or an agent with browser tools).
6. `storebound validate` (states, localizations, group names, review screenshots, active Play base plans, terms URL)
and `storebound catalog diff` (both stores against the config, prices per region).
## Disclosure (review checks it)
- Purchase screen: plan name, length, **full renewal price per period as the most prominent price**, what is included,
trial length and what is charged after it, how to cancel, Restore Purchases, links to the **Terms of Use** and the
**Privacy Policy** (Apple 3.1.2 and "Clearly describing subscriptions",
https://developer.apple.com/app-store/subscriptions/; Google Play subscriptions policy,
https://support.google.com/googleplay/android-developer/answer/9900533).
- Metadata: the Terms of Use link in the App Store description, or a custom EULA in App Information > License
Agreement; the privacy policy URL field (`storebound apple listing`). `validate` warns when a description has no
Terms link. 3.1.2(a): a subscription must give ongoing value and last at least 7 days.
- Review notes: where the paywall is, that the demo account can buy in the sandbox (`review-access`).
## Gotchas
- A product id, a billing period or a subscription's group cannot change; make a new id.
- Apple applies one introductory offer per customer per group; offers cannot be edited, only replaced.
- Account deletion does not cancel a subscription: say so (`account-deletion`).
- Unverified (no live account during development): free promotional offers and offer codes are sent with
territories but no price point; check the first run in App Store Connect.