@invonetwork/web-sdk 2.4.0 → 2.5.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/CHANGELOG.md +38 -0
- package/README.md +109 -7
- package/dist/{chunk-SSTZKXPC.js → chunk-ZKYUSYK5.js} +30 -3
- package/dist/index.cjs +207 -1
- package/dist/index.d.cts +44 -3
- package/dist/index.d.ts +44 -3
- package/dist/index.js +181 -3
- package/dist/server.cjs +219 -2
- package/dist/server.d.cts +103 -3
- package/dist/server.d.ts +103 -3
- package/dist/server.js +193 -4
- package/dist/{types-7Hl0Z1Ta.d.cts → types-g1xz5GDk.d.cts} +264 -2
- package/dist/{types-7Hl0Z1Ta.d.ts → types-g1xz5GDk.d.ts} +264 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { assertSecureBaseUrl, Http, toDestinationsResult
|
|
2
|
-
export { InvoError } from './chunk-
|
|
1
|
+
import { InvoError, assertSecureBaseUrl, Http, toDestinationsResult } from './chunk-ZKYUSYK5.js';
|
|
2
|
+
export { InvoError } from './chunk-ZKYUSYK5.js';
|
|
3
3
|
|
|
4
4
|
// src/shared/webauthn.ts
|
|
5
5
|
function malformedOptions(field) {
|
|
@@ -120,6 +120,182 @@ function toBalanceRow(row) {
|
|
|
120
120
|
raw: row
|
|
121
121
|
};
|
|
122
122
|
}
|
|
123
|
+
var PROCESSOR_SRC = "https://js.stripe.com/v3";
|
|
124
|
+
var processorScriptLoad;
|
|
125
|
+
function loadProcessorScript() {
|
|
126
|
+
if (typeof document === "undefined" || typeof window === "undefined") {
|
|
127
|
+
return Promise.reject(
|
|
128
|
+
new InvoError({
|
|
129
|
+
message: "confirmCardPayment requires a browser DOM (window/document).",
|
|
130
|
+
code: "DOM_UNAVAILABLE",
|
|
131
|
+
status: 0
|
|
132
|
+
})
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
if (window.Stripe) return Promise.resolve();
|
|
136
|
+
if (processorScriptLoad) return processorScriptLoad;
|
|
137
|
+
processorScriptLoad = new Promise((resolve, reject) => {
|
|
138
|
+
const existing = document.querySelector(
|
|
139
|
+
`script[src="${PROCESSOR_SRC}"]`
|
|
140
|
+
);
|
|
141
|
+
const script = existing ?? document.createElement("script");
|
|
142
|
+
if (!existing) {
|
|
143
|
+
script.src = PROCESSOR_SRC;
|
|
144
|
+
script.async = true;
|
|
145
|
+
document.head.appendChild(script);
|
|
146
|
+
}
|
|
147
|
+
script.addEventListener("load", () => resolve());
|
|
148
|
+
script.addEventListener("error", () => {
|
|
149
|
+
processorScriptLoad = void 0;
|
|
150
|
+
reject(
|
|
151
|
+
new InvoError({
|
|
152
|
+
message: "Failed to load the card processor script.",
|
|
153
|
+
code: "PROCESSOR_LOAD_FAILED",
|
|
154
|
+
status: 0
|
|
155
|
+
})
|
|
156
|
+
);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
return processorScriptLoad;
|
|
160
|
+
}
|
|
161
|
+
async function defaultLoadProcessor(publishableKey) {
|
|
162
|
+
await loadProcessorScript();
|
|
163
|
+
const factory = window.Stripe;
|
|
164
|
+
if (typeof factory !== "function") {
|
|
165
|
+
throw new InvoError({
|
|
166
|
+
message: "The card processor was unavailable after loading.",
|
|
167
|
+
code: "PROCESSOR_UNAVAILABLE",
|
|
168
|
+
status: 0
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
return factory(publishableKey);
|
|
172
|
+
}
|
|
173
|
+
function mapCardConfirm(res) {
|
|
174
|
+
const raw = res;
|
|
175
|
+
if (res.error) {
|
|
176
|
+
return { status: "failed", error: res.error.message ?? "Card payment failed.", raw };
|
|
177
|
+
}
|
|
178
|
+
const pi = res.paymentIntent;
|
|
179
|
+
const s = pi?.status;
|
|
180
|
+
let status;
|
|
181
|
+
if (s === "succeeded") status = "succeeded";
|
|
182
|
+
else if (s === "processing") status = "processing";
|
|
183
|
+
else if (s === "requires_action" || s === "requires_confirmation") status = "requires_action";
|
|
184
|
+
else status = "failed";
|
|
185
|
+
return { status, paymentIntentId: pi?.id, raw };
|
|
186
|
+
}
|
|
187
|
+
function resolveSubmit(opts) {
|
|
188
|
+
if (opts.submit) {
|
|
189
|
+
const el = typeof opts.submit === "string" ? typeof document !== "undefined" ? document.querySelector(opts.submit) : null : opts.submit;
|
|
190
|
+
if (!el) {
|
|
191
|
+
throw new InvoError({
|
|
192
|
+
message: `confirmCardPayment could not find the submit element "${String(opts.submit)}".`,
|
|
193
|
+
code: "SUBMIT_NOT_FOUND",
|
|
194
|
+
status: 0
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
return { el, created: false };
|
|
198
|
+
}
|
|
199
|
+
if (typeof document === "undefined") {
|
|
200
|
+
throw new InvoError({
|
|
201
|
+
message: "confirmCardPayment needs a submit button: pass `submit`, or use `mountCardPayment(...).confirm()` from your own button.",
|
|
202
|
+
code: "SUBMIT_REQUIRED",
|
|
203
|
+
status: 0
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const container = typeof opts.mount === "string" ? document.querySelector(opts.mount) : opts.mount;
|
|
207
|
+
const btn = document.createElement("button");
|
|
208
|
+
btn.type = "button";
|
|
209
|
+
btn.textContent = opts.submitLabel ?? "Pay";
|
|
210
|
+
(container ?? document.body).appendChild(btn);
|
|
211
|
+
return { el: btn, created: true };
|
|
212
|
+
}
|
|
213
|
+
var PlatformCommerceClient = class {
|
|
214
|
+
constructor(defaultPublishableKey) {
|
|
215
|
+
this.defaultPublishableKey = defaultPublishableKey;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Mount the Payment Element and get a session you confirm from your OWN Pay button.
|
|
219
|
+
* This is the fully-controllable primitive (`confirmCardPayment` builds on it).
|
|
220
|
+
*
|
|
221
|
+
* ```ts
|
|
222
|
+
* const session = await invo.platformCommerce.mountCardPayment(clientSecret, {
|
|
223
|
+
* mount: "#pay", publishableKey: "pk_live_…",
|
|
224
|
+
* });
|
|
225
|
+
* // on your Pay button click:
|
|
226
|
+
* const r = await session.confirm({ returnUrl: location.href });
|
|
227
|
+
* if (r.status === "succeeded") showProcessing();
|
|
228
|
+
* session.destroy();
|
|
229
|
+
* ```
|
|
230
|
+
*/
|
|
231
|
+
async mountCardPayment(clientSecret, opts) {
|
|
232
|
+
if (!clientSecret || !clientSecret.trim()) {
|
|
233
|
+
throw new Error("mountCardPayment requires a `clientSecret`.");
|
|
234
|
+
}
|
|
235
|
+
if (opts?.mount == null || typeof opts.mount === "string" && !opts.mount.trim()) {
|
|
236
|
+
throw new Error("mountCardPayment requires a `mount` target (selector or element).");
|
|
237
|
+
}
|
|
238
|
+
const pk = opts.publishableKey ?? this.defaultPublishableKey();
|
|
239
|
+
if (!pk) {
|
|
240
|
+
throw new InvoError({
|
|
241
|
+
message: "A card processor publishableKey is required \u2014 pass it in options, or set `commercePublishableKey` on the InvoClient config.",
|
|
242
|
+
code: "MISSING_PUBLISHABLE_KEY",
|
|
243
|
+
status: 0
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
const load = opts.loadProcessor ?? defaultLoadProcessor;
|
|
247
|
+
const processor = await load(pk);
|
|
248
|
+
const elements = processor.elements({ clientSecret, appearance: opts.appearance });
|
|
249
|
+
const element = elements.create("payment");
|
|
250
|
+
element.mount(opts.mount);
|
|
251
|
+
const confirm = async (confirmOpts) => {
|
|
252
|
+
const returnUrl = confirmOpts?.returnUrl ?? opts.returnUrl;
|
|
253
|
+
const res = await processor.confirmPayment({
|
|
254
|
+
elements,
|
|
255
|
+
confirmParams: returnUrl ? { return_url: returnUrl } : void 0,
|
|
256
|
+
// Stay in-page unless the bank forces a redirect (then return_url completes it).
|
|
257
|
+
redirect: "if_required"
|
|
258
|
+
});
|
|
259
|
+
return mapCardConfirm(res);
|
|
260
|
+
};
|
|
261
|
+
return {
|
|
262
|
+
element,
|
|
263
|
+
confirm,
|
|
264
|
+
destroy() {
|
|
265
|
+
try {
|
|
266
|
+
element.unmount?.();
|
|
267
|
+
} catch {
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* One-call mount + confirm. Mounts the Payment Element into `opts.mount` and resolves
|
|
274
|
+
* when the payment is confirmed via a submit trigger — either `opts.submit` (your Pay
|
|
275
|
+
* button, selector or element) or a minimal button the SDK renders inside `mount`. For
|
|
276
|
+
* full control over the button, prefer {@link mountCardPayment}.
|
|
277
|
+
*/
|
|
278
|
+
async confirmCardPayment(clientSecret, opts) {
|
|
279
|
+
const session = await this.mountCardPayment(clientSecret, opts);
|
|
280
|
+
const trigger = resolveSubmit(opts);
|
|
281
|
+
return new Promise((resolve, reject) => {
|
|
282
|
+
const finish = (settle) => {
|
|
283
|
+
if (trigger.created) trigger.el.remove();
|
|
284
|
+
session.destroy();
|
|
285
|
+
settle();
|
|
286
|
+
};
|
|
287
|
+
const onClick = () => {
|
|
288
|
+
trigger.el.removeEventListener("click", onClick);
|
|
289
|
+
if ("disabled" in trigger.el) trigger.el.disabled = true;
|
|
290
|
+
session.confirm().then(
|
|
291
|
+
(r) => finish(() => resolve(r)),
|
|
292
|
+
(e) => finish(() => reject(e))
|
|
293
|
+
);
|
|
294
|
+
};
|
|
295
|
+
trigger.el.addEventListener("click", onClick);
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
};
|
|
123
299
|
var InvoClient = class {
|
|
124
300
|
constructor(config) {
|
|
125
301
|
if (!config.token) throw new Error("InvoClient requires a player `token`.");
|
|
@@ -136,6 +312,8 @@ var InvoClient = class {
|
|
|
136
312
|
});
|
|
137
313
|
this.auth = { kind: "bearer", token: config.token };
|
|
138
314
|
this.refreshToken = config.refreshToken;
|
|
315
|
+
this.commercePublishableKey = config.commercePublishableKey;
|
|
316
|
+
this.platformCommerce = new PlatformCommerceClient(() => this.commercePublishableKey);
|
|
139
317
|
}
|
|
140
318
|
assertWebAuthn() {
|
|
141
319
|
if (typeof navigator === "undefined" || !navigator.credentials) {
|
|
@@ -476,6 +654,6 @@ var InvoClient = class {
|
|
|
476
654
|
}
|
|
477
655
|
};
|
|
478
656
|
|
|
479
|
-
export { InvoClient };
|
|
657
|
+
export { InvoClient, PlatformCommerceClient };
|
|
480
658
|
//# sourceMappingURL=index.js.map
|
|
481
659
|
//# sourceMappingURL=index.js.map
|
package/dist/server.cjs
CHANGED
|
@@ -134,10 +134,37 @@ var InvoError = class _InvoError extends Error {
|
|
|
134
134
|
get isPhoneShareAlreadyApproved() {
|
|
135
135
|
return this.code === "PHONE_SHARE_ALREADY_APPROVED";
|
|
136
136
|
}
|
|
137
|
-
/** True if an idempotency-keyed request was a duplicate (item purchase → 409). */
|
|
137
|
+
/** True if an idempotency-keyed request was a duplicate (item / platform purchase → 409). */
|
|
138
138
|
get isDuplicateRequest() {
|
|
139
139
|
return this.code === "DUPLICATE_REQUEST" || this.status === 409 && /duplicate/i.test(this.message);
|
|
140
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* True if a Platform Commerce call was rejected because the tenant isn't a platform
|
|
143
|
+
* tenant (`NOT_A_PLATFORM_TENANT`, 403). Platform Commerce (`invo.platformCommerce.*`)
|
|
144
|
+
* is only for non-game platform tenants — a game tenant should use `purchaseItem`
|
|
145
|
+
* (spend game currency) or `createCheckout`/`purchaseCurrency` (buy currency) instead.
|
|
146
|
+
*/
|
|
147
|
+
get isNotPlatformTenant() {
|
|
148
|
+
return this.code === "NOT_A_PLATFORM_TENANT";
|
|
149
|
+
}
|
|
150
|
+
/** True if a Platform Commerce purchase was too small for the fee to round above zero
|
|
151
|
+
* (`AMOUNT_BELOW_MINIMUM`, 400) — raise the amount. */
|
|
152
|
+
get isAmountBelowMinimum() {
|
|
153
|
+
return this.code === "AMOUNT_BELOW_MINIMUM";
|
|
154
|
+
}
|
|
155
|
+
/** True if a Platform Commerce CARD purchase was below the processor's floor of $0.50
|
|
156
|
+
* (backend code `BELOW_STRIPE_MINIMUM`, 400). Neutral name; matches the wire code. */
|
|
157
|
+
get isBelowCardMinimum() {
|
|
158
|
+
return this.code === "BELOW_STRIPE_MINIMUM";
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* True if a Platform Commerce refund targeted an order that was already refunded
|
|
162
|
+
* (409). Idempotent outcome — the original refund did happen, so treat this as
|
|
163
|
+
* success, not a failure to retry-loop.
|
|
164
|
+
*/
|
|
165
|
+
get isAlreadyRefunded() {
|
|
166
|
+
return this.code === "ALREADY_REFUNDED" || this.status === 409 && /already\s+refunded/i.test(this.message);
|
|
167
|
+
}
|
|
141
168
|
/** Seconds to wait before retrying, when the backend throttled the call (429 `retry_after`). */
|
|
142
169
|
get retryAfter() {
|
|
143
170
|
const v = this.bodyObject()["retry_after"];
|
|
@@ -578,7 +605,7 @@ async function hmacHexSubtle(secret, message) {
|
|
|
578
605
|
}
|
|
579
606
|
|
|
580
607
|
// src/server.ts
|
|
581
|
-
var DEFAULT_UA = "invonetwork-web-sdk/2.
|
|
608
|
+
var DEFAULT_UA = "invonetwork-web-sdk/2.5.0 (+https://invo.network)";
|
|
582
609
|
var MAX_USD_AMOUNT = 999.99;
|
|
583
610
|
var MAX_ITEM_PRICE = 999999.99;
|
|
584
611
|
function invalidInput(label, value, why) {
|
|
@@ -739,6 +766,194 @@ function requireField(value, field, raw) {
|
|
|
739
766
|
}
|
|
740
767
|
return s;
|
|
741
768
|
}
|
|
769
|
+
var FUNDING_SOURCES = /* @__PURE__ */ new Set(["balance", "card"]);
|
|
770
|
+
function assertBillingAddress(addr, label) {
|
|
771
|
+
if (!addr || typeof addr !== "object") {
|
|
772
|
+
throw invalidInput(label, addr, 'is required for the "card" funding source');
|
|
773
|
+
}
|
|
774
|
+
const required = [
|
|
775
|
+
[`${label}.line1`, addr.line1],
|
|
776
|
+
[`${label}.city`, addr.city],
|
|
777
|
+
[`${label}.postalCode`, addr.postalCode],
|
|
778
|
+
[`${label}.country`, addr.country]
|
|
779
|
+
];
|
|
780
|
+
for (const [k, v] of required) {
|
|
781
|
+
if (typeof v !== "string" || !v.trim()) throw invalidInput(k, v, "is required");
|
|
782
|
+
}
|
|
783
|
+
if (!/^[A-Za-z]{2}$/.test(addr.country)) {
|
|
784
|
+
throw invalidInput(`${label}.country`, addr.country, "must be a 2-letter ISO country code");
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
function toBillingAddressBody(addr) {
|
|
788
|
+
const body = {
|
|
789
|
+
line1: addr.line1,
|
|
790
|
+
city: addr.city,
|
|
791
|
+
postal_code: addr.postalCode,
|
|
792
|
+
country: addr.country
|
|
793
|
+
};
|
|
794
|
+
if (addr.name) body["name"] = addr.name;
|
|
795
|
+
if (addr.line2) body["line2"] = addr.line2;
|
|
796
|
+
if (addr.state) body["state"] = addr.state;
|
|
797
|
+
return body;
|
|
798
|
+
}
|
|
799
|
+
var PlatformCommerceServer = class {
|
|
800
|
+
constructor(http, auth) {
|
|
801
|
+
this.http = http;
|
|
802
|
+
this.auth = auth;
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Create a purchase. The funding source is resolved server-side under lock — the client
|
|
806
|
+
* can request `"balance"` or `"card"`, but the backend verifies the real balance before
|
|
807
|
+
* value moves.
|
|
808
|
+
*
|
|
809
|
+
* - `fundingSource: "balance"` → settles synchronously; result `status:"success"` with
|
|
810
|
+
* `newBalance`/`financialBreakdown`. `totalPrice` is the tenant's network-currency amount.
|
|
811
|
+
* - `fundingSource: "card"` → result `status:"requires_payment"` + `clientSecret`; hand
|
|
812
|
+
* that to the browser `platformCommerce.confirmCardPayment`. `totalPrice` is USD and a
|
|
813
|
+
* `billingAddress` is REQUIRED. The sale is real only on the `platform_commerce.purchased`
|
|
814
|
+
* webhook — never on the client confirmation.
|
|
815
|
+
*
|
|
816
|
+
* Idempotent on `clientRequestId` (a duplicate throws a 409 `err.isDuplicateRequest`).
|
|
817
|
+
* A non-platform tenant throws `err.isNotPlatformTenant` (403).
|
|
818
|
+
*/
|
|
819
|
+
async purchase(input, opts) {
|
|
820
|
+
const required = [
|
|
821
|
+
["clientRequestId", input.clientRequestId],
|
|
822
|
+
["playerEmail", input.playerEmail],
|
|
823
|
+
["playerName", input.playerName],
|
|
824
|
+
["itemId", input.itemId],
|
|
825
|
+
["itemName", input.itemName]
|
|
826
|
+
];
|
|
827
|
+
for (const [k, v] of required) {
|
|
828
|
+
if (typeof v !== "string" || !v.trim()) throw invalidInput(k, v, "is required");
|
|
829
|
+
}
|
|
830
|
+
if (!FUNDING_SOURCES.has(input.fundingSource)) {
|
|
831
|
+
throw invalidInput("fundingSource", input.fundingSource, 'must be "balance" or "card"');
|
|
832
|
+
}
|
|
833
|
+
if (!Number.isInteger(input.itemQuantity) || input.itemQuantity < 1 || input.itemQuantity > 1e3) {
|
|
834
|
+
throw invalidInput("itemQuantity", input.itemQuantity, "must be an integer 1..1000");
|
|
835
|
+
}
|
|
836
|
+
const unit = parseMoney(input.unitPrice, MAX_ITEM_PRICE, "unitPrice");
|
|
837
|
+
const total = parseMoney(input.totalPrice, MAX_ITEM_PRICE, "totalPrice");
|
|
838
|
+
const expectedCents = Math.round(unit * input.itemQuantity * 100);
|
|
839
|
+
const totalCents = Math.round(total * 100);
|
|
840
|
+
if (Math.abs(totalCents - expectedCents) > 1) {
|
|
841
|
+
throw invalidInput(
|
|
842
|
+
"totalPrice",
|
|
843
|
+
input.totalPrice,
|
|
844
|
+
`must equal unitPrice \xD7 itemQuantity (\xB10.01): ${unit} \xD7 ${input.itemQuantity}`
|
|
845
|
+
);
|
|
846
|
+
}
|
|
847
|
+
if (input.fundingSource === "card") {
|
|
848
|
+
assertBillingAddress(input.billingAddress, "billingAddress");
|
|
849
|
+
}
|
|
850
|
+
const body = {
|
|
851
|
+
client_request_id: input.clientRequestId,
|
|
852
|
+
funding_source: input.fundingSource,
|
|
853
|
+
player_email: input.playerEmail,
|
|
854
|
+
player_name: input.playerName,
|
|
855
|
+
item_id: input.itemId,
|
|
856
|
+
item_name: input.itemName,
|
|
857
|
+
item_quantity: input.itemQuantity,
|
|
858
|
+
unit_price: input.unitPrice,
|
|
859
|
+
total_price: input.totalPrice
|
|
860
|
+
};
|
|
861
|
+
if (input.playerPhone) body["player_phone"] = input.playerPhone;
|
|
862
|
+
if (input.itemDescription) body["item_description"] = input.itemDescription;
|
|
863
|
+
if (input.itemCategory) body["item_category"] = input.itemCategory;
|
|
864
|
+
if (input.billingAddress) body["billing_address"] = toBillingAddressBody(input.billingAddress);
|
|
865
|
+
const raw = await this.http.post(
|
|
866
|
+
"/api/platform-commerce/purchase",
|
|
867
|
+
body,
|
|
868
|
+
this.auth,
|
|
869
|
+
{ idempotent: true, signal: opts?.signal }
|
|
870
|
+
// client_request_id makes this safe to retry (dup → 409)
|
|
871
|
+
);
|
|
872
|
+
const orderIdRaw = raw["order_id"];
|
|
873
|
+
requireField(orderIdRaw, "order_id", raw);
|
|
874
|
+
const status = String(raw["status"] ?? "");
|
|
875
|
+
if (status === "requires_payment" && !raw["client_secret"]) {
|
|
876
|
+
requireField(raw["client_secret"], "client_secret", raw);
|
|
877
|
+
}
|
|
878
|
+
return {
|
|
879
|
+
status,
|
|
880
|
+
fundingSource: String(raw["funding_source"] ?? input.fundingSource),
|
|
881
|
+
orderId: orderIdRaw,
|
|
882
|
+
transactionId: raw["transaction_id"],
|
|
883
|
+
newBalance: raw["new_balance"] ?? null,
|
|
884
|
+
previousBalance: raw["previous_balance"] ?? null,
|
|
885
|
+
currencyName: raw["currency_name"],
|
|
886
|
+
financialBreakdown: raw["financial_breakdown"],
|
|
887
|
+
clientSecret: raw["client_secret"],
|
|
888
|
+
amountUsd: raw["amount_usd"] ?? null,
|
|
889
|
+
raw
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
/** Poll an order's status: `completed` (balance immediately; card after the webhook),
|
|
893
|
+
* `pending_payment` (card awaiting confirmation), or `refunded`. */
|
|
894
|
+
async getStatus(orderId, opts) {
|
|
895
|
+
if (orderId == null || String(orderId).trim() === "") {
|
|
896
|
+
throw invalidInput("orderId", orderId, "is required");
|
|
897
|
+
}
|
|
898
|
+
const raw = await this.http.get(
|
|
899
|
+
`/api/platform-commerce/purchase-status/${encodeURIComponent(String(orderId))}`,
|
|
900
|
+
this.auth,
|
|
901
|
+
{ signal: opts?.signal }
|
|
902
|
+
);
|
|
903
|
+
return {
|
|
904
|
+
orderId: raw["order_id"] ?? orderId,
|
|
905
|
+
status: String(raw["status"] ?? ""),
|
|
906
|
+
gameCurrencyAmount: raw["game_currency_amount"] ?? null,
|
|
907
|
+
usdAmount: raw["usd_amount"] ?? null,
|
|
908
|
+
paymentMethod: raw["payment_method"],
|
|
909
|
+
createdAt: raw["created_at"],
|
|
910
|
+
raw
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* Refund a completed purchase. Provide EXACTLY ONE of `orderId` or `clientRequestId`.
|
|
915
|
+
* INVO retains its fee — the customer is made whole (balance re-credit or card refund)
|
|
916
|
+
* minus that fee. Idempotent on the order: a second refund throws a 409
|
|
917
|
+
* (`err.isAlreadyRefunded`) — treat that as "already done", not a failure.
|
|
918
|
+
*/
|
|
919
|
+
async refund(input, opts) {
|
|
920
|
+
const hasOrder = input.orderId != null && String(input.orderId).trim() !== "";
|
|
921
|
+
const hasReq = typeof input.clientRequestId === "string" && input.clientRequestId.trim() !== "";
|
|
922
|
+
if (hasOrder === hasReq) {
|
|
923
|
+
throw new InvoError({
|
|
924
|
+
message: "refund requires EXACTLY ONE of orderId or clientRequestId.",
|
|
925
|
+
code: "INVALID_INPUT",
|
|
926
|
+
status: 0
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
const body = {};
|
|
930
|
+
if (hasOrder) body["order_id"] = input.orderId;
|
|
931
|
+
else body["client_request_id"] = input.clientRequestId;
|
|
932
|
+
if (input.reason) body["reason"] = input.reason;
|
|
933
|
+
const raw = await this.http.post(
|
|
934
|
+
"/api/platform-commerce/refund",
|
|
935
|
+
body,
|
|
936
|
+
this.auth,
|
|
937
|
+
// Idempotent on the order: a lost-response retry re-refunds nothing (backend 409s
|
|
938
|
+
// "already refunded"), so a transient 5xx/network retry is safe.
|
|
939
|
+
{ idempotent: true, signal: opts?.signal }
|
|
940
|
+
);
|
|
941
|
+
const fundingSource = raw["funding_source"];
|
|
942
|
+
return {
|
|
943
|
+
status: String(raw["status"] ?? ""),
|
|
944
|
+
orderId: raw["order_id"] ?? void 0,
|
|
945
|
+
fundingSource,
|
|
946
|
+
transactionId: raw["transaction_id"],
|
|
947
|
+
// Backend key differs per leg: `refunded_amount` (balance) / `refunded_amount_usd` (card).
|
|
948
|
+
refundedAmount: raw["refunded_amount"] ?? raw["refunded_amount_usd"] ?? null,
|
|
949
|
+
// The refund HTTP response carries no unit; derive it (card → USD). The balance leg's
|
|
950
|
+
// unit is the tenant's network currency, not present here — left undefined.
|
|
951
|
+
amountUnit: raw["amount_unit"] ?? (fundingSource === "card" ? "usd" : void 0),
|
|
952
|
+
feeRetained: raw["fee_retained"] === true,
|
|
953
|
+
raw
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
};
|
|
742
957
|
var InvoServer = class {
|
|
743
958
|
constructor(config) {
|
|
744
959
|
if (!config.gameSecret) throw new Error("InvoServer requires a `gameSecret`.");
|
|
@@ -755,6 +970,7 @@ var InvoServer = class {
|
|
|
755
970
|
hooks: config.hooks
|
|
756
971
|
});
|
|
757
972
|
this.auth = { kind: "game-secret", secret: config.gameSecret };
|
|
973
|
+
this.platformCommerce = new PlatformCommerceServer(this.http, this.auth);
|
|
758
974
|
}
|
|
759
975
|
/**
|
|
760
976
|
* Mint a short-lived, game-scoped player token to hand to the browser InvoClient.
|
|
@@ -1436,6 +1652,7 @@ var InvoServer = class {
|
|
|
1436
1652
|
|
|
1437
1653
|
exports.InvoError = InvoError;
|
|
1438
1654
|
exports.InvoServer = InvoServer;
|
|
1655
|
+
exports.PlatformCommerceServer = PlatformCommerceServer;
|
|
1439
1656
|
exports.createWebhookHandler = createWebhookHandler;
|
|
1440
1657
|
exports.verifyWebhook = verifyWebhook;
|
|
1441
1658
|
exports.verifyWebhookAsync = verifyWebhookAsync;
|
package/dist/server.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { o as InvoError, H as Http, v as AuthHeader, w as PlatformPurchaseInput, d as CallOptions, x as PlatformPurchaseResult, y as PlatformOrderStatusResult, z as PlatformRefundInput, F as PlatformRefundResult, S as ServerConfig, G as PlayerToken, J as InitiateSendInput, K as InitiateResult, N as InitiateTransferInput, O as CreateCheckoutInput, Q as CreateCheckoutResult, T as PurchaseInput, U as PurchaseResult, W as ConfirmPaymentResult, X as OrderDetailsResult, Y as PurchaseItemInput, Z as PurchaseItemResult, _ as ItemHistoryQuery, $ as ItemHistoryResult, a0 as ItemOrderQuery, a1 as PlayerBalanceQuery, a2 as PlayerBalanceResult, a3 as InboundPendingQuery, a4 as InboundPendingResult, a5 as LinkedIdentitiesQuery, a6 as LinkedIdentitiesResult, a7 as SmsVerifyResult, a8 as ClaimTransferInput, a9 as ClaimResult, aa as ClaimCurrencyInput, ab as TransactionStatusResult, ac as GuardianApprovalStatusResult, ad as ServerDestinationsQuery, f as DestinationsResult, ae as PhoneShareContact, af as PhoneShareInitiateResult, ag as PhoneShareApproveInput, ah as PhoneShareApproveResult, ai as PhoneShareStatusResult } from './types-g1xz5GDk.cjs';
|
|
2
|
+
export { aj as BillingAddress, ak as CurrencyBalance, k as DestinationGame, al as FundingSource, am as InboundPendingItem, p as InvoErrorInfo, q as InvoHooks, r as InvoRequestInfo, s as InvoResponseInfo, an as LinkedIdentityEmail, ao as PlatformPurchaseStatus, u as Rail, V as VerificationMethod } from './types-g1xz5GDk.cjs';
|
|
3
3
|
|
|
4
4
|
interface VerifyWebhookOptions {
|
|
5
5
|
/** Max age of the signed timestamp, in seconds. Default 300 (5 min). */
|
|
@@ -53,6 +53,44 @@ interface ItemPurchasedData {
|
|
|
53
53
|
fee_breakdown?: Record<string, unknown>;
|
|
54
54
|
[key: string]: unknown;
|
|
55
55
|
}
|
|
56
|
+
/** `platform_commerce.purchased` — a Platform Commerce (ecommerce) purchase completed
|
|
57
|
+
* (balance immediately; card after the payment settles). Fulfill card orders on THIS,
|
|
58
|
+
* never on the browser confirmation. */
|
|
59
|
+
interface PlatformCommercePurchasedData {
|
|
60
|
+
transaction_id: string;
|
|
61
|
+
order_id: string | number;
|
|
62
|
+
/** "balance" | "card". */
|
|
63
|
+
funding_source: string;
|
|
64
|
+
player_email: string;
|
|
65
|
+
identity_id: string;
|
|
66
|
+
item_id: string;
|
|
67
|
+
item_name: string;
|
|
68
|
+
item_quantity: number;
|
|
69
|
+
/** Balance leg only — the network-currency amount. The CARD leg carries `total_price_usd`
|
|
70
|
+
* instead (this field is absent there). */
|
|
71
|
+
total_price?: string;
|
|
72
|
+
/** Balance leg only. */
|
|
73
|
+
unit_price?: string;
|
|
74
|
+
currency_name?: string;
|
|
75
|
+
new_balance?: string;
|
|
76
|
+
/** Card leg only (the USD charged). */
|
|
77
|
+
total_price_usd?: string;
|
|
78
|
+
fee_breakdown?: Record<string, unknown>;
|
|
79
|
+
[key: string]: unknown;
|
|
80
|
+
}
|
|
81
|
+
/** `platform_commerce.refunded` — a Platform Commerce purchase was refunded. INVO keeps
|
|
82
|
+
* its fee (`fee_retained: true`); the customer is made whole minus that fee. */
|
|
83
|
+
interface PlatformCommerceRefundedData {
|
|
84
|
+
order_id: string | number;
|
|
85
|
+
/** "balance" | "card". */
|
|
86
|
+
funding_source: string;
|
|
87
|
+
player_email: string;
|
|
88
|
+
refunded_amount: string;
|
|
89
|
+
/** `"usd"` (card) or the literal `"currency"` (balance). */
|
|
90
|
+
amount_unit: string;
|
|
91
|
+
fee_retained: boolean;
|
|
92
|
+
[key: string]: unknown;
|
|
93
|
+
}
|
|
56
94
|
interface TransferEventData {
|
|
57
95
|
transaction_id: string;
|
|
58
96
|
/** "transfer" | "send". */
|
|
@@ -79,6 +117,12 @@ type InvoWebhookEvent = (WebhookBase & {
|
|
|
79
117
|
}) | (WebhookBase & {
|
|
80
118
|
event_type: "item.purchased";
|
|
81
119
|
data: ItemPurchasedData;
|
|
120
|
+
}) | (WebhookBase & {
|
|
121
|
+
event_type: "platform_commerce.purchased";
|
|
122
|
+
data: PlatformCommercePurchasedData;
|
|
123
|
+
}) | (WebhookBase & {
|
|
124
|
+
event_type: "platform_commerce.refunded";
|
|
125
|
+
data: PlatformCommerceRefundedData;
|
|
82
126
|
}) | (WebhookBase & {
|
|
83
127
|
event_type: PurchaseEventType;
|
|
84
128
|
data: PurchaseEventData;
|
|
@@ -145,9 +189,65 @@ interface WebhookHandlerOptions {
|
|
|
145
189
|
*/
|
|
146
190
|
declare function createWebhookHandler(opts: WebhookHandlerOptions): (request: Request) => Promise<Response>;
|
|
147
191
|
|
|
192
|
+
/**
|
|
193
|
+
* @invonetwork/web-sdk/server — NODE entry.
|
|
194
|
+
*
|
|
195
|
+
* InvoServer holds the game secret and runs every server-side call: minting the
|
|
196
|
+
* short-lived player token for the browser, initiating sends/transfers, and the
|
|
197
|
+
* currency-purchase flow (hosted checkout + rail selector). The game secret must
|
|
198
|
+
* NEVER reach the browser.
|
|
199
|
+
*
|
|
200
|
+
* All endpoints here authenticate with the `X-Game-Secret-Key` header.
|
|
201
|
+
*/
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Platform Commerce — the ECOMMERCE surface (server side). A PLATFORM tenant (a non-game
|
|
205
|
+
* app: vertical video, creator merch, marketplace) sells items funded by INVO balance OR a
|
|
206
|
+
* real card, with INVO as merchant of record and full refunds. This is NOT item purchase
|
|
207
|
+
* (§4.8) — that is a GAME tenant spending a player's existing game currency on an in-game
|
|
208
|
+
* item (balance only, no card, no refund). Different endpoints, different fee, different
|
|
209
|
+
* settlement. Reached as `invo.platformCommerce.*`.
|
|
210
|
+
*/
|
|
211
|
+
declare class PlatformCommerceServer {
|
|
212
|
+
private readonly http;
|
|
213
|
+
private readonly auth;
|
|
214
|
+
constructor(http: Http, auth: AuthHeader);
|
|
215
|
+
/**
|
|
216
|
+
* Create a purchase. The funding source is resolved server-side under lock — the client
|
|
217
|
+
* can request `"balance"` or `"card"`, but the backend verifies the real balance before
|
|
218
|
+
* value moves.
|
|
219
|
+
*
|
|
220
|
+
* - `fundingSource: "balance"` → settles synchronously; result `status:"success"` with
|
|
221
|
+
* `newBalance`/`financialBreakdown`. `totalPrice` is the tenant's network-currency amount.
|
|
222
|
+
* - `fundingSource: "card"` → result `status:"requires_payment"` + `clientSecret`; hand
|
|
223
|
+
* that to the browser `platformCommerce.confirmCardPayment`. `totalPrice` is USD and a
|
|
224
|
+
* `billingAddress` is REQUIRED. The sale is real only on the `platform_commerce.purchased`
|
|
225
|
+
* webhook — never on the client confirmation.
|
|
226
|
+
*
|
|
227
|
+
* Idempotent on `clientRequestId` (a duplicate throws a 409 `err.isDuplicateRequest`).
|
|
228
|
+
* A non-platform tenant throws `err.isNotPlatformTenant` (403).
|
|
229
|
+
*/
|
|
230
|
+
purchase(input: PlatformPurchaseInput, opts?: CallOptions): Promise<PlatformPurchaseResult>;
|
|
231
|
+
/** Poll an order's status: `completed` (balance immediately; card after the webhook),
|
|
232
|
+
* `pending_payment` (card awaiting confirmation), or `refunded`. */
|
|
233
|
+
getStatus(orderId: string | number, opts?: CallOptions): Promise<PlatformOrderStatusResult>;
|
|
234
|
+
/**
|
|
235
|
+
* Refund a completed purchase. Provide EXACTLY ONE of `orderId` or `clientRequestId`.
|
|
236
|
+
* INVO retains its fee — the customer is made whole (balance re-credit or card refund)
|
|
237
|
+
* minus that fee. Idempotent on the order: a second refund throws a 409
|
|
238
|
+
* (`err.isAlreadyRefunded`) — treat that as "already done", not a failure.
|
|
239
|
+
*/
|
|
240
|
+
refund(input: PlatformRefundInput, opts?: CallOptions): Promise<PlatformRefundResult>;
|
|
241
|
+
}
|
|
148
242
|
declare class InvoServer {
|
|
149
243
|
private readonly http;
|
|
150
244
|
private readonly auth;
|
|
245
|
+
/**
|
|
246
|
+
* Platform Commerce (ecommerce) — a PLATFORM tenant selling items funded by balance or
|
|
247
|
+
* card, with refunds. DISTINCT from `purchaseItem` (a game tenant spending existing game
|
|
248
|
+
* currency on an in-game item). See {@link PlatformCommerceServer}.
|
|
249
|
+
*/
|
|
250
|
+
readonly platformCommerce: PlatformCommerceServer;
|
|
151
251
|
constructor(config: ServerConfig);
|
|
152
252
|
/**
|
|
153
253
|
* Mint a short-lived, game-scoped player token to hand to the browser InvoClient.
|
|
@@ -323,4 +423,4 @@ declare class InvoServer {
|
|
|
323
423
|
private toInitiateResult;
|
|
324
424
|
}
|
|
325
425
|
|
|
326
|
-
export { CallOptions, ClaimCurrencyInput, ClaimResult, ClaimTransferInput, ConfirmPaymentResult, CreateCheckoutInput, CreateCheckoutResult, DestinationsResult, GuardianApprovalStatusResult, InboundPendingQuery, InboundPendingResult, InitiateResult, InitiateSendInput, InitiateTransferInput, InvoError, InvoServer, type InvoWebhookEvent, ItemHistoryQuery, ItemHistoryResult, ItemOrderQuery, type ItemPurchasedData, LinkedIdentitiesQuery, LinkedIdentitiesResult, OrderDetailsResult, PhoneShareApproveInput, PhoneShareApproveResult, PhoneShareContact, PhoneShareInitiateResult, PhoneShareStatusResult, PlayerBalanceQuery, PlayerBalanceResult, PlayerToken, type PurchaseCompletedData, type PurchaseEventData, PurchaseInput, PurchaseItemInput, PurchaseItemResult, PurchaseResult, ServerConfig, ServerDestinationsQuery, SmsVerifyResult, TransactionStatusResult, type TransferEventData, type VerifyWebhookOptions, type WebhookHandlerOptions, createWebhookHandler, verifyWebhook, verifyWebhookAsync };
|
|
426
|
+
export { CallOptions, ClaimCurrencyInput, ClaimResult, ClaimTransferInput, ConfirmPaymentResult, CreateCheckoutInput, CreateCheckoutResult, DestinationsResult, GuardianApprovalStatusResult, InboundPendingQuery, InboundPendingResult, InitiateResult, InitiateSendInput, InitiateTransferInput, InvoError, InvoServer, type InvoWebhookEvent, ItemHistoryQuery, ItemHistoryResult, ItemOrderQuery, type ItemPurchasedData, LinkedIdentitiesQuery, LinkedIdentitiesResult, OrderDetailsResult, PhoneShareApproveInput, PhoneShareApproveResult, PhoneShareContact, PhoneShareInitiateResult, PhoneShareStatusResult, type PlatformCommercePurchasedData, type PlatformCommerceRefundedData, PlatformCommerceServer, PlatformOrderStatusResult, PlatformPurchaseInput, PlatformPurchaseResult, PlatformRefundInput, PlatformRefundResult, PlayerBalanceQuery, PlayerBalanceResult, PlayerToken, type PurchaseCompletedData, type PurchaseEventData, PurchaseInput, PurchaseItemInput, PurchaseItemResult, PurchaseResult, ServerConfig, ServerDestinationsQuery, SmsVerifyResult, TransactionStatusResult, type TransferEventData, type VerifyWebhookOptions, type WebhookHandlerOptions, createWebhookHandler, verifyWebhook, verifyWebhookAsync };
|