forked from tebexio/Tebex.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.ts
More file actions
538 lines (459 loc) · 16.1 KB
/
checkout.ts
File metadata and controls
538 lines (459 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import zoid, {
type ZoidComponent,
type ZoidComponentInstance
} from "zoid";
import {
createNanoEvents,
type Unsubscribe
} from "nanoevents";
import { Lightbox } from "./lightbox";
import { spinnerRender } from "./spinner";
import {
type CssDimension,
type Implements,
assert,
warn,
isInDocument,
isApplePayAvailable,
isMobile,
isNullOrUndefined,
isString,
isArray,
isNonEmptyString,
isObject,
isBoolean,
} from "./utils";
const DEFAULT_WIDTH = "800px";
const DEFAULT_HEIGHT = "760px";
export const THEME_NAMES = [
"auto",
"default",
"light",
"dark"
] as const;
export const COLOR_NAMES = [
"primary",
"secondary",
"background",
"surface",
"surface-variant",
"success",
"warning",
"error",
"green",
"red",
"fields",
"field-border",
] as const;
export const EVENT_NAMES = [
"open",
"close",
"payment:complete",
"payment:error"
] as const;
/**
* Configuration options for `Tebex.checkout.init()`.
*/
export type CheckoutOptions = {
/**
* The checkout request ident received from either the Headless or Checkout APIs.
*/
ident: string;
/**
* The default language to use, defined as an ISO locale code - e.g. `"en_US" for American English, "de_DE" for German, etc.
* @default `navigator.language`
*/
locale?: string;
/**
* Tebex checkout panel color theme.
* @default "light"
*/
theme?: CheckoutTheme;
/**
* Tebex checkout panel UI brand colors.
* @default []
*/
colors?: CheckoutColorDefinition[];
/**
* Whether to close the Tebex.js popup when the user clicks outside of the modal.
* @default false
*/
closeOnClickOutside?: boolean;
/**
* Whether to close the Tebex.js popup when the user presses the Escape key.
* @default false
*/
closeOnEsc?: boolean;
/**
* Whether to automatically close the Tebex.js popup as soon as the payment is completed; `payment:complete` and `close` events will still be emitted.
* @default false
*/
closeOnPaymentComplete?: boolean;
/**
* Select a payment method to highlight on the checkout by passing its ident.
* @default undefined
*/
defaultPaymentMethod?: string;
/**
* Whether to still display a popup on mobile or not. If `false` or undefined, then calling `launch()` will open a new window on mobile devices.
* @default false
*/
popupOnMobile?: boolean;
/**
* API endpoint to use. Do not change this unless otherwise guided to do so.
* @default ""
* @internal
*/
endpoint?: string;
};
/**
* Color theme for the embedded Tebex checkout panel.
*/
export type CheckoutTheme = typeof THEME_NAMES[number];
/**
* Color definition. The `color` property can be set to any valid CSS color, so long as it does not rely on CSS Variables.
*/
export type CheckoutColorDefinition = {
name: typeof COLOR_NAMES[number];
color: string;
}; // TODO: might make this legacy (but still supported), and just define colors as an object of { name: color }
/**
* Checkout event type. You can subscribe to checkout events with `Tebex.checkout.on()`.
*/
export type CheckoutEvent = typeof EVENT_NAMES[number];
/**
* Maps a {@link CheckoutEvent} to its event callback type.
*/
export type CheckoutEventMap = Implements<Record<CheckoutEvent, Function>, {
"open": () => void;
"close": () => void;
"payment:complete": (e: Event) => void;
"payment:error": (e: Event) => void;
}>;
/**
* Props passed through Zoid component.
* @internal
*/
export type CheckoutZoidProps = {
locale: string;
colors: CheckoutColorDefinition[];
closeOnClickOutside: boolean;
closeOnEsc: boolean;
closeOnPaymentComplete: boolean;
defaultPaymentMethod?: string;
theme: CheckoutTheme;
onOpenWindow: (url: string) => void;
onClosePopup: () => Promise<void>;
onPaymentComplete: (e: any) => void;
onPaymentError: (e: any) => void;
isApplePayAvailable: boolean;
isEmbedded: boolean;
referrer: string;
origin: string;
path: string;
params: string;
version: string;
};
/**
* Tebex checkout instance.
*/
export default class Checkout {
ident: string = null;
locale: string = null;
theme: CheckoutTheme = "default";
colors: CheckoutColorDefinition[] = [];
closeOnClickOutside = false;
closeOnEsc = false;
closeOnPaymentComplete = false;
defaultPaymentMethod?: string = undefined;
popupOnMobile = false;
endpoint = "https://pay.tebex.io";
isOpen = false;
emitter = createNanoEvents<CheckoutEventMap>();
lightbox: Lightbox = null;
component: ZoidComponent<CheckoutZoidProps> = null;
zoid: ZoidComponentInstance = null;
#didRender = false;
#onRender: Function;
/**
* Configure the Tebex checkout settings.
*/
init(options: CheckoutOptions) {
assert(options.ident && isString(options.ident), "ident option is required, and must be a string");
this.ident = options.ident;
this.locale = this.#resolveLocale(options) ?? this.locale;
this.theme = this.#resolveTheme(options) ?? this.theme;
this.colors = this.#resolveColors(options) ?? this.colors;
this.popupOnMobile = this.#resolvePopupOnMobile(options) ?? this.popupOnMobile;
this.endpoint = this.#resolveEndpoint(options) ?? this.endpoint;
this.closeOnClickOutside = this.#resolveCloseOnClickOutside(options) ?? this.closeOnClickOutside;
this.closeOnEsc = this.#resolveCloseOnEsc(options) ?? this.closeOnEsc;
this.closeOnPaymentComplete = this.#resolveCloseOnPaymentComplete(options) ?? this.closeOnPaymentComplete;
this.defaultPaymentMethod = this.#resolveDefaultPaymentMethod(options) ?? this.defaultPaymentMethod;
}
/**
* Subscribe to Tebex checkout events, such as when the embed is closed or when a payment is completed.
* NOTE: None of these events should not be used to confirm actual receipt of payment - you should use Webhooks for that.
*/
on<T extends CheckoutEvent>(event: T, callback: CheckoutEventMap[T]): Unsubscribe {
// @ts-ignore - handles legacy event name
if (event === "payment_complete")
event = "payment:complete" as T;
// @ts-ignore - handles legacy event name
if (event === "payment_error")
event = "payment:error" as T;
if (!EVENT_NAMES.includes(event)) {
warn(`invalid event name "${ event }"`);
return () => {};
}
return this.emitter.on(event, callback);
}
/**
* Launch the Tebex checkout panel.
* On desktop, the panel will launch in a "lightbox" mode that covers the screen. On mobile, it will be opened as a new page.
*/
async launch() {
if (!this.popupOnMobile && isMobile(DEFAULT_WIDTH, DEFAULT_HEIGHT)) {
await this.#renderComponent(document.body, true);
this.isOpen = true;
this.emitter.emit("open");
return;
}
await this.#showLightbox();
}
/**
* Close the Tebex checkout panel.
*/
async close() {
if (this.lightbox)
await this.lightbox.hide();
if (this.zoid) {
await this.zoid.close();
this.isOpen = false;
this.emitter.emit("close");
}
}
/**
* Close and destroy the element immediately, without waiting for CSS transitions.
*/
destroy() {
if (this.lightbox)
this.lightbox.destroy();
if (this.zoid) {
this.zoid.close();
this.isOpen = false;
this.emitter.emit("close");
}
}
/**
* Render the Tebex checkout panel immediately, into a specified HTML element.
* If `popupOnMobile` is true, then on mobile devices the checkout will be immediately opened as a new page instead.
*/
async render(element: HTMLElement, width: CssDimension, height: CssDimension, popupOnMobile = this.popupOnMobile) {
// Zoid requires that elements are already in the page, otherwise it throws a confusing error.
assert(isInDocument(element), "Target element must already be inserted into the page before it can be used");
width = isString(width) ? width : `${ width }px`;
height = isString(height) ? height : `${ height }px`;
this.#buildComponent(width, height);
await this.#renderComponent(element, popupOnMobile && isMobile(width, height));
this.isOpen = true;
this.emitter.emit("open");
}
/**
* Await internal Zoid render tests - primarily exposed for tests.
* @internal
*/
async renderFinished() {
return new Promise<void>(resolve => {
this.#onRender = resolve;
if (this.#didRender)
resolve();
});
}
#resolveLocale(options: CheckoutOptions) {
if (isNullOrUndefined(options.locale))
return null;
if (!isNonEmptyString(options.locale)) {
warn(`invalid locale option "${ options.locale }" - must be a non-empty string`);
return null;
}
return options.locale;
}
#resolveTheme(options: CheckoutOptions) {
if (isNullOrUndefined(options.theme))
return null;
if(!THEME_NAMES.includes(options.theme)) {
const list = THEME_NAMES.map(n => `"${ n }"`).join(", ");
warn(`invalid theme option "${ options.theme }" - must be one of ${ list }`);
return null;
}
return options.theme;
}
#resolveColors(options: CheckoutOptions) {
if (isNullOrUndefined(options.colors))
return null;
if (!isArray(options.colors)) {
warn(`invalid colors option "${ options.colors }" - must be an array`);
return null;
}
for (let entry of options.colors) {
if (!isObject(entry)) {
warn(`invalid colors option item ${ entry } - must be an object`);
return null;
}
if (!entry.hasOwnProperty("name")) {
warn(`invalid colors option item - missing 'name' field`);
return null;
}
if (!entry.hasOwnProperty("color")) {
warn(`invalid colors option item - missing 'color' field`);
return null;
}
if (!COLOR_NAMES.includes(entry.name)) {
const list = COLOR_NAMES.map(n => `"${ n }"`).join(", ");
warn(`invalid color name "${ entry.name }" - must be one of ${ list }`);
return null;
}
if (!isNonEmptyString(entry.color)) {
warn(`invalid color value "${ entry.color }" - must be a non-empty string`);
return null;
}
if (entry.color.includes("var(")) {
warn(`invalid color value "${ entry.color }" - cannot include CSS variables`);
return null;
}
}
return options.colors;
}
#resolvePopupOnMobile(options: CheckoutOptions) {
if (isNullOrUndefined(options.popupOnMobile))
return null;
if (!isBoolean(options.popupOnMobile)) {
warn(`invalid popupOnMobile option "${ options.popupOnMobile }" - must be a boolean`);
return null;
}
return options.popupOnMobile;
}
#resolveEndpoint(options: CheckoutOptions) {
if (isNullOrUndefined(options.endpoint))
return null;
if (!isNonEmptyString(options.endpoint)) {
warn(`invalid endpoint option "${ options.endpoint }" - must be a non-empty string`);
return null;
}
return options.endpoint;
}
#resolveCloseOnClickOutside(options: CheckoutOptions) {
if (isNullOrUndefined(options.closeOnClickOutside))
return null;
if (!isBoolean(options.closeOnClickOutside)) {
warn(`invalid closeOnClickOutside option "${ options.closeOnClickOutside }" - must be a boolean`);
return null;
}
return options.closeOnClickOutside;
}
#resolveCloseOnEsc(options: CheckoutOptions) {
if (isNullOrUndefined(options.closeOnEsc))
return null;
if (!isBoolean(options.closeOnEsc)) {
warn(`invalid closeOnEsc option "${ options.closeOnEsc }" - must be a boolean`);
return null
}
return options.closeOnEsc;
}
#resolveCloseOnPaymentComplete(options: CheckoutOptions) {
if (isNullOrUndefined(options.closeOnPaymentComplete))
return null;
if (!isBoolean(options.closeOnPaymentComplete)) {
warn(`invalid closeOnPaymentComplete option "${ options.closeOnPaymentComplete }" - must be a boolean`);
return null;
}
return options.closeOnPaymentComplete;
}
#resolveDefaultPaymentMethod(options: CheckoutOptions) {
if (isNullOrUndefined(options.defaultPaymentMethod))
return null;
if (!isNonEmptyString(options.defaultPaymentMethod)) {
warn(`invalid default payment method option "${ options.defaultPaymentMethod }" - must be a non-empty string`);
return null;
}
return options.defaultPaymentMethod;
}
#onRequestLightboxClose = async () => {
if (this.isOpen)
await this.close();
};
async #showLightbox() {
if (!this.lightbox)
this.lightbox = new Lightbox();
if (this.closeOnClickOutside)
this.lightbox.clickOutsideHandler = this.#onRequestLightboxClose;
if (this.closeOnEsc)
this.lightbox.escKeyHandler = this.#onRequestLightboxClose;
await this.lightbox.show();
await this.#renderComponent(this.lightbox.holder, false);
this.isOpen = true;
this.emitter.emit("open");
}
#buildComponent(width: CssDimension = DEFAULT_WIDTH, height: CssDimension = DEFAULT_HEIGHT) {
this.component = zoid.create({
tag: "tebex-js-checkout-component",
url: () => this.endpoint + "/" + this.ident,
autoResize: {
width: false,
height: false,
},
dimensions: {
width,
height,
},
prerenderTemplate: spinnerRender,
attributes: {
iframe: {
allow: "payment https://pay.tebex.io",
},
},
});
}
async #renderComponent(container: HTMLElement, popup: boolean) {
const url = new URL(window.location.href);
if (!this.component)
this.#buildComponent();
this.zoid = this.component({
locale: this.locale,
colors: this.colors,
closeOnClickOutside: this.closeOnClickOutside,
closeOnEsc: this.closeOnEsc,
closeOnPaymentComplete: this.closeOnPaymentComplete,
defaultPaymentMethod: this.defaultPaymentMethod,
theme: this.theme,
onOpenWindow: (url) => {
window.open(url);
},
onClosePopup: async () => {
await this.zoid.close();
if (this.lightbox)
await this.lightbox.hide();
this.isOpen = false;
this.emitter.emit("close");
},
onPaymentComplete: (e) => {
this.emitter.emit("payment:complete", e);
},
onPaymentError: (e) => {
this.emitter.emit("payment:error", e);
},
isApplePayAvailable: isApplePayAvailable(),
isEmbedded: !popup,
referrer: url.hostname,
origin: url.origin,
path: url.pathname,
params: url.search,
version: __VERSION__,
});
await this.zoid.renderTo(window, container, popup ? "popup" : "iframe");
this.#didRender = true;
if (this.#onRender)
this.#onRender();
}
}