跳转到内容

网页脚本

kasskeep-web.js 是一个零依赖的 ES 模块,和 SDK tarball 一起发布(dist-release/kasskeep-web.js,附带类型定义)。把它复制到你的网页项目里。它还会设置 globalThis.KasskeepWeb。

它适用于三种情况:

模式 何时 行为
native 在注入了 KASSKEEP_WEBVIEW_INJECTED_JS 的壳里 调用经 WebView 桥接转给原生 SDK
test_store 普通浏览器,已调用 configureTestStore 用公钥调用测试商店
unavailable 普通浏览器 isAvailable() 为 false;请改用网页结账

KasskeepWeb.mode() 返回当前模式。

import KasskeepWeb from "./vendor/kasskeep-web.js";
if (KasskeepWeb.isAvailable()) {
await KasskeepWeb.setAppUserId(userUuid);
const [coins] = await KasskeepWeb.getProducts(["com.example.game.coins_300"], "inapp");
const result = await KasskeepWeb.purchase({ productId: coins.productId, type: "inapp", consumable: true });
if (result.status === "completed") refreshWalletFromServer();
}
函数 说明
isAvailable() 在原生壳里,或已配置测试商店时为 true
getProducts(ids, type, opts?)、getCustomer(opts?)、setAppUserId(id, opts?) 默认超时 20 秒
purchase(request, opts?)、restore(opts?) 默认超时 300 秒,因为商店面板要等用户操作
configure({ timeoutMs?, purchaseTimeoutMs? }) 修改默认值;opts.timeoutMs 可按次覆盖
configureTestStore({ baseUrl, apiKey, appUserId, prices?, outcome?, fetch? } | null) 在浏览器里直接访问测试商店
configureCheckout({ baseUrl, apiKey, appUserId, fetch? } | null) 直接使用网页结账
checkout({ channel, productId, successUrl, cancelUrl, quantity?, redirect? }) 创建 Checkout Session 并跳转
ads.showRewarded({ adUnit, customData? }) 在壳里经桥接调用
configureTestAds({ baseUrl, apiKey, appUserId, outcome?, network? }) 在普通浏览器里使用测试广告

出错时以 KasskeepWebError reject。它的 code 是原生错误码,或 unavailable、timeout、method_not_allowed、unsupported_version、bridge_error 之一。超时不会取消原生购买,所以请以服务端为准确认结果,不要以页面为准。

KasskeepWeb.configureCheckout({ baseUrl: "https://api.kasskeep.com", apiKey: "pk_...", appUserId: user.id });
await KasskeepWeb.checkout({
channel: "stripe",
productId: "pro_monthly",
successUrl: "https://play.example.com/shop/done?session={CHECKOUT_SESSION_ID}",
cancelUrl: "https://play.example.com/shop",
});

checkout 先调用 POST /v1/checkout,再执行 location.assign(url)。传 redirect: false 时改为返回 { url, sessionId }。它从不经过原生桥接。

浏览器直接调用 Kasskeep,所以 App 的 cors_origins 里要有页面的 origin。见 CORS。