glitch-javascript-sdk 4.0.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/dist/cjs/index.js +236 -42
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/api/Microtransactions.d.ts +30 -5
- package/dist/esm/api/Preorders.d.ts +162 -0
- package/dist/esm/api/index.d.ts +1 -0
- package/dist/esm/index.d.ts +3 -0
- package/dist/esm/index.js +221 -32
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/routes/PreordersRoute.d.ts +7 -0
- package/dist/index.d.ts +192 -6
- package/guides/microtransactions.md +318 -25
- package/package.json +4 -3
- package/src/api/Microtransactions.ts +30 -6
- package/src/api/Preorders.ts +234 -0
- package/src/api/index.ts +1 -0
- package/src/index.ts +3 -0
- package/src/routes/PreordersRoute.ts +34 -0
- package/src/util/MicrotransactionOverlay.ts +92 -27
|
@@ -1,16 +1,180 @@
|
|
|
1
1
|
# Game microtransactions
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
## Start with direct REST (recommended for AI/LLM setup)
|
|
4
|
+
|
|
5
|
+
Prefer native fetch/HTTP for a new game integration. **No npm install, SDK import
|
|
6
|
+
or SDK version is a prerequisite.** MCP configures the server directly and the
|
|
7
|
+
runtime REST contract below works without a JavaScript library. The SDK remains
|
|
8
|
+
an optional convenience; preserve existing working SDK-based frontend code.
|
|
9
|
+
|
|
10
|
+
The complete dependency-free modal/verified-callback starter is published in the
|
|
11
|
+
MCP `glitch://microtransactions/setup` resource and the
|
|
12
|
+
`glitch_setup_microtransactions` prompt, also used by the game's AI setup export.
|
|
13
|
+
Use the starter rather than granting inventory in an unchecked message listener.
|
|
14
|
+
The following browser fetch example demonstrates guest transport only:
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
// apiBaseUrl ends in /api; titleId is the configured title, not message input.
|
|
18
|
+
const base = apiBaseUrl.replace(/\/$/, '') + '/titles/'
|
|
19
|
+
+ encodeURIComponent(titleId) + '/microtransactions';
|
|
20
|
+
async function guest(path, body) {
|
|
21
|
+
const response = await fetch(base + path, {
|
|
22
|
+
method: body === undefined ? 'GET' : 'POST', credentials: 'omit', redirect: 'error',
|
|
23
|
+
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
|
24
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
25
|
+
}); // Browser supplies Origin automatically; no Authorization or manual Origin.
|
|
26
|
+
const payload = await response.json();
|
|
27
|
+
if (!response.ok || !payload.data) throw new Error('Commerce unavailable: ' + response.status);
|
|
28
|
+
return payload.data; // ONE JSON envelope, unlike an Axios response.data.data wrapper.
|
|
29
|
+
}
|
|
30
|
+
const catalog = await guest('/catalog?environment=sandbox&country=US¤cy=USD');
|
|
31
|
+
// Call once for this purchase intent, not on every retry/callback.
|
|
32
|
+
const nonce = crypto.randomUUID();
|
|
33
|
+
const session = await guest('/checkout-sessions', {
|
|
34
|
+
product_id: productId, quantity: 1, country: 'US', currency: 'USD', environment: 'sandbox',
|
|
35
|
+
channel: 'web', return_origin: window.location.origin, nonce,
|
|
36
|
+
});
|
|
37
|
+
// Validate the configured checkout origin/path/session/#token, then mount the starter's
|
|
38
|
+
// modal iframe with session.hosted_url. Never assign window.location or grant here.
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
For shell diagnostics only, curl can send `Origin`; browser fetch cannot set it:
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
curl --fail-with-body \
|
|
45
|
+
"$API_BASE_URL/titles/$TITLE_ID/microtransactions/catalog?environment=sandbox&country=US¤cy=USD" \
|
|
46
|
+
-H 'Accept: application/json' -H "Origin: $APPROVED_GAME_ORIGIN"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The variables above are nonsecret integration configuration. Sandbox catalog
|
|
50
|
+
requires enabled sandbox settings and an exact approved Origin. Checkout session
|
|
51
|
+
creation requires enabled matching environment and `return_origin` equal to the
|
|
52
|
+
browser Origin. Live catalog is public but does not authorize payment. Restore
|
|
53
|
+
entry uses `POST /restore-sessions` with environment/return_origin/fresh nonce and
|
|
54
|
+
can remain available after sales stop. Hosted HTTPS policy is not relaxed by
|
|
55
|
+
`environment:sandbox`; HTTP development origins require a local/testing backend.
|
|
56
|
+
|
|
57
|
+
Keep checkout inside the game's accessible modal iframe with pause/resume and
|
|
58
|
+
focus restoration, no top navigation, and bounded Retry/Close for the same
|
|
59
|
+
session. Pin exact checkout origin, actual iframe `contentWindow`, title/session
|
|
60
|
+
and nonce on ready/close/updated messages. `glitch.microtransaction.updated`
|
|
61
|
+
version1 supplies a one-use `claim_code`, not a paid entitlement. Exchange it at
|
|
62
|
+
`POST /handoffs/claim` with `{claim_code,nonce,return_origin,checkout_session_id}`
|
|
63
|
+
using guest headers; deduplicate repeated/in-flight messages. Validate returned
|
|
64
|
+
title/session/order/player and future token expiry, then use the scoped token in
|
|
65
|
+
per-request Authorization to read own `GET /orders/{order_id}` and
|
|
66
|
+
`GET /entitlements?environment=...`. Recheck receipt ownership/status and replace
|
|
67
|
+
inventory. Never increment by product quantity. Defer close until claim and
|
|
68
|
+
inventory work finishes; an uncertain/lost exchange needs restore, not blind replay.
|
|
69
|
+
|
|
70
|
+
Glitch's hosted page handles account creation/login and embedded Stripe/3DS.
|
|
71
|
+
The account JWT never enters the game. `X-Checkout-Token` permits limited session
|
|
72
|
+
status only. Keep the claimed player token in memory, not global auth/storage.
|
|
73
|
+
Own history is `GET /me/purchases?environment=...&page=1&per_page=20`; it does not
|
|
74
|
+
grant items. Explicit spending is `POST /consume` with key/quantity/environment
|
|
75
|
+
and one stable action_id retained across retry, followed by fresh inventory.
|
|
76
|
+
Restore may return `no_purchases_to_restore` for fully refunded-only accounts;
|
|
77
|
+
do not promise a token or repurchase as a history workaround. UI-ready/client
|
|
78
|
+
completion/authorization never proves capture, fulfillment or browser3DS success.
|
|
79
|
+
|
|
80
|
+
Media uploaded with `POST /titles/{title_id}/microtransactions/media` (multipart
|
|
81
|
+
`media`, commerce:write) is **commerce-only**, even though it reuses processing.
|
|
82
|
+
It must not populate title/game previews, galleries, cover or social imagery.
|
|
83
|
+
Attach only same-title commerce Media IDs to products/branding; generic/gallery/
|
|
84
|
+
social assets require separate commerce upload, not relinking. MCP management
|
|
85
|
+
still executes authorized writes without a custom human-confirmation workflow.
|
|
86
|
+
|
|
87
|
+
## Optional JavaScript SDK reference
|
|
88
|
+
|
|
89
|
+
The remainder documents the optional SDK. These versions and imports are not
|
|
90
|
+
requirements for the REST flow above. **Optional player checkout/history minimum:
|
|
91
|
+
SDK `3.15.0`, which is published.** The new
|
|
4
92
|
administrative direct-management API below is a **major SDK `4.0.0` migration**.
|
|
5
|
-
|
|
6
|
-
|
|
93
|
+
Registry verification on September 16, 2026 confirmed SDK `3.15.0`, SDK `4.0.0`
|
|
94
|
+
and MCP `0.5.0` published. SDK4 is not required just for the guest player flow.
|
|
95
|
+
SDK `4.0.1` includes the additive readiness and tax-collection types, checkout
|
|
96
|
+
overlay retry/layout fixes, and tutorial corrections below. Release validation
|
|
97
|
+
is local; no hosted backend deployment was performed for this update.
|
|
98
|
+
Server-side MCP catalog/provider
|
|
7
99
|
setup does not require installing or publishing the game SDK, so do not block
|
|
8
100
|
authorized server configuration while runtime package work is pending.
|
|
9
101
|
|
|
10
102
|
The SDK entry point is `Glitch.api.Microtransactions`. All HTTP methods return an
|
|
11
103
|
Axios response whose `response.data.data` contains the typed commerce result.
|
|
12
104
|
Configure the ordinary API base once using the existing Glitch configuration.
|
|
13
|
-
Never put
|
|
105
|
+
Never put administrative/developer credentials, MCP tokens or provider secrets
|
|
106
|
+
into a shipped browser game. Existing supported **install-purpose runtime tokens**
|
|
107
|
+
are a separate capability: use them only for their documented install, validation,
|
|
108
|
+
heartbeat and telemetry endpoints. They do not authenticate commerce or prove paid
|
|
109
|
+
ownership, and must not be injected into the guest commerce context.
|
|
110
|
+
|
|
111
|
+
## Guest authentication and supported test origins
|
|
112
|
+
|
|
113
|
+
A fresh SDK context has no default auth token. Setting only the API base URL does
|
|
114
|
+
not log in, read credentials from storage, or add a Bearer token. However,
|
|
115
|
+
`Config.setAuthToken` and `Requests.setAuthToken` configure shared global auth:
|
|
116
|
+
`Requests.processRoute` automatically includes that Authorization header, including
|
|
117
|
+
on `catalog`, `createCheckoutSession` and `createRestoreSession`. A per-request
|
|
118
|
+
`{playerToken}` overrides it; `{checkoutToken}` adds only `X-Checkout-Token` and
|
|
119
|
+
does NOT suppress global auth. The published 3.15.0 also appends a selected global
|
|
120
|
+
`community_id` query on these routes (not a body field); 4.0.0 excludes community
|
|
121
|
+
context for commerce. Neither commerce implementation mutates global auth/context.
|
|
122
|
+
|
|
123
|
+
Keep guest commerce in its own credential-free SDK context. Do not initialize it
|
|
124
|
+
with an admin JWT, MCP credential or shared Axios Authorization default/interceptor.
|
|
125
|
+
This does not require removing an unrelated allowed install-purpose token from
|
|
126
|
+
the game's existing install/validation/heartbeat flow or changing global SDK auth.
|
|
127
|
+
Preserve that supported integration; do not reuse its token as commerce auth or
|
|
128
|
+
temporarily clear/replace another context's global auth to make a guest request.
|
|
129
|
+
Keep the owning account JWT inside Glitch's hosted account page, and use
|
|
130
|
+
the verified short-lived player token only in per-request player options. Adding
|
|
131
|
+
an admin JWT to a guest request is not a fix for a hosted sandbox 401.
|
|
132
|
+
|
|
133
|
+
The local backend guest-entry change applies only to `catalog`, `checkout-sessions`
|
|
134
|
+
and `restore-sessions`: use the exact configured browser **gameOrigin**, and for
|
|
135
|
+
session creation set `return_origin` equal to it. Hosted testing requires approved
|
|
136
|
+
**HTTPS** game/API/checkout endpoints. Sandbox catalog/checkout require enabled
|
|
137
|
+
sandbox title settings; sandbox is a payment environment, not a relaxed Origin
|
|
138
|
+
policy. Historical restore entry may remain available with commerce off, but
|
|
139
|
+
the hosted owning-account bind still controls access. Quote/pay/inventory/finance
|
|
140
|
+
do not become anonymous. This contract must be verified on the target backend;
|
|
141
|
+
an SDK transport test alone does not establish that the server fix is deployed.
|
|
142
|
+
|
|
143
|
+
HTTP loopback is only for an explicitly configured **local/testing backend** and
|
|
144
|
+
its approved local game/checkout origins. `allowLocalDevelopment:true` relaxes a
|
|
145
|
+
client helper check only; it cannot authorize localhost against hosted services.
|
|
146
|
+
Published helpers also recognize some development hostnames; that does not make
|
|
147
|
+
those hostnames supported by a hosted backend. Browsers supply `Origin`; never
|
|
148
|
+
spoof it in game code. Use `window.location.origin`, not the full page URL.
|
|
149
|
+
|
|
150
|
+
An origin is scheme + host + port. Paths are NOT an origin boundary: games at
|
|
151
|
+
`https://shared.example/games/a` and `/games/b` have the same origin. Shared S3 or
|
|
152
|
+
CDN hostnames with per-game paths cannot isolate tenants via an origin allowlist.
|
|
153
|
+
Use an independently approved per-game hostname/origin; do not expand an allowlist
|
|
154
|
+
or silently substitute a path to make testing pass.
|
|
155
|
+
|
|
156
|
+
## Configuration readiness versus verified integration
|
|
157
|
+
|
|
158
|
+
Sandbox proof is **optional QA, not required to enable purchases or activate live
|
|
159
|
+
sales**. Authorized developers can enable purchases through normal settings
|
|
160
|
+
without a sandbox order or `integration.verify` call. Actual provider/account,
|
|
161
|
+
market/tax, revenue, payment and fulfillment rules remain enforced.
|
|
162
|
+
|
|
163
|
+
`ready` and optional `configuration_ready` describe configuration only. Optional
|
|
164
|
+
`readiness.integration_verified` means stored sandbox **paid + fulfilled + claimed**
|
|
165
|
+
evidence. Older responses may omit the new field: absence means unknown, not true
|
|
166
|
+
and not false. `settings.integration_verified` already exists separately. A false
|
|
167
|
+
or absent proof flag is not an activation prerequisite and enabling purchases must
|
|
168
|
+
not manufacture a true flag. Neither
|
|
169
|
+
a configuration save, a ready flag, nor an iframe-ready event proves a new payment,
|
|
170
|
+
current inventory delivery or successful claim. Integration evidence is not browser
|
|
171
|
+
3DS certification; record challenge success/cancel/failure separately. Do not call
|
|
172
|
+
`verifyIntegration` or perform a test purchase without authorization.
|
|
173
|
+
|
|
174
|
+
MCP tool discovery is not credential scope. A visible tool can still return 403
|
|
175
|
+
for a missing title ability; that is separate from a guest-entry 401. Preserve the
|
|
176
|
+
status/code and check the effective connection's credential abilities. Do not change
|
|
177
|
+
global connector credentials or broaden permissions as a runtime workaround.
|
|
14
178
|
|
|
15
179
|
## Developer setup
|
|
16
180
|
|
|
@@ -20,9 +184,11 @@ Never put a developer/MCP/install token into a shipped browser game.
|
|
|
20
184
|
The **Enable in-game purchases** and **Show ads** switches live only on the
|
|
21
185
|
game's Pricing/monetization page. Microtransactions is for products, media,
|
|
22
186
|
prices, orders and integration—not a second location for those switches.
|
|
23
|
-
2. `uploadMedia(titleId, file, onProgress?)`
|
|
24
|
-
trusted title/actor ownership. Attach returned `id` to
|
|
25
|
-
`branding.logo_media_id`.
|
|
187
|
+
2. Optional SDK `uploadMedia(titleId, file, onProgress?)` uses the same commerce-only
|
|
188
|
+
Media route and trusted title/actor ownership. Attach returned `id` to
|
|
189
|
+
`media_ids` or `branding.logo_media_id`. It does not populate title/game preview,
|
|
190
|
+
gallery, cover or social imagery. Generic/gallery/social media cannot be
|
|
191
|
+
relinked; upload separately via commerce. No scheduler post is created.
|
|
26
192
|
3. Create a product draft using `createProduct`. Prices use integer minor units,
|
|
27
193
|
not floating-point money: USD 499 means $4.99; JPY 499 means ¥499. Supported
|
|
28
194
|
currencies are USD/EUR/GBP/CAD/AUD/JPY/BRL/INR/KRW; provider coverage can be
|
|
@@ -37,13 +203,83 @@ Never put a developer/MCP/install token into a shipped browser game.
|
|
|
37
203
|
game name/accent/logo with `updateSettings`. The fixed commission is 1200bp
|
|
38
204
|
(12%) of discounted pre-tax subtotal. Actual provider costs are separate.
|
|
39
205
|
Taxes are separate; pending earnings are not a verified available payout.
|
|
40
|
-
6.
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
206
|
+
6. **Optional QA:** if you choose to test, use a real authorized sandbox purchase
|
|
207
|
+
and verified delivery/claim, then optionally call
|
|
208
|
+
`verifyIntegration(titleId, {order_id})`. This still requires real evidence,
|
|
209
|
+
not a self-certified checkbox. It is not required to enable purchases or
|
|
210
|
+
activate live sales. Actual provider/account/tax capability and global sales
|
|
211
|
+
emergency controls still apply; no live test charge is implied by setup.
|
|
44
212
|
|
|
45
213
|
## SDK4.0 administrative migration
|
|
46
214
|
|
|
215
|
+
### Stripe Tax setup is a platform-account workflow
|
|
216
|
+
|
|
217
|
+
Use the [official setup instructions](https://docs.stripe.com/tax/set-up).
|
|
218
|
+
Glitch Checkout and `tax.settings` use the platform processing account, not the
|
|
219
|
+
connected account that receives game proceeds. A personal Stripe account link
|
|
220
|
+
or a `payout_source` change does not fix platform Tax configuration.
|
|
221
|
+
|
|
222
|
+
An unavailable payout recipient does not block otherwise-eligible customer payment
|
|
223
|
+
collection. Proceeds remain held under existing ledger/payout rules after the 12%
|
|
224
|
+
commission and actual fees. Payout onboarding is not tax setup and does not
|
|
225
|
+
reassign historical recipients or release old held funds automatically.
|
|
226
|
+
|
|
227
|
+
Saving `tax_mode:automatic` is a Glitch-managed preference, not self-service Tax
|
|
228
|
+
activation. Read `tax.status`/`missing_fields`; pending `head_office` or
|
|
229
|
+
`platform_tax_settings` needs Glitch platform operations/support. The operator
|
|
230
|
+
must configure the actual processing account with legitimate head-office details,
|
|
231
|
+
preset product classification/default tax behavior, applicable registrations and
|
|
232
|
+
separate filing/remittance setup. Supply support with title/environment and safe
|
|
233
|
+
status information, never invented credentials, addresses or registrations.
|
|
234
|
+
|
|
235
|
+
After that external setup, use the existing provider refresh operation and reread
|
|
236
|
+
the facts. MCP/REST/SDK management can read facts, save preferences and refresh;
|
|
237
|
+
it cannot write platform Tax settings. Optional `tax_code` is route-wide product
|
|
238
|
+
classification, not a registration ID; omitted/null uses the platform default
|
|
239
|
+
when available. Preserve requested/effective `tax_collection` modes and fallback
|
|
240
|
+
reasons. Active tax status does not certify registrations, filing or liability;
|
|
241
|
+
zero collected tax is not necessarily failure or zero tax owed. Payout onboarding
|
|
242
|
+
stays separate. Xsolla is distinct; do not apply Stripe-specific tax assumptions.
|
|
243
|
+
|
|
244
|
+
### SDK 4.0.1 additive follow-up
|
|
245
|
+
|
|
246
|
+
This follow-up adds optional `configuration_ready` and `integration_verified`
|
|
247
|
+
readiness fields; it does not change routes, auth precedence or required player
|
|
248
|
+
request fields. Existing typed DTO literals and older servers remain valid.
|
|
249
|
+
Callers must handle an absent integration flag as unknown. The copyable starter
|
|
250
|
+
now additionally requires `gameOrigin` and `timberGrantKey` (example function
|
|
251
|
+
parameters, not new SDK/API parameters). These additions follow the SDK `4.0.0`
|
|
252
|
+
baseline; local tests do not establish hosted backend deployment.
|
|
253
|
+
|
|
254
|
+
Published SDK3.15.0 CJS and its explicit CommonJS/bundler-interoperable ESM path
|
|
255
|
+
support the guest/account payloads. Its raw native ESM entry contains a legacy
|
|
256
|
+
`require('crypto-js')` during initialization, so it is not a standalone browser
|
|
257
|
+
script-module guarantee. SDK4 CJS and native ESM pass the runtime tests. This
|
|
258
|
+
packaging distinction is separate from backend 401 and does not require an
|
|
259
|
+
already-working SDK3.15 game to upgrade just for player checkout.
|
|
260
|
+
|
|
261
|
+
Local verification (no backend/provider calls):
|
|
262
|
+
|
|
263
|
+
```sh
|
|
264
|
+
npm test
|
|
265
|
+
npx tsc --noEmit
|
|
266
|
+
npm run build
|
|
267
|
+
npm run build-docs
|
|
268
|
+
npm run test:package
|
|
269
|
+
npm run test:commerce-compat -- --published
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
The last command fetches only public npm registry tarballs into memory, verifies
|
|
273
|
+
the pinned SHA-512 values in `scripts/fixtures/published-commerce.json`, and runs
|
|
274
|
+
their unmodified CJS/ESM bundles with an in-memory browser HTTP transport. It also
|
|
275
|
+
records the SDK3.15 raw-ESM caveat separately rather than hiding it with a shim.
|
|
276
|
+
It asserts exact guest bodies/query, no default auth, legacy community injection,
|
|
277
|
+
hosted account-bind and scoped credentials, and old/new readiness response
|
|
278
|
+
pass-through. It does not prove deployed backend authorization, catalog availability,
|
|
279
|
+
payment, fulfillment, claim execution or browser 3DS. Ordinary package tests run
|
|
280
|
+
the local-build part offline. The normal build/build-docs pipeline generates
|
|
281
|
+
artifacts; never hand-edit `dist` or generated API docs.
|
|
282
|
+
|
|
47
283
|
Player checkout, restore, inventory and self-history routes remain compatible with
|
|
48
284
|
SDK3.15. The administrative changes are deliberately major:
|
|
49
285
|
|
|
@@ -131,14 +367,25 @@ Server capability schemas remain authoritative.
|
|
|
131
367
|
Required product fields are **SKU\***, **Name\***, **Type\***, **Prices\*** and
|
|
132
368
|
**Grants\***; each price needs currency, country and integer minor-unit amount,
|
|
133
369
|
and each grant needs key, quantity and kind. A pass also needs duration in seconds.
|
|
134
|
-
For a pack of **100 Timber** spent building things,
|
|
135
|
-
|
|
136
|
-
|
|
370
|
+
For a pack of **100 Timber** spent building things, use that title's actual
|
|
371
|
+
consumable grant key. Keys are title-scoped, not globally reserved: another game
|
|
372
|
+
may already use `timber` as consumable and should pass that exact key. The starter
|
|
373
|
+
requires an explicit key using the existing 1–100 character grammar above;
|
|
374
|
+
namespacing is optional. Validate its canonical grant kind from the title's catalog
|
|
375
|
+
and server-verified inventory, never from the display name. Preserve the per-title
|
|
376
|
+
key/kind invariant and all old grants/orders; never convert durable ownership.
|
|
377
|
+
|
|
378
|
+
**WOTW-specific migration proposal:** WOTW (title ID prefix `ad467`, abbreviated)
|
|
379
|
+
already has durable `timber`. That title needs a coordinated new consumable key
|
|
380
|
+
and game-resource mapping; a new SKU alone cannot retype its existing key.
|
|
381
|
+
`wotw.resource.timber` is one possible new key, not an existing catalog fact or a
|
|
382
|
+
global naming rule. This proposal does not create/publish products or prices or
|
|
383
|
+
authorize a catalog mutation. It does not restrict other titles' consumable keys.
|
|
137
384
|
|
|
138
385
|
## Hosted checkout and account creation
|
|
139
386
|
|
|
140
387
|
`createCheckoutSession(titleId, {product_id,quantity,country,currency,environment,
|
|
141
|
-
channel:'web',return_origin,nonce})`
|
|
388
|
+
channel:'web',return_origin,nonce})` supports guest entry and only opens the purchase
|
|
142
389
|
flow. Use `createMicrotransactionNonce()` to generate the nonce and retain it in
|
|
143
390
|
the game. `hosted_url` points to Glitch's game-branded checkout with the session
|
|
144
391
|
secret in a `#token` fragment, never a query parameter.
|
|
@@ -162,6 +409,15 @@ only after its valid-session account/checkout UI is usable. Exact origin/source/
|
|
|
162
409
|
session/nonce checks protect this signal, and it never grants inventory. Retry
|
|
163
410
|
resets timers; verified readiness and close clear them.
|
|
164
411
|
|
|
412
|
+
Retry first commits `about:blank` inside the existing iframe, then restores the
|
|
413
|
+
exact original hosted URL after that blank document loads. This avoids a
|
|
414
|
+
fragment-only navigation after checkout removes `#token` from its visible URL.
|
|
415
|
+
The iframe and its WindowProxy stay the same, so the existing exact
|
|
416
|
+
origin/source/title/session/nonce bridge remains pinned. No query parameter,
|
|
417
|
+
new checkout session or payment is created. Repeated Retry clicks during this
|
|
418
|
+
navigation are coalesced; each phase has a bounded watchdog, and Close still
|
|
419
|
+
cleans up while navigation or a verified claim is pending.
|
|
420
|
+
|
|
165
421
|
The read-only `getCheckoutFramePolicy(titleId,sessionId)` returns only approved
|
|
166
422
|
`frame_ancestors` and expiry; the hosted document uses that server-owned policy.
|
|
167
423
|
It does not expose a checkout token or player data.
|
|
@@ -186,6 +442,26 @@ and client completion are not paid/delivered proof. Call
|
|
|
186
442
|
`reconcileCheckoutSession(titleId, sessionId, options)` to query the original
|
|
187
443
|
attempt; never charge another provider after an uncertain submission.
|
|
188
444
|
|
|
445
|
+
### Optional saved cards: hosted form only, rollout gated
|
|
446
|
+
|
|
447
|
+
After the `commerce_customer_bindings` migration and matching backend rollout,
|
|
448
|
+
new marked Stripe orders may show native optional save/remove controls inside
|
|
449
|
+
Glitch-hosted payment. [Provider reference](https://docs.stripe.com/payments/checkout/save-during-payment?payment-ui=embedded-page).
|
|
450
|
+
This adds no SDK route or game payment-method API and is not required for enabling
|
|
451
|
+
purchases. Do not promise availability on older deployments or legacy orders.
|
|
452
|
+
|
|
453
|
+
The server binds a customer to the Glitch user/provider/actual processing account/
|
|
454
|
+
environment. Same-user cross-game reuse stays within that scope. Preparing the
|
|
455
|
+
binding may call the provider Customer API but is not a charge; the customer and
|
|
456
|
+
payment payload are frozen before submission. Existing orders/retries remain
|
|
457
|
+
unchanged, and a deleted customer may be replaced only for a new purchase.
|
|
458
|
+
|
|
459
|
+
Saving requires the player's explicit opt-in in the hosted form. It is not
|
|
460
|
+
permission for off-session/autopay; later purchases require user confirmation and
|
|
461
|
+
may require 3DS. Cards cannot cross providers/environments. No Xsolla support is
|
|
462
|
+
implied, and raw card data, customer IDs or payment methods never belong in game,
|
|
463
|
+
admin or MCP APIs. Do not implement card storage in this SDK/game example.
|
|
464
|
+
|
|
189
465
|
## Verified game/account handoff
|
|
190
466
|
|
|
191
467
|
After verified payment and fulfillment, `createHandoff` returns an event with
|
|
@@ -204,9 +480,10 @@ event. Closing checkout without a successful claim does not call this a purchase
|
|
|
204
480
|
### Minimal working Timber shop
|
|
205
481
|
|
|
206
482
|
Copy this JavaScript module into your game's browser bundle. Call
|
|
207
|
-
`installTimberShop` with the title/product IDs
|
|
208
|
-
|
|
209
|
-
|
|
483
|
+
`installTimberShop` with the title/product IDs, exact approved `gameOrigin`,
|
|
484
|
+
API/checkout origins and actual consumable `timberGrantKey` from that title's catalog.
|
|
485
|
+
Use approved HTTPS origins for hosted sandbox testing. HTTP loopback with
|
|
486
|
+
`allowLocalDevelopment:true` additionally requires a local/testing backend.
|
|
210
487
|
The example creates its own small UI, so no undefined HTML elements or game helper
|
|
211
488
|
functions are required. It never takes the player away from the game.
|
|
212
489
|
|
|
@@ -217,8 +494,16 @@ import Glitch, {
|
|
|
217
494
|
openMicrotransactionRestoreOverlay,
|
|
218
495
|
} from 'glitch-javascript-sdk';
|
|
219
496
|
|
|
220
|
-
export function installTimberShop({ titleId, productId, apiBaseUrl, checkoutOrigin,
|
|
497
|
+
export function installTimberShop({ titleId, productId, apiBaseUrl, checkoutOrigin, gameOrigin, timberGrantKey,
|
|
221
498
|
environment = 'sandbox', allowLocalDevelopment = false }) {
|
|
499
|
+
if (new URL(gameOrigin).origin !== gameOrigin || window.location.origin !== gameOrigin) {
|
|
500
|
+
throw new Error('Open the game on its exact approved gameOrigin; a path is not an origin.');
|
|
501
|
+
}
|
|
502
|
+
if (typeof timberGrantKey !== 'string' || timberGrantKey.length < 1 || timberGrantKey.length > 100
|
|
503
|
+
|| /[^A-Za-z0-9_.-]/.test(timberGrantKey)) {
|
|
504
|
+
throw new Error('Supply an explicit grant key: 1–100 letters, numbers, underscores, dots or hyphens.');
|
|
505
|
+
}
|
|
506
|
+
// This game bundle must not configure global account/admin/MCP auth.
|
|
222
507
|
Glitch.util.Requests.setBaseUrl(apiBaseUrl); // Set API location, NOT global auth.
|
|
223
508
|
const api = Glitch.api.Microtransactions;
|
|
224
509
|
const game = { playerId: null, inventory: [], paused: false };
|
|
@@ -232,15 +517,17 @@ export function installTimberShop({ titleId, productId, apiBaseUrl, checkoutOrig
|
|
|
232
517
|
const say = text => { status.textContent = text; };
|
|
233
518
|
|
|
234
519
|
function replaceInventoryInYourGame(entitlements) {
|
|
520
|
+
const resource = entitlements.find(x => x.key === timberGrantKey);
|
|
521
|
+
if (resource && resource.kind !== 'consumable') throw new Error('Timber grant kind mismatch.');
|
|
235
522
|
game.inventory = entitlements; // REPLACE the snapshot. Never add 100 here.
|
|
236
|
-
timber.textContent = 'Timber: ' + (
|
|
523
|
+
timber.textContent = 'Timber: ' + (resource?.balance ?? 0);
|
|
237
524
|
}
|
|
238
525
|
function setGamePaused(paused) { game.paused = paused; }
|
|
239
526
|
function onVerified(result) {
|
|
527
|
+
replaceInventoryInYourGame(result.entitlements); // Validate canonical kind before accepting this account.
|
|
240
528
|
game.playerId = result.player_id; // Associate the game's profile with this player.
|
|
241
529
|
playerToken = result.player_token; // Memory only; never a URL or global auth token.
|
|
242
530
|
tokenExpiresAt = Date.parse(result.expires_at);
|
|
243
|
-
replaceInventoryInYourGame(result.entitlements); // Already verified by Glitch.
|
|
244
531
|
say('Account connected. Your current inventory is ready.');
|
|
245
532
|
}
|
|
246
533
|
function playerOptions() {
|
|
@@ -261,7 +548,7 @@ export function installTimberShop({ titleId, productId, apiBaseUrl, checkoutOrig
|
|
|
261
548
|
if (opening || overlay) return;
|
|
262
549
|
opening = true;
|
|
263
550
|
try {
|
|
264
|
-
const context = { return_origin:
|
|
551
|
+
const context = { return_origin: gameOrigin,
|
|
265
552
|
nonce: createMicrotransactionNonce(), environment };
|
|
266
553
|
const response = restore
|
|
267
554
|
? await api.createRestoreSession(titleId, context)
|
|
@@ -291,12 +578,14 @@ export function installTimberShop({ titleId, productId, apiBaseUrl, checkoutOrig
|
|
|
291
578
|
async function useTenTimber() {
|
|
292
579
|
if (spending || game.paused) return;
|
|
293
580
|
const options = playerOptions();
|
|
581
|
+
const resource = game.inventory.find(x => x.key === timberGrantKey);
|
|
582
|
+
if (!resource || resource.kind !== 'consumable') throw new Error('A verified consumable grant is required.');
|
|
294
583
|
if (pendingUse && pendingUse.playerId !== game.playerId) {
|
|
295
584
|
throw new Error('Restore the original account before retrying its pending action.');
|
|
296
585
|
}
|
|
297
586
|
// Create ONCE for this gameplay intent. A failed retry keeps this same object.
|
|
298
587
|
pendingUse ??= { playerId: game.playerId, action_id: createMicrotransactionNonce(),
|
|
299
|
-
key:
|
|
588
|
+
key: timberGrantKey, quantity: 10 };
|
|
300
589
|
spending = true;
|
|
301
590
|
try {
|
|
302
591
|
await api.consume(titleId, { key: pendingUse.key, quantity: pendingUse.quantity,
|
|
@@ -323,11 +612,15 @@ export function installTimberShop({ titleId, productId, apiBaseUrl, checkoutOrig
|
|
|
323
612
|
```
|
|
324
613
|
|
|
325
614
|
Call `installTimberShop({titleId: YOUR_TITLE_ID, productId: YOUR_TIMBER_PRODUCT_ID,
|
|
326
|
-
apiBaseUrl: YOUR_API_BASE, checkoutOrigin: YOUR_CHECKOUT_ORIGIN
|
|
327
|
-
|
|
615
|
+
apiBaseUrl: YOUR_API_BASE, checkoutOrigin: YOUR_CHECKOUT_ORIGIN,
|
|
616
|
+
gameOrigin: YOUR_APPROVED_GAME_ORIGIN, timberGrantKey: YOUR_CONSUMABLE_GRANT_KEY})`
|
|
617
|
+
from your existing game initialization. These names describe your configuration;
|
|
328
618
|
replace them with the actual values, not credentials. `environment` is optional
|
|
329
619
|
and defaults to sandbox. The example assumes an eligible US/USD price; choose a
|
|
330
620
|
server-supported country/currency for your real player instead of guessing from IP.
|
|
621
|
+
Pass `timberGrantKey:'timber'` when that title's canonical `timber` is consumable.
|
|
622
|
+
The starter checks the returned entitlement kind before accepting an account or
|
|
623
|
+
spending; backend validation remains authoritative. It never changes a grant kind.
|
|
331
624
|
|
|
332
625
|
**`replaceInventoryInYourGame` and `setGamePaused` are example game functions, not
|
|
333
626
|
SDK APIs.** Their working demo bodies update the displayed Timber and `game`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "glitch-javascript-sdk",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.1.0",
|
|
4
4
|
"description": "Javascript SDK for Glitch",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -14,10 +14,11 @@
|
|
|
14
14
|
],
|
|
15
15
|
"types": "dist/index.d.ts",
|
|
16
16
|
"scripts": {
|
|
17
|
-
"test": "node scripts/test-hosting-routes.cjs && node scripts/test-game-advertising-routes.cjs && node scripts/test-game-design-routes.cjs && node scripts/test-discord-media-routes.cjs && node scripts/test-user-email-delivery-routes.cjs && node scripts/test-game-show-ticket-routes.cjs && node scripts/test-festival-networking-routes.cjs && node scripts/test-microtransaction-routes.cjs && node scripts/test-microtransaction-overlay.cjs && node scripts/test-microtransaction-tutorial.cjs",
|
|
17
|
+
"test": "node scripts/test-hosting-routes.cjs && node scripts/test-game-advertising-routes.cjs && node scripts/test-game-design-routes.cjs && node scripts/test-discord-media-routes.cjs && node scripts/test-user-email-delivery-routes.cjs && node scripts/test-game-show-ticket-routes.cjs && node scripts/test-festival-networking-routes.cjs && node scripts/test-microtransaction-routes.cjs && node scripts/test-preorder-routes.cjs && node scripts/test-microtransaction-overlay.cjs && node scripts/test-microtransaction-tutorial.cjs",
|
|
18
18
|
"build": "rm -Rf dist && rollup -c --bundleConfigAsCjs",
|
|
19
19
|
"build-docs": "rm -rf docs && typedoc --tsconfig tsconfig.json src/",
|
|
20
|
-
"test:package": "node scripts/test-package-exports.cjs"
|
|
20
|
+
"test:package": "node scripts/test-package-exports.cjs && npm run test:commerce-compat",
|
|
21
|
+
"test:commerce-compat": "node --experimental-vm-modules scripts/test-commerce-compat.cjs"
|
|
21
22
|
},
|
|
22
23
|
"author": "",
|
|
23
24
|
"license": "ISC",
|
|
@@ -118,6 +118,17 @@ export interface MicrotransactionProduct extends Omit<MicrotransactionProductInp
|
|
|
118
118
|
created_at: string;
|
|
119
119
|
updated_at: string;
|
|
120
120
|
}
|
|
121
|
+
/** Read-only collection facts, not tax exemption or a determination of tax owed. */
|
|
122
|
+
export interface MicrotransactionTaxCollection {
|
|
123
|
+
/** Configured intent stays automatic during a known pending-setup fallback. */
|
|
124
|
+
requested_mode: 'automatic' | 'disabled';
|
|
125
|
+
/** Pending setup may disable collection for a NEW order; unknown facts are null and block new automatic checkout. */
|
|
126
|
+
effective_mode: 'automatic' | 'disabled' | null;
|
|
127
|
+
status: string;
|
|
128
|
+
missing_fields: string[];
|
|
129
|
+
fallback_reason: 'stripe_tax_setup_incomplete' | null;
|
|
130
|
+
warnings: string[];
|
|
131
|
+
}
|
|
121
132
|
export interface MicrotransactionProvider {
|
|
122
133
|
provider: MicrotransactionProviderName;
|
|
123
134
|
environment: MicrotransactionEnvironment;
|
|
@@ -132,10 +143,14 @@ export interface MicrotransactionProvider {
|
|
|
132
143
|
channels: string[];
|
|
133
144
|
payment_methods: string[];
|
|
134
145
|
configuration: MicrotransactionProviderConfiguration;
|
|
135
|
-
account: { id: string; country: string | null; charges_enabled: boolean; payouts_enabled: boolean; requirements_due: string[] } | null;
|
|
146
|
+
account: { id: string; country: string | null; charges_enabled: boolean; payouts_enabled: boolean; requirements_due: string[]; merchant_name?: string | null } | null;
|
|
136
147
|
/** The game's payout target. Do not substitute the platform processing account's payouts_enabled. */
|
|
137
148
|
payout_account: { source: 'platform' | 'user' | 'community' | 'managed'; id: string | null; available: boolean; country: string | null; transfers_active: boolean; payouts_enabled: boolean; requirements_due: string[]; reasons: string[] };
|
|
138
149
|
tax: { status: string; missing_fields: string[] };
|
|
150
|
+
/** Current route facts only. Never use these to reinterpret an existing order's frozen decision. */
|
|
151
|
+
tax_collection?: MicrotransactionTaxCollection | null;
|
|
152
|
+
/** Non-blocking collection warnings, separate from reasons and payout_account availability. */
|
|
153
|
+
warnings?: string[];
|
|
139
154
|
reasons: string[];
|
|
140
155
|
checked_at: string | null;
|
|
141
156
|
revision?: number;
|
|
@@ -147,6 +162,7 @@ export interface MicrotransactionProviderSku {
|
|
|
147
162
|
amount_minor: number;
|
|
148
163
|
}
|
|
149
164
|
export interface MicrotransactionProviderConfiguration {
|
|
165
|
+
/** Requested configuration. Explicit disabled is sandbox-only; pending-setup fallback does not change live configuration to disabled. */
|
|
150
166
|
tax_mode: 'automatic' | 'disabled';
|
|
151
167
|
/** Stripe tax code txcd_ followed by exactly eight digits. */
|
|
152
168
|
tax_code: string | null;
|
|
@@ -247,7 +263,12 @@ export interface MicrotransactionRefundInput extends MicrotransactionLegacyConfi
|
|
|
247
263
|
}
|
|
248
264
|
export interface MicrotransactionReadiness {
|
|
249
265
|
status: 'disabled' | 'draft' | 'sandbox' | 'ready' | 'live' | 'degraded' | 'suspended';
|
|
266
|
+
/** Configuration readiness only; not proof of payment, delivery, claim or browser 3DS. */
|
|
250
267
|
ready: boolean;
|
|
268
|
+
/** Optional on older backends; retains the same configuration meaning as ready. */
|
|
269
|
+
configuration_ready?: boolean;
|
|
270
|
+
/** Stored sandbox paid + fulfilled + claimed evidence. Absent means unknown; not browser/3DS certification. */
|
|
271
|
+
integration_verified?: boolean;
|
|
251
272
|
blockers: string[];
|
|
252
273
|
providers: MicrotransactionProvider[];
|
|
253
274
|
commission_basis_points: 1200;
|
|
@@ -342,6 +363,8 @@ export interface MicrotransactionOrder {
|
|
|
342
363
|
paid_at: string | null;
|
|
343
364
|
refunded_minor: number;
|
|
344
365
|
items: MicrotransactionGrant[];
|
|
366
|
+
/** Frozen decision, also returned inside checkout/session.order. Null/absent for legacy orders; never infer from current provider facts. Warnings do not imply zero tax owed. */
|
|
367
|
+
tax_collection?: MicrotransactionTaxCollection | null;
|
|
345
368
|
entitlements?: MicrotransactionEntitlement[];
|
|
346
369
|
}
|
|
347
370
|
export interface MicrotransactionOrderDetail extends MicrotransactionOrder {
|
|
@@ -523,8 +546,9 @@ export interface MicrotransactionCapabilities {
|
|
|
523
546
|
}
|
|
524
547
|
|
|
525
548
|
/**
|
|
526
|
-
* Provider-neutral, title-scoped commerce.
|
|
527
|
-
*
|
|
549
|
+
* Provider-neutral, title-scoped commerce. Guest games configure only the API
|
|
550
|
+
* base URL, never global account/admin auth. Hosted account pages use their own
|
|
551
|
+
* user JWT and limited checkout capability; playerToken overrides auth per request. Install/title
|
|
528
552
|
* tokens cannot authorize money, ownership, refunds, or catalog changes.
|
|
529
553
|
*
|
|
530
554
|
* Each result preserves payment versus fulfillment versus settlement. Redirects
|
|
@@ -609,13 +633,13 @@ class Microtransactions {
|
|
|
609
633
|
}
|
|
610
634
|
/** Replay the same immutable event. Receiver must deduplicate event_id. This cannot mint goods. */
|
|
611
635
|
static replayDelivery(title_id: string, delivery_id: string, data: MicrotransactionLegacyConfirmation = {}, options?: MicrotransactionRequestOptions) { return this.call<MicrotransactionDeliveryResult>('replayDelivery', title_id, data, { delivery_id }, undefined, options); }
|
|
612
|
-
/**
|
|
636
|
+
/** Guest catalog on the exact approved game Origin. Sandbox requires enabled sandbox settings; the backend enforces environment policy. */
|
|
613
637
|
static catalog(title_id: string, params?: MicrotransactionCatalogFilter, options?: MicrotransactionRequestOptions) { return this.call<MicrotransactionCatalog>('catalog', title_id, undefined, {}, params, options); }
|
|
614
638
|
/** User-authenticated quote. Clients select product/quantity, never monetary values or seller accounts. */
|
|
615
639
|
static createQuote(title_id: string, data: MicrotransactionPurchaseInput, options?: MicrotransactionRequestOptions) { return this.call<MicrotransactionQuote>('createQuote', title_id, data, {}, undefined, options); }
|
|
616
|
-
/**
|
|
640
|
+
/** Guest opening only: browser Origin must equal approved return_origin. Inherits configured global auth; use an isolated credential-free game context. Hosted UI authenticates before payment. */
|
|
617
641
|
static createCheckoutSession(title_id: string, data: MicrotransactionCheckoutSessionInput, options?: MicrotransactionRequestOptions) { return this.call<MicrotransactionCreatedCheckoutSession>('createCheckoutSession', title_id, data, {}, undefined, options); }
|
|
618
|
-
/**
|
|
642
|
+
/** Guest entry to hosted recovery, not inventory access. Exact approved Origin/return_origin required. Owning-account bind remains mandatory, including when commerce is off. Never install an account JWT in the game. */
|
|
619
643
|
static createRestoreSession(title_id: string, data: { return_origin: string; nonce: string; environment: MicrotransactionEnvironment }, options?: MicrotransactionRequestOptions) { return this.call<MicrotransactionCreatedCheckoutSession>('createRestoreSession', title_id, data, {}, undefined, options); }
|
|
620
644
|
/** Read the session using its limited capability. Cannot mutate user identity or declare payment. */
|
|
621
645
|
static getCheckoutSession(title_id: string, session_id: string, options: MicrotransactionSessionOptions) { return this.call<MicrotransactionCheckoutSession>('checkoutSession', title_id, undefined, { session_id }, undefined, options); }
|