A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(sdk): in-game purchase, and the device it is not allowed on
yhh86d100dba685
diff --git a/docs/astro/src/content/docs/guides/services.mdx b/docs/astro/src/content/docs/guides/services.mdxindex 4f2467db9..172a9ee82 100644--- a/docs/astro/src/content/docs/guides/services.mdx+++ b/docs/astro/src/content/docs/guides/services.mdx@@ -186,3 +186,42 @@ still the real renderer, so rehearsing them tells you something. A pretend codeis a string no server can exchange — rehearsing with it would only rehearse arequest that is going to fail. Off-platform, `available` is `false`, and a gametakes whatever path it takes when there is no account.++## In-game purchase++Buying inside a mini-game is a **permission, not a feature**. On WeChat it is+Android-only: the call is present on an iPhone and the platform refuses it. So+`available` answers for the **device**, and a shop asks before it opens rather+than finding out when someone taps Buy.++```typescript+import { defineSystem, Res, Payment } from 'esengine';++if (!payment.available) return; // iOS, web, native — do not open the shop++try {+ await payment.request({ offerId: 'your-offer-id', quantity: 10 });+ // The HOST says the purchase completed. Now ask YOUR server what the player+ // owns — do not add the coins here.+ await refreshInventoryFromYourServer();+} catch (err) {+ // The host's own message and code, including "the player changed their mind".+ // Those are different UI, and only the host can tell them apart.+ if ((err as { code?: number }).code === /* your host's cancel code */ 2) return;+ showPurchaseFailed(err);+}+```++Pass `sandbox: true` while you build the flow, and `zoneId` if your game has+more than one server.++Two things this service deliberately does not do. It **does not interpret the+host's error codes** — they differ between vendors, and a mapping invented in+the engine is a guess your game would then branch on. And it **grants nothing**:+a purchase the client believes in is a purchase an attacker can claim. The host+notifies your server, and your server is what hands out currency; `request()`+resolving is the cue to go and ask it.++There is no local stand-in in play mode, for the same reason sign-in has none —+a rehearsed purchase that charges nothing and grants nothing rehearses only the+dialog, and the part that goes wrong is behind it.diff --git a/docs/astro/src/content/docs/zh-cn/guides/services.mdx b/docs/astro/src/content/docs/zh-cn/guides/services.mdxindex e1998f038..d8ffc4627 100644--- a/docs/astro/src/content/docs/zh-cn/guides/services.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/services.mdx@@ -169,3 +169,37 @@ code**。是真的渲染器,排练它们有意义;而假 code 是任何服务器都换不了的字符串——拿它排练,排练的只是一个注定失败的请求。在没有该能力的平台上 `available` 是 `false`,游戏走它在「没有账号」时本来该走的那条路。++## 内购++在小游戏里付费是一种**权限,不是功能**。微信上它**只在安卓可用**:在 iPhone 上这个+调用是存在的,而平台会拒绝它。所以 `available` 回答的是**这台设备**能不能买,商店+应该在打开之前就问,而不是等玩家点了「购买」才发现。++```typescript+import { defineSystem, Res, Payment } from 'esengine';++if (!payment.available) return; // iOS、网页、原生——不要打开商店++try {+ await payment.request({ offerId: '你的 offerId', quantity: 10 });+ // 是**宿主**说购买完成了。现在去问**你自己的服务器**玩家拥有什么,+ // 不要在这里发货。+ await refreshInventoryFromYourServer();+} catch (err) {+ // 宿主自己的消息和错误码,包括「玩家改主意了」。+ // 这两种要不同的 UI,而只有宿主分得清。+ if ((err as { code?: number }).code === /* 你的宿主的取消码 */ 2) return;+ showPurchaseFailed(err);+}+```++调试期传 `sandbox: true`;游戏有多个区服时传 `zoneId`。++这个服务**刻意不做**两件事。它**不解释宿主的错误码**——各家不一样,引擎自己编一张+映射表就是一个猜测,而你的游戏会照着它分支。它也**不发货**:客户端相信的购买等于+攻击者可以声称的购买。宿主通知的是**你的服务器**,发货是服务器的事;`request()`+resolve 只是「去问服务器」的信号。++Play 模式里没有本地替身,理由和登录那节一样——一次不扣钱也不发货的排练,排练的只有+那个弹窗,而真正会出问题的是弹窗后面。diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex d3acc7a11..34c4b4e09 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1402 stable · 17 beta · 1 deprecated+Symbols: 1406 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -4599,6 +4599,29 @@ diagonal: boolean | undefinedsnapRadius: number | undefined```+## Payment — const+```+ResourceDef<PaymentAPI>+```++## PaymentAPI — class+```+available: boolean+request: (request: PaymentRequest) => Promise<void>+static new (): PaymentAPI+static prototype: PaymentAPI+```++## PaymentFailure — interface+```+code: number | undefined+```++## PaymentRequest — type+```+PlatformPaymentRequest+```+## Perceiver — const```ComponentDef<PerceiverData>@@ -4820,6 +4843,7 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => void@@ -4856,6 +4880,7 @@ readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => void+requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefineddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex dbe5b5830..118687e10 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1421 stable · 22 beta · 1 deprecated+Symbols: 1425 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -4755,6 +4755,29 @@ diagonal: boolean | undefinedsnapRadius: number | undefined```+## Payment — const+```+ResourceDef<PaymentAPI>+```++## PaymentAPI — class+```+available: boolean+request: (request: PaymentRequest) => Promise<void>+static new (): PaymentAPI+static prototype: PaymentAPI+```++## PaymentFailure — interface+```+code: number | undefined+```++## PaymentRequest — type+```+PlatformPaymentRequest+```+## Perceiver — const```ComponentDef<PerceiverData>@@ -4976,6 +4999,7 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => void@@ -5012,6 +5036,7 @@ readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => void+requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefineddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 511bb8dad..45b7d6dd4 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1401 stable · 19 beta · 1 deprecated+Symbols: 1405 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -4594,6 +4594,29 @@ diagonal: boolean | undefinedsnapRadius: number | undefined```+## Payment — const+```+ResourceDef<PaymentAPI>+```++## PaymentAPI — class+```+available: boolean+request: (request: PaymentRequest) => Promise<void>+static new (): PaymentAPI+static prototype: PaymentAPI+```++## PaymentFailure — interface+```+code: number | undefined+```++## PaymentRequest — type+```+PlatformPaymentRequest+```+## Perceiver — const```ComponentDef<PerceiverData>@@ -4815,6 +4838,7 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => void@@ -4851,6 +4875,7 @@ readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => void+requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefineddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 087c74d37..49d7497d7 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1422 stable · 17 beta · 1 deprecated+Symbols: 1426 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -4239,6 +4239,7 @@ onTouchMove: (cb: (res: MiniGameTouchEvent) => void) => voidonTouchStart: (cb: (res: MiniGameTouchEvent) => void) => voidremoveStorageSync: (key: string) => voidrequest: (opts: MiniGameRequestOptions) => void+requestMidasPayment: ((opts: { mode: string; offerId: string; buyQuantity: number; zoneId?: string; currencyType?: string; platform?: string; env?: number; success?: () => void; fail?: (err: { errMsg?: string; errCode?: number; }) => void; }) => void) | undefinedsetStorageSync: (key: string, value: string) => voidsetUserCloudStorage: ((opts: { KVDataList: MiniGameKVData[]; success?: () => void; fail?: (err: unknown) => void; complete?: () => void; }) => void) | undefinedshareAppMessage: ((opts: MiniGameShareOptions) => void) | undefined@@ -4280,6 +4281,7 @@ code: string## MiniGamePlatformAdapter — class```bindInputEvents: (callbacks: InputEventCallbacks, _target?: unknown) => void+canPay: () => booleancanSignIn: () => booleancheckSession: () => Promise<boolean>clearStorage: (prefix: string) => void@@ -4310,6 +4312,7 @@ openDataPostMessage: (message: Record<string, unknown>) => voidreadFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>removeStorageItem: (key: string) => void+requestPayment: (request: PlatformPaymentRequest) => Promise<void>setCloudKeyValues: (entries: Readonly<Record<string, string>>) => booleansetStorageItem: (key: string, value: string) => voidshare: (options: PlatformShareOptions) => void@@ -4393,6 +4396,7 @@ keys: string[]```language: string | undefinedpixelRatio: number | undefined+platform: string | undefinedwindowHeight: number | undefinedwindowWidth: number | undefined```@@ -4827,6 +4831,29 @@ diagonal: boolean | undefinedsnapRadius: number | undefined```+## Payment — const+```+ResourceDef<PaymentAPI>+```++## PaymentAPI — class+```+available: boolean+request: (request: PaymentRequest) => Promise<void>+static new (): PaymentAPI+static prototype: PaymentAPI+```++## PaymentFailure — interface+```+code: number | undefined+```++## PaymentRequest — type+```+PlatformPaymentRequest+```+## Perceiver — const```ComponentDef<PerceiverData>@@ -5048,6 +5075,7 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => void@@ -5084,6 +5112,7 @@ readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => void+requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefineddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 4950a7d7b..9f15b711d 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1412 stable · 17 beta · 1 deprecated+Symbols: 1416 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -4601,6 +4601,29 @@ diagonal: boolean | undefinedsnapRadius: number | undefined```+## Payment — const+```+ResourceDef<PaymentAPI>+```++## PaymentAPI — class+```+available: boolean+request: (request: PaymentRequest) => Promise<void>+static new (): PaymentAPI+static prototype: PaymentAPI+```++## PaymentFailure — interface+```+code: number | undefined+```++## PaymentRequest — type+```+PlatformPaymentRequest+```+## Perceiver — const```ComponentDef<PerceiverData>@@ -4822,6 +4845,7 @@ _physics_updateBodyProperties: (entityId: number, bodyType: number, gravityScale## PlatformAdapter — interface```bindInputEvents: (callbacks: InputEventCallbacks, target?: unknown) => void+canPay: (() => boolean) | undefinedcanSignIn: (() => boolean) | undefinedcheckSession: (() => Promise<boolean>) | undefinedclearStorage: (prefix: string) => void@@ -4858,6 +4882,7 @@ readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>registerFont: ((family: string, bytes: ArrayBuffer) => Promise<void>) | undefinedremoveStorageItem: (key: string) => void+requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefineddiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 74bf2a14c..e59b70209 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -406,11 +406,12 @@ export {Ads, AdsAPI, createMockAdProvider,Share, ShareAPI,Leaderboard, LeaderboardAPI, createLocalLeaderboard,- Identity, IdentityAPI,+ Identity, IdentityAPI, Payment, PaymentAPI,ServicesPlugin, servicesPlugin,type AdProvider, type AdsHost, type MockAdProviderOptions, type ShareCard,type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,type LeaderboardStyle, type LocalLeaderboardOptions, type LoginResult,+ type PaymentRequest, type PaymentFailure,} from './services';// =============================================================================diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.tsindex a0d57f47d..f151cee60 100644--- a/sdk/src/platform/base.ts+++ b/sdk/src/platform/base.ts@@ -324,6 +324,23 @@ export function platformCheckSession(): Promise<boolean> {return getPlatform().checkSession?.() ?? Promise.resolve(false);}+/** Whether a purchase may happen here at all — declared by the platform, and+ * permitted on THIS device. See `PlatformAdapter.canPay`. */+export function platformCanPay(): boolean {+ if (!isPlatformInitialized()) return false;+ const p = getPlatform();+ return p.requestPayment !== undefined && (p.canPay?.() ?? true);+}++/** Buy in-game currency; rejects where purchase is not available, so a caller+ * that skipped {@link platformCanPay} hears why rather than hanging. */+export function platformRequestPayment(request: import('./types').PlatformPaymentRequest): Promise<void> {+ if (!platformCanPay()) {+ return Promise.reject(new Error('in-game purchase is not available on this platform'));+ }+ return getPlatform().requestPayment!(request);+}+/*** Whether this platform has a USABLE open data context — what a leaderboard* reads to hide itself honestly (web, native and the editor have none).diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.tsindex 8982c60e9..d22609715 100644--- a/sdk/src/platform/index.ts+++ b/sdk/src/platform/index.ts@@ -61,6 +61,8 @@ export {platformShare,platformOnShareRequest,platformCanSignIn,+ platformCanPay,+ platformRequestPayment,platformLogin,platformCheckSession,platformCanOpenData,diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.tsindex 7281c8d72..3cdcc90e6 100644--- a/sdk/src/platform/minigame/adapter.ts+++ b/sdk/src/platform/minigame/adapter.ts@@ -27,6 +27,7 @@ import type {PlatformRewardedAdResult,PlatformInterstitialAd,PlatformShareOptions,+ PlatformPaymentRequest,} from '../types';import type { PlatformAudioBackend } from '../../audio/PlatformAudioBackend';import type { PlatformVideoBackend, VideoBackendContext } from '../../video/PlatformVideoBackend';@@ -192,6 +193,54 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {return this.g_.login !== undefined;}+ /**+ * Whether a purchase may happen on THIS device.+ *+ * Paying inside a mini-game is an Android-only permission: the call exists+ * on an iPhone and the platform refuses it. That is a rule, not a fault, so+ * it belongs in the capability rather than in an error a game discovers by+ * charging someone. Devtools counts — that is where a purchase flow is+ * built, against the host's sandbox.+ */+ canPay(): boolean {+ if (!this.g_.requestMidasPayment) return false;+ const where = this.g_.getSystemInfoSync().platform;+ // Unknown means a host that did not say. Treated as allowed: refusing+ // on silence would disable purchase on any vendor whose system info we+ // have not met, and the host still gets the final word at call time.+ return where === undefined || where === 'android' || where === 'devtools';+ }++ /** Buy in-game currency. Rejects with the host's own reason: "the purchase+ * failed" without a code cannot be told apart from the player changing+ * their mind, and those need different UI. */+ requestPayment(request: PlatformPaymentRequest): Promise<void> {+ const pay = this.g_.requestMidasPayment;+ if (!pay) return Promise.reject(new Error('this host sells nothing'));+ return new Promise<void>((resolve, reject) => {+ pay.call(this.g_, {+ mode: 'game',+ offerId: request.offerId,+ buyQuantity: request.quantity,+ zoneId: request.zoneId ?? '1',+ currencyType: 'CNY',+ // Named explicitly rather than left to the host's default: the+ // one platform this is allowed on is the one it must say.+ platform: 'android',+ ...(request.sandbox ? { env: 1 } : {}),+ success: () => resolve(),+ fail: (err) => {+ const e = new Error(err?.errMsg ?? 'payment failed') as Error & { code?: number };+ // Carried, not interpreted: the codes are the host's, they+ // differ between vendors, and a mapping this layer invented+ // would be a guess a game then branches on.+ e.code = err?.errCode;+ reject(e);+ },+ });+ });+ }+/** Begin a sign-in, as a promise. Rejects with the host's own words: this* is a network round trip and "it failed" without why is unactionable. */login(): Promise<string> {diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.tsindex b3c9f1b45..f9f5155a0 100644--- a/sdk/src/platform/minigame/api.ts+++ b/sdk/src/platform/minigame/api.ts@@ -73,6 +73,10 @@ export interface MiniGameSystemInfo {language?: string;windowWidth?: number;windowHeight?: number;+ /** Where the host itself is running — `ios`, `android`, `devtools`, … Not+ * cosmetic: in-game purchase is permitted on some of these and forbidden+ * on others, so a capability has to read it. */+ platform?: string;}export interface MiniGameTouch {@@ -256,6 +260,21 @@ export interface MiniGameGlobal {* answer by WHICH callback it calls, not by a value. */checkSession?(opts: { success?: () => void; fail?: (err: unknown) => void }): void;+ /** In-game purchase of the host's currency. Present on the global whatever+ * device it is running on — whether it may actually be CALLED is a+ * platform rule, not an API-shape question. See `MiniGamePlatformAdapter.canPay`. */+ requestMidasPayment?(opts: {+ mode: string;+ offerId: string;+ buyQuantity: number;+ zoneId?: string;+ currencyType?: string;+ platform?: string;+ env?: number;+ success?: () => void;+ fail?: (err: { errMsg?: string; errCode?: number }) => void;+ }): void;+/** The open data context, if this host has one. Absent on a host without* friend data, and on a game whose package declares no context directory. */getOpenDataContext?(): MiniGameOpenDataContext;diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex 6449fee8b..4820ecf16 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -531,6 +531,20 @@ export interface PlatformAdapter {* and presence stands; a family answers for the host it actually wraps.*/canSignIn?(): boolean;++ /**+ * Whether in-game purchase is permitted HERE.+ *+ * A separate question from whether the host exposes the call, and the+ * reason this is a capability rather than a try-and-see: on WeChat, paying+ * inside a mini-game is an Android-only permission — the API is present on+ * an iPhone and refusing it is the platform's rule, not a fault. A game has+ * to be able to ask before it shows a shop.+ */+ canPay?(): boolean;+ /** Buy `quantity` units of the host's in-game currency. Resolves when the+ * host reports the purchase done; rejects with the host's own reason. */+ requestPayment?(request: PlatformPaymentRequest): Promise<void>;/** Whether the host still regards the last sign-in as current, so a game* can skip re-exchanging a code it does not need. */checkSession?(): Promise<boolean>;@@ -576,6 +590,19 @@ export interface PlatformInterstitialAd {destroy(): void;}+/** One in-game purchase, in the vocabulary every mini-game host shares. */+export interface PlatformPaymentRequest {+ /** The offer this game sells under, from the host's developer console. */+ offerId: string;+ /** How many units of the host's in-game currency to buy. */+ quantity: number;+ /** Which of the game's zones/servers the currency lands in. Hosts default+ * it to the first one; a single-zone game can leave it out. */+ zoneId?: string;+ /** Use the host's sandbox rather than charging real money. */+ sandbox?: boolean;+}+/** The share card for an active or passive share. `query` rides the launch* options of whoever opens the shared card (invite links, room codes). */export interface PlatformShareOptions {diff --git a/sdk/src/services/index.ts b/sdk/src/services/index.tsindex 6d7bfcc5b..010e30cb6 100644--- a/sdk/src/services/index.ts+++ b/sdk/src/services/index.ts@@ -11,4 +11,5 @@ export {type LeaderboardStyle, type LocalLeaderboardOptions,} from './leaderboard';export { Identity, IdentityAPI, type LoginResult } from './identity';+export { Payment, PaymentAPI, type PaymentRequest, type PaymentFailure } from './payment';export { ServicesPlugin, servicesPlugin } from './servicesPlugin';diff --git a/sdk/src/services/payment.ts b/sdk/src/services/payment.tsnew file mode 100644index 000000000..e0fbaf0d7--- /dev/null+++ b/sdk/src/services/payment.ts@@ -0,0 +1,69 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file payment.ts+ * @brief In-game purchase as an engine service — including where it is not+ * allowed to happen.+ *+ * Buying inside a mini-game is a PERMISSION, not a feature: on WeChat it is+ * Android-only, and the same call on an iPhone is refused by the platform. The+ * API exists there; the purchase does not. So `available` answers for the+ * DEVICE, not for the API, and a shop asks it before it opens rather than+ * finding out when someone taps Buy.+ *+ * What this service deliberately does NOT do:+ *+ * It does not interpret the host's error codes. They differ between vendors+ * and a mapping invented here is a guess a game would then branch on — so the+ * code is carried through, named, for the game to read against its host's own+ * table.+ *+ * It does not grant anything. A purchase the CLIENT believes in is a purchase+ * an attacker can claim; the host notifies the game's own server, and that is+ * what may hand out currency. This resolving means "the host says the+ * purchase completed", which is the cue to go ASK your server, not to add+ * coins.+ *+ * It has no local stand-in for play mode, for the same reason sign-in has+ * none: a rehearsed purchase that charges nothing and grants nothing rehearses+ * only the dialog, and the part that goes wrong is the part behind it.+ */+import { defineResource } from '../ecs/resource';+import { platformCanPay, platformRequestPayment } from '../platform';+import type { PlatformPaymentRequest } from '../platform/types';++export type PaymentRequest = PlatformPaymentRequest;++/** A purchase that did not complete. `code` is the HOST's — see the file+ * header for why it is not translated. */+export interface PaymentFailure extends Error {+ code?: number;+}++export class PaymentAPI {+ /**+ * Whether this device may buy at all.+ *+ * False on iOS even though the host exposes the call, false off-platform,+ * false on a vendor with no purchase API. A shop reads this to stay closed+ * rather than to open and fail.+ */+ get available(): boolean {+ return platformCanPay();+ }++ /**+ * Buy `quantity` units of the host's in-game currency.+ *+ * Resolves when the HOST says the purchase completed — which is the moment+ * to ask your own server what the player now owns, not the moment to grant+ * it. Rejects with the host's own message and code, including when the+ * player simply changed their mind: those are different UI, and only the+ * host can tell them apart.+ */+ request(request: PaymentRequest): Promise<void> {+ return platformRequestPayment(request);+ }+}++export const Payment = defineResource<PaymentAPI>(null!, 'Payment');diff --git a/sdk/src/services/servicesPlugin.ts b/sdk/src/services/servicesPlugin.tsindex 2be539239..ac23535fc 100644--- a/sdk/src/services/servicesPlugin.ts+++ b/sdk/src/services/servicesPlugin.ts@@ -22,6 +22,7 @@ import { Ads, AdsAPI } from './ads';import { Share, ShareAPI } from './share';import { Leaderboard, LeaderboardAPI } from './leaderboard';import { Identity, IdentityAPI } from './identity';+import { Payment, PaymentAPI } from './payment';export class ServicesPlugin implements Plugin {name = 'Services';@@ -38,6 +39,7 @@ export class ServicesPlugin implements Plugin {}));app.insertResource(Share, new ShareAPI());app.insertResource(Identity, new IdentityAPI());+ app.insertResource(Payment, new PaymentAPI());// Resolved per call rather than captured: the module is attached by// connectCpp, which can run after the plugins have built.app.insertResource(Leaderboard, new LeaderboardAPI(() => app.wasmModule));diff --git a/sdk/tests/payment.test.ts b/sdk/tests/payment.test.tsnew file mode 100644index 000000000..11e9de670--- /dev/null+++ b/sdk/tests/payment.test.ts@@ -0,0 +1,119 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file In-game purchase, and the device it is not allowed on.+ *+ * The thing worth pinning is the permission: the call exists on an iPhone and+ * the platform refuses it, so `available` has to answer for the DEVICE. A shop+ * that read the API's existence would open and then fail at the tap.+ */+import { describe, it, expect } from 'vitest';+import { PaymentAPI } from '../src/services/payment';+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';+import { setPlatform } from '../src/platform/base';+import type { MiniGameGlobal, MiniGameProfile } from '../src/platform/minigame/api';+import type { PlatformAdapter } from '../src/platform/types';++type PayOpts = Parameters<NonNullable<MiniGameGlobal['requestMidasPayment']>>[0];++function host(opts: { where?: string; pay?: (o: PayOpts) => void } = {}): {+ api: PaymentAPI; calls: PayOpts[];+} {+ const calls: PayOpts[] = [];+ const profile: MiniGameProfile = {+ id: 'wechat',+ hostLabel: 'Test',+ global: {+ getSystemInfoSync: () => ({ pixelRatio: 1, platform: opts.where ?? 'android' }),+ ...(opts.pay === undefined+ ? { requestMidasPayment: (o: PayOpts) => { calls.push(o); o.success?.(); } }+ : { requestMidasPayment: (o: PayOpts) => { calls.push(o); opts.pay!(o); } }),+ } as unknown as MiniGameGlobal,+ };+ setPlatform(new MiniGamePlatformAdapter(profile));+ return { api: new PaymentAPI(), calls };+}++/** A mini-game host with no purchase API at all. */+function hostWithoutPay(): PaymentAPI {+ setPlatform(new MiniGamePlatformAdapter({+ id: 'wechat', hostLabel: 'Test',+ global: { getSystemInfoSync: () => ({ platform: 'android' }) } as unknown as MiniGameGlobal,+ }));+ return new PaymentAPI();+}++describe('available', () => {+ it('is true on Android, where buying is permitted', () => {+ expect(host({ where: 'android' }).api.available).toBe(true);+ });++ it('is FALSE on iOS, where the call exists and the platform refuses it', () => {+ // The whole reason this is a capability and not a try-and-see.+ expect(host({ where: 'ios' }).api.available).toBe(false);+ });++ it('is true in devtools, which is where a purchase flow gets built', () => {+ expect(host({ where: 'devtools' }).api.available).toBe(true);+ });++ it('is true on a host that did not say where it is running', () => {+ // Refusing on silence would disable purchase on any vendor whose system+ // info we have not met; the host still gets the final word at call time.+ expect(host({ where: undefined }).api.available).toBe(true);+ });++ it('is false with no purchase API, and off-platform', () => {+ expect(hostWithoutPay().available).toBe(false);+ setPlatform({ name: 'web', devicePixelRatio: () => 1 } as unknown as PlatformAdapter);+ expect(new PaymentAPI().available).toBe(false);+ });+});++describe('request', () => {+ it('sends the offer, the quantity and the zone', async () => {+ const h = host();+ await h.api.request({ offerId: 'offer-1', quantity: 3, zoneId: '7' });+ expect(h.calls[0]).toMatchObject({ mode: 'game', offerId: 'offer-1', buyQuantity: 3, zoneId: '7' });+ });++ it('defaults the zone rather than leaving it to the host', async () => {+ const h = host();+ await h.api.request({ offerId: 'o', quantity: 1 });+ expect(h.calls[0].zoneId).toBe('1');+ });++ it('names the one platform this is allowed on', async () => {+ const h = host();+ await h.api.request({ offerId: 'o', quantity: 1 });+ expect(h.calls[0].platform).toBe('android');+ });++ it('asks for the sandbox only when told to', async () => {+ const real = host();+ await real.api.request({ offerId: 'o', quantity: 1 });+ expect(real.calls[0].env).toBeUndefined();++ const test = host();+ await test.api.request({ offerId: 'o', quantity: 1, sandbox: true });+ expect(test.calls[0].env).toBe(1);+ });++ it('carries the host\'s message AND code, without interpreting either', async () => {+ // A cancel and a failure need different UI, and only the host can tell+ // them apart — a mapping invented here is a guess a game branches on.+ const h = host({ pay: (o) => o.fail?.({ errMsg: 'requestMidasPayment:fail cancel', errCode: 2 }) });+ await expect(h.api.request({ offerId: 'o', quantity: 1 }))+ .rejects.toMatchObject({ message: expect.stringContaining('cancel'), code: 2 });+ });++ it('rejects on iOS instead of charging, and says why', async () => {+ const h = host({ where: 'ios' });+ await expect(h.api.request({ offerId: 'o', quantity: 1 })).rejects.toThrow(/not available on this platform/);+ expect(h.calls).toEqual([]);+ });++ it('rejects rather than hanging where nothing is sold', async () => {+ await expect(hostWithoutPay().request({ offerId: 'o', quantity: 1 })).rejects.toThrow(/not available/);+ });+});