-
Notifications
You must be signed in to change notification settings - Fork 62
/
button-manager.ts
430 lines (369 loc) · 12.9 KB
/
button-manager.ts
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
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* eslint-disable react/no-is-mounted */
import { loadScript } from '../lib/load-script';
export interface ReadyToPayChangeResponse {
isButtonVisible: boolean;
isReadyToPay: boolean;
paymentMethodPresent?: boolean;
}
export interface Config {
environment: google.payments.api.Environment;
existingPaymentMethodRequired?: boolean;
paymentRequest: google.payments.api.PaymentDataRequest;
onPaymentDataChanged?: google.payments.api.PaymentDataChangedHandler;
onPaymentAuthorized?: google.payments.api.PaymentAuthorizedHandler;
onLoadPaymentData?: (paymentData: google.payments.api.PaymentData) => void;
onCancel?: (reason: google.payments.api.PaymentsError) => void;
onError?: (error: Error | google.payments.api.PaymentsError) => void;
onReadyToPayChange?: (result: ReadyToPayChangeResponse) => void;
onClick?: (event: Event) => void;
buttonType?: google.payments.api.ButtonType;
buttonColor?: google.payments.api.ButtonColor;
buttonRadius?: number;
buttonSizeMode?: google.payments.api.ButtonSizeMode;
buttonLocale?: string;
}
interface ButtonManagerOptions {
cssSelector: string;
softwareInfoId: string;
softwareInfoVersion: string;
}
/**
* Manages the lifecycle of the Google Pay button.
*
* Includes lifecycle management of the `PaymentsClient` instance,
* `isReadyToPay`, `onClick`, `loadPaymentData`, and other callback methods.
*/
export class ButtonManager {
private client?: google.payments.api.PaymentsClient;
private config?: Config;
private element?: Element;
private options: ButtonManagerOptions;
private oldInvalidationValues?: any[];
isReadyToPay?: boolean;
paymentMethodPresent?: boolean;
constructor(options: ButtonManagerOptions) {
this.options = options;
}
getElement(): Element | undefined {
return this.element;
}
private isGooglePayLoaded(): boolean {
return 'google' in (window || global) && !!google?.payments?.api?.PaymentsClient;
}
async mount(element: Element): Promise<void> {
if (!this.isGooglePayLoaded()) {
try {
await loadScript('https://pay.google.com/gp/p/js/pay.js');
} catch (err) {
if (this.config?.onError) {
this.config.onError(err as Error);
} else {
console.error(err);
}
return;
}
}
this.element = element;
if (element) {
this.appendStyles();
if (this.config) {
this.updateElement();
}
}
}
unmount(): void {
this.element = undefined;
}
configure(newConfig: Config): Promise<void> {
let promise: Promise<void> | undefined = undefined;
this.config = newConfig;
if (!this.oldInvalidationValues || this.isClientInvalidated(newConfig)) {
promise = this.updateElement();
}
this.oldInvalidationValues = this.getInvalidationValues(newConfig);
return promise ?? Promise.resolve();
}
/**
* Creates client configuration options based on button configuration
* options.
*
* This method would normally be private but has been made public for
* testing purposes.
*
* @private
*/
createClientOptions(config: Config): google.payments.api.PaymentOptions {
const clientConfig: google.payments.api.PaymentOptions = {
environment: config.environment,
merchantInfo: this.createMerchantInfo(config),
};
if (config.onPaymentDataChanged || config.onPaymentAuthorized) {
clientConfig.paymentDataCallbacks = {};
if (config.onPaymentDataChanged) {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
clientConfig.paymentDataCallbacks.onPaymentDataChanged = paymentData => {
const result = config.onPaymentDataChanged!(paymentData);
return result || ({} as google.payments.api.PaymentDataRequestUpdate);
};
}
if (config.onPaymentAuthorized) {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
clientConfig.paymentDataCallbacks.onPaymentAuthorized = paymentData => {
const result = config.onPaymentAuthorized!(paymentData);
return result || ({} as google.payments.api.PaymentAuthorizationResult);
};
}
}
return clientConfig;
}
private createIsReadyToPayRequest(config: Config): google.payments.api.IsReadyToPayRequest {
const paymentRequest = config.paymentRequest;
const request: google.payments.api.IsReadyToPayRequest = {
apiVersion: paymentRequest.apiVersion,
apiVersionMinor: paymentRequest.apiVersionMinor,
allowedPaymentMethods: paymentRequest.allowedPaymentMethods,
existingPaymentMethodRequired: config.existingPaymentMethodRequired,
};
return request;
}
/**
* Constructs `loadPaymentData` request object based on button configuration.
*
* It infers request properties like `shippingAddressRequired`,
* `shippingOptionRequired`, and `billingAddressRequired` if not already set
* based on the presence of their associated options and parameters. It also
* infers `callbackIntents` based on the callback methods defined in button
* configuration.
*
* This method would normally be private but has been made public for
* testing purposes.
*
* @private
*/
createLoadPaymentDataRequest(config: Config): google.payments.api.PaymentDataRequest {
const request = {
...config.paymentRequest,
merchantInfo: this.createMerchantInfo(config),
};
// TODO: #13 re-enable inferrence if/when we agree as a team
return request;
}
private createMerchantInfo(config: Config): google.payments.api.MerchantInfo {
const merchantInfo: google.payments.api.MerchantInfo = {
...config.paymentRequest.merchantInfo,
};
// apply softwareInfo if not set
if (!merchantInfo.softwareInfo) {
merchantInfo.softwareInfo = {
id: this.options.softwareInfoId,
version: this.options.softwareInfoVersion,
};
}
return merchantInfo;
}
private isMounted(): boolean {
return this.element != null && this.element.isConnected !== false;
}
private removeButton(): void {
if (this.element instanceof ShadowRoot || this.element instanceof Element) {
for (const child of Array.from(this.element.children)) {
if (child.tagName !== 'STYLE') {
child.remove();
}
}
}
}
private async updateElement(): Promise<void> {
if (!this.isMounted()) return;
const element = this.getElement()!;
if (!this.config) {
throw new Error('google-pay-button: Missing configuration');
}
// remove existing button
this.removeButton();
try {
this.client = new google.payments.api.PaymentsClient(this.createClientOptions(this.config));
} catch (err) {
if (this.config.onError) {
this.config.onError(err as Error);
} else {
console.error(err);
}
return;
}
const buttonOptions: google.payments.api.ButtonOptions = {
buttonType: this.config.buttonType,
buttonColor: this.config.buttonColor,
buttonRadius: this.config.buttonRadius,
buttonSizeMode: this.config.buttonSizeMode,
buttonLocale: this.config.buttonLocale,
onClick: this.handleClick,
allowedPaymentMethods: this.config.paymentRequest.allowedPaymentMethods,
};
const rootNode = element.getRootNode();
if (rootNode instanceof ShadowRoot) {
buttonOptions.buttonRootNode = rootNode;
}
// pre-create button
const button = this.client.createButton(buttonOptions);
this.setClassName(element, [element.className, 'not-ready']);
element.appendChild(button);
let showButton = false;
let readyToPay: google.payments.api.IsReadyToPayResponse | undefined;
try {
readyToPay = await this.client.isReadyToPay(this.createIsReadyToPayRequest(this.config));
showButton =
(readyToPay.result && !this.config.existingPaymentMethodRequired)
|| (readyToPay.result && readyToPay.paymentMethodPresent && this.config.existingPaymentMethodRequired)
|| false;
} catch (err) {
if (this.config.onError) {
this.config.onError(err as Error);
} else {
console.error(err);
}
}
if (!this.isMounted()) return;
if (showButton) {
try {
this.client.prefetchPaymentData(this.createLoadPaymentDataRequest(this.config));
} catch (err) {
console.log('Error with prefetch', err);
}
// remove hidden className
this.setClassName(
element,
(element.className || '').split(' ').filter(className => className && className !== 'not-ready'),
);
}
if (this.isReadyToPay !== readyToPay?.result || this.paymentMethodPresent !== readyToPay?.paymentMethodPresent) {
this.isReadyToPay = !!readyToPay?.result;
this.paymentMethodPresent = readyToPay?.paymentMethodPresent;
if (this.config.onReadyToPayChange) {
const readyToPayResponse: ReadyToPayChangeResponse = {
isButtonVisible: showButton,
isReadyToPay: this.isReadyToPay,
};
if (this.paymentMethodPresent) {
readyToPayResponse.paymentMethodPresent = this.paymentMethodPresent;
}
this.config.onReadyToPayChange(readyToPayResponse);
}
}
}
/**
* Handles the click event of the Google Pay button.
*
* This method would normally be private but has been made public for
* testing purposes.
*
* @private
*/
handleClick = async (event: Event): Promise<void> => {
const config = this.config;
if (!config) {
throw new Error('google-pay-button: Missing configuration');
}
const request = this.createLoadPaymentDataRequest(config);
try {
if (config.onClick) {
config.onClick(event);
}
if (event.defaultPrevented) {
return;
}
const result = await this.client!.loadPaymentData(request);
if (config.onLoadPaymentData) {
config.onLoadPaymentData(result);
}
} catch (err) {
if ((err as google.payments.api.PaymentsError).statusCode === 'CANCELED') {
if (config.onCancel) {
config.onCancel(err as google.payments.api.PaymentsError);
}
} else if (config.onError) {
config.onError(err as google.payments.api.PaymentsError);
} else {
console.error(err);
}
}
};
private setClassName(element: Element, classNames: string[]): void {
const className = classNames.filter(name => name).join(' ');
if (className) {
element.className = className;
} else {
element.removeAttribute('class');
}
}
private appendStyles(): void {
if (typeof document === 'undefined') return;
const rootNode = this.element?.getRootNode() as Document | ShadowRoot | undefined;
const styleId = `default-google-style-${this.options.cssSelector.replace(/[^\w-]+/g, '')}-${
this.config?.buttonLocale
}`;
// initialize styles if rendering on the client:
if (rootNode) {
if (!rootNode.getElementById?.(styleId)) {
const style = document.createElement('style');
style.id = styleId;
style.type = 'text/css';
style.innerHTML = `
${this.options.cssSelector} {
display: inline-block;
}
${this.options.cssSelector}.not-ready {
width: 0;
height: 0;
overflow: hidden;
}
`;
if (rootNode instanceof Document && rootNode.head) {
rootNode.head.appendChild(style);
} else {
rootNode.appendChild(style);
}
}
}
}
private isClientInvalidated(newConfig: Config): boolean {
if (!this.oldInvalidationValues) return true;
const newValues = this.getInvalidationValues(newConfig);
return newValues.some(
(value, index) => JSON.stringify(value) !== JSON.stringify(this.oldInvalidationValues![index]),
);
}
private getInvalidationValues(config: Config): any[] {
return [
config.environment,
config.existingPaymentMethodRequired,
!!config.onPaymentDataChanged,
!!config.onPaymentAuthorized,
config.buttonType,
config.buttonColor,
config.buttonRadius,
config.buttonLocale,
config.buttonSizeMode,
config.paymentRequest.merchantInfo.merchantId,
config.paymentRequest.merchantInfo.merchantName,
config.paymentRequest.merchantInfo.softwareInfo?.id,
config.paymentRequest.merchantInfo.softwareInfo?.version,
config.paymentRequest.allowedPaymentMethods,
];
}
}