@fat-zebra/sdk 2.0.1-beta.0 → 2.0.1-beta.10

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/dist/hpp/hpp.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import Sca from '../sca';
2
2
  import { ChallengeWindowSize } from '../sca/types';
3
3
  import { Customer, PaymentIntent } from '../shared/types';
4
+ import ThreeDSecure from "../three_d_secure";
4
5
  declare const HPP_DEFAULT_OPTIONS: {
5
6
  [key: string]: boolean | string;
6
7
  };
@@ -11,6 +12,8 @@ interface HppModuleConfig {
11
12
  customer: Customer;
12
13
  username: string;
13
14
  sca: Sca;
15
+ threeDSecure: ThreeDSecure;
16
+ requestThreeDSEnabled: () => Promise<boolean>;
14
17
  test?: boolean;
15
18
  }
16
19
  interface HppLoadParams {
@@ -42,7 +45,7 @@ declare class Hpp {
42
45
  private customer;
43
46
  private username;
44
47
  private sca;
45
- private ThreeDSecure;
48
+ private threeDSecure;
46
49
  private cardToken;
47
50
  private postMessageClient;
48
51
  private test;
@@ -50,11 +53,14 @@ declare class Hpp {
50
53
  private headlessLoaded;
51
54
  private headlessPreviouslyLoaded;
52
55
  private iframeLoaded;
53
- private threeDSecureEnabled;
56
+ private isThreeDSecureEnabled;
57
+ private requestThreeDSEnabled;
54
58
  private challengeWindowSize;
55
59
  private scaHandler;
60
+ private crossFrameListenersBound;
61
+ private publicEventListenersBound;
56
62
  constructor(config: HppModuleConfig);
57
- setListenersAndEmitReady(): void;
63
+ setListenersAndEmitReady(): Promise<void>;
58
64
  load(config: HppLoadParams): void;
59
65
  purchase(): void;
60
66
  getPayNowUrl(options?: {
@@ -62,6 +68,7 @@ declare class Hpp {
62
68
  }): string;
63
69
  setCrossFramesEventListeners(): void;
64
70
  setPublicEventListeners(): void;
71
+ destroy(): void;
65
72
  createPurchase(extra?: {
66
73
  [key: string]: boolean | string;
67
74
  }): void;
package/dist/hpp/hpp.js CHANGED
@@ -4,15 +4,25 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
4
4
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
8
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9
+ return new (P || (P = Promise))(function (resolve, reject) {
10
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
12
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
13
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
14
+ });
15
+ };
7
16
  import * as bridge from '../shared/bridge-client';
8
17
  import { LocalStorageAccessTokenKey } from '../shared/constants';
9
18
  import { emit, off, on } from '../shared/event-manager';
10
19
  import { PostMessageClient } from '../shared/post-message-client';
11
20
  import { BridgeEvent, PublicEvent, } from '../shared/types';
12
21
  import * as util from '../shared/util';
13
- import { logMethod } from "../logging/logMethod";
14
22
  import { setTransactionReference } from "../logging/logger-context";
15
- import ThreeDSecure from "../three_d_secure";
23
+ import { logMethod } from "../logging/logMethod";
24
+ import env from "../shared/env";
25
+ import { configureLogger } from "../logging/instrument";
16
26
  const HPP_DEFAULT_OPTIONS = {
17
27
  enableSca: false,
18
28
  hideButton: false,
@@ -20,7 +30,7 @@ const HPP_DEFAULT_OPTIONS = {
20
30
  };
21
31
  class Hpp {
22
32
  constructor(config) {
23
- this.threeDSecureEnabled = false;
33
+ this.isThreeDSecureEnabled = false;
24
34
  this.paymentIntent = config.paymentIntent;
25
35
  this.customer = config.customer;
26
36
  this.username = config.username;
@@ -30,58 +40,66 @@ class Hpp {
30
40
  this.headlessLoaded = false;
31
41
  this.headlessPreviouslyLoaded = false;
32
42
  this.iframeLoaded = false;
33
- this.postMessageClient = new PostMessageClient({
34
- channel: 'sca',
35
- target: this.iframe
43
+ this.threeDSecure = config.threeDSecure;
44
+ this.requestThreeDSEnabled = config.requestThreeDSEnabled;
45
+ this.crossFrameListenersBound = false;
46
+ this.publicEventListenersBound = false;
47
+ configureLogger({
48
+ baseUrl: env[process.env.API_ENV].payNowUrl
36
49
  });
37
50
  }
38
51
  setListenersAndEmitReady() {
39
- const message = {
40
- channel: 'sca',
41
- subject: BridgeEvent.READY,
42
- data: {}
43
- };
44
- if (this.headlessLoaded && this.iframeLoaded) {
45
- // initial headless load
46
- this.ThreeDSecure = new ThreeDSecure({
47
- bridge: this.headless,
48
- environment: process.env.API_ENV,
49
- iframe: this.iframe
50
- });
51
- this.setCrossFramesEventListeners();
52
- this.setPublicEventListeners();
53
- emit(PublicEvent.HPP_READY);
54
- this.iframe.contentWindow.postMessage(message, '*');
55
- }
56
- else if (this.headlessPreviouslyLoaded && this.iframeLoaded) {
57
- this.ThreeDSecure = new ThreeDSecure({
58
- bridge: this.headless,
59
- environment: process.env.API_ENV,
60
- iframe: this.iframe
61
- });
62
- this.iframe.contentWindow.postMessage(message, '*');
63
- // subsequent iframe loads after headless has been previously loaded
64
- // this caters for the SPA scenario
65
- emit(PublicEvent.HPP_READY);
66
- }
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ if (!this.crossFrameListenersBound) {
54
+ this.setCrossFramesEventListeners();
55
+ this.crossFrameListenersBound = true;
56
+ }
57
+ if (this.headlessLoaded && this.iframeLoaded) {
58
+ this.isThreeDSecureEnabled = yield this.requestThreeDSEnabled();
59
+ if (!this.publicEventListenersBound && !this.isThreeDSecureEnabled) {
60
+ this.setPublicEventListeners();
61
+ this.publicEventListenersBound = true;
62
+ }
63
+ emit(PublicEvent.HPP_READY);
64
+ }
65
+ else if (this.headlessPreviouslyLoaded && this.iframeLoaded) {
66
+ this.isThreeDSecureEnabled = yield this.requestThreeDSEnabled();
67
+ // subsequent iframe loads after headless has been previously loaded
68
+ // this caters for the SPA scenario
69
+ if (!this.publicEventListenersBound && !this.isThreeDSecureEnabled) {
70
+ this.setPublicEventListeners();
71
+ this.publicEventListenersBound = true;
72
+ }
73
+ emit(PublicEvent.HPP_READY);
74
+ }
75
+ });
67
76
  }
68
77
  load(config) {
69
- this.challengeWindowSize = config.options.challengeWindowSize;
78
+ var _a;
79
+ this.challengeWindowSize = (_a = config.options) === null || _a === void 0 ? void 0 : _a.challengeWindowSize;
70
80
  setTransactionReference(config.paymentIntent.payment.reference);
71
- this.hppOptions = config.options;
81
+ this.hppOptions = config.options || {};
72
82
  const { el, isExisting } = bridge.load2(process.env.PAYNOW_BRIDGE_URL);
73
83
  this.headless = el;
74
84
  this.headlessPreviouslyLoaded = isExisting;
75
85
  this.iframe = document.createElement('iframe');
76
86
  document.getElementById(config.containerId).appendChild(this.iframe);
77
- this.headless.onload = () => {
87
+ this.postMessageClient = new PostMessageClient({
88
+ channel: 'sca',
89
+ target: this.iframe
90
+ });
91
+ this.headless.addEventListener('load', () => {
78
92
  this.headlessLoaded = true;
79
93
  this.setListenersAndEmitReady();
80
- };
94
+ });
81
95
  this.iframe.onload = () => {
82
96
  this.iframeLoaded = true;
83
97
  this.setListenersAndEmitReady();
84
98
  };
99
+ if (this.headlessPreviouslyLoaded) {
100
+ this.headlessLoaded = true;
101
+ this.setListenersAndEmitReady();
102
+ }
85
103
  const payNowUrl = this.getPayNowUrl(config.options);
86
104
  this.iframe.setAttribute("src", payNowUrl);
87
105
  this.iframe.setAttribute('allow', 'payment');
@@ -141,13 +159,14 @@ class Hpp {
141
159
  if (this.hppOptions.tokenizeOnly)
142
160
  return;
143
161
  if (this.hppOptions.enableSca) {
144
- if (this.threeDSecureEnabled) {
145
- this.ThreeDSecure.run({
162
+ if (this.isThreeDSecureEnabled) {
163
+ this.threeDSecure.run({
146
164
  paymentIntent: this.paymentIntent,
147
165
  merchantUsername: this.username,
148
166
  cardToken: this.cardToken,
149
167
  test: this.test,
150
168
  challengeWindowSize: this.challengeWindowSize,
169
+ iframe: this.iframe,
151
170
  tokenizeOnly: false
152
171
  });
153
172
  return; // do not continue execution to old 3DS
@@ -211,16 +230,7 @@ class Hpp {
211
230
  data: data,
212
231
  });
213
232
  };
214
- handlers[BridgeEvent.THREE_D_SECURE_ENABLED] = (data) => {
215
- this.threeDSecureEnabled = typeof data === "boolean" ? data : false;
216
- if (this.threeDSecureEnabled) {
217
- // setPublicEventListeners is set before this feature flag is returned.
218
- // we need to therefore unset the scaHandler (for the old implementation or we will get two purchase requests
219
- off(PublicEvent.SCA_SUCCESS, this.scaHandler);
220
- }
221
- };
222
- const handlersIncludingThreeDSecure = Object.assign(Object.assign({}, handlers), this.ThreeDSecure.messageHandlers());
223
- this.postMessageClient.setEventListeners(handlersIncludingThreeDSecure);
233
+ this.postMessageClient.setEventListeners(handlers);
224
234
  }
225
235
  setPublicEventListeners() {
226
236
  this.scaHandler = (event) => {
@@ -232,6 +242,12 @@ class Hpp {
232
242
  };
233
243
  on(PublicEvent.SCA_SUCCESS, this.scaHandler);
234
244
  }
245
+ destroy() {
246
+ if (this.publicEventListenersBound && this.scaHandler) {
247
+ off(PublicEvent.SCA_SUCCESS, this.scaHandler);
248
+ this.publicEventListenersBound = false;
249
+ }
250
+ }
235
251
  createPurchase(extra = null) {
236
252
  const message = {
237
253
  channel: 'sca',
@@ -1,7 +1,11 @@
1
- type LogOptions = {
2
- endpoint?: string;
3
- mapArgs?: (args: unknown[]) => unknown;
1
+ export type LogOptions<A extends unknown[]> = {
2
+ endpoint?: string | ((...args: A) => string);
3
+ mapArgs?: (args: A) => unknown;
4
4
  enabled?: () => boolean;
5
5
  };
6
- export declare function instrumentFunction<A extends any[], R>(methodName: string, fn: (...args: A) => R, opts?: LogOptions): (...args: A) => R;
6
+ type LoggerConfig = {
7
+ baseUrl?: string;
8
+ };
9
+ export declare function configureLogger(config: LoggerConfig): void;
10
+ export declare function instrumentFunction<A extends unknown[], R>(methodName: string, fn: (...args: A) => R, opts?: LogOptions<A>): (...args: A) => R;
7
11
  export {};
@@ -1,7 +1,13 @@
1
1
  import axios from "axios";
2
2
  import { getLoggerUsername, getTransactionReference } from "./logger-context";
3
+ let loggerConfig = {};
4
+ export function configureLogger(config) {
5
+ loggerConfig = config;
6
+ }
3
7
  function defaultEndpoint() {
4
- return `${process.env.PAYNOW_BASE_URL}/log_sdk`;
8
+ return loggerConfig.baseUrl
9
+ ? `${loggerConfig.baseUrl}/log_sdk`
10
+ : `${process.env.PAYNOW_BASE_URL}/log_sdk`;
5
11
  }
6
12
  function sendLog(endpoint, payload) {
7
13
  try {
@@ -20,12 +26,15 @@ function sendLog(endpoint, payload) {
20
26
  }
21
27
  }
22
28
  export function instrumentFunction(methodName, fn, opts = {}) {
23
- var _a, _b, _c;
24
- const endpoint = (_a = opts.endpoint) !== null && _a !== void 0 ? _a : defaultEndpoint();
25
- const enabled = (_b = opts.enabled) !== null && _b !== void 0 ? _b : (() => true);
26
- const mapArgs = (_c = opts.mapArgs) !== null && _c !== void 0 ? _c : ((a) => a);
29
+ var _a, _b;
30
+ const enabled = (_a = opts.enabled) !== null && _a !== void 0 ? _a : (() => true);
31
+ const mapArgs = (_b = opts.mapArgs) !== null && _b !== void 0 ? _b : ((a) => a);
27
32
  return function instrumented(...args) {
33
+ var _a;
28
34
  if (enabled()) {
35
+ const endpoint = typeof opts.endpoint === "function"
36
+ ? opts.endpoint(...args)
37
+ : (_a = opts.endpoint) !== null && _a !== void 0 ? _a : defaultEndpoint();
29
38
  const payload = {
30
39
  username: getLoggerUsername(),
31
40
  reference: getTransactionReference(),
@@ -1,7 +1,7 @@
1
- type LogOptions = {
2
- endpoint?: string;
3
- mapArgs?: (args: unknown[]) => unknown;
1
+ type LogOptions<A extends unknown[]> = {
2
+ endpoint?: string | ((args: A) => string);
3
+ mapArgs?: (args: A) => unknown;
4
4
  enabled?: () => boolean;
5
5
  };
6
- export declare function logMethod(opts?: LogOptions): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
6
+ export declare function logMethod(opts?: LogOptions<unknown[]>): (target: any, propertyKey: string, descriptor: PropertyDescriptor) => PropertyDescriptor;
7
7
  export {};
@@ -35,6 +35,7 @@ export function logMethod(opts = {}) {
35
35
  const original = descriptor.value;
36
36
  if (typeof original !== "function") {
37
37
  console.error(`@logMethod can only decorate methods (${propertyKey})`);
38
+ return descriptor;
38
39
  }
39
40
  descriptor.value = instrumentFunction(propertyKey, original, Object.assign(Object.assign({}, opts), { mapArgs: (_a = opts.mapArgs) !== null && _a !== void 0 ? _a : ((args) => args.map((a) => {
40
41
  if (!a || typeof a !== "object")
package/dist/main.d.ts CHANGED
@@ -28,13 +28,21 @@ export default class FatZebra {
28
28
  private fzConfig;
29
29
  private gatewayClient;
30
30
  private headless;
31
+ private threeDSecure;
32
+ private threeDSecureListenersBound;
33
+ private bridgeReady;
31
34
  constructor(config: FZConfig);
32
35
  tokenizeCard(card: Card): void;
33
36
  cardDidTokenize(callback: (data: any) => void): void;
37
+ private requestThreeDSEnabled;
34
38
  verifyCard(params: VerifyCardParams): Promise<void>;
39
+ setThreeDSecureListeners(): void;
35
40
  renderPaymentsPage(params: HppLoadParams): void;
36
41
  renderApplePayButton(params: ApplePayParams): void;
37
42
  renderClickToPay(params: HppClickToPayParams): void;
43
+ reportThreeDSecureFetchedOnInit(data: any): void;
44
+ reportThreeDSecureFetched(data: any, paymentIntent?: PaymentIntent): void;
45
+ reportRequestThreedsEnabledTimeout(paymentIntent?: PaymentIntent): void;
38
46
  checkout(): void;
39
47
  on(event: PublicEvent, callback: (e: any) => void): void;
40
48
  off(event: PublicEvent, callback: (e: any) => void): void;
package/dist/main.js CHANGED
@@ -23,13 +23,14 @@ import { toHumanizedErrors, validateClickToPayLoadParams, validateHppLoadParams,
23
23
  import GatewayClient from './shared/api-gateway-client';
24
24
  import { Hpp } from './hpp';
25
25
  import ClickToPay from './click_to_pay';
26
- import { validateApplePayLoadParams } from "./validation/validators/apple-pay-load-params-button-validator";
27
- import { ApplePay } from "./applepay";
28
- import { setLoggerUsername } from "./logging/logger-context";
29
- import { logMethod } from "./logging/logMethod";
30
- import ThreeDSecure from "./three_d_secure";
26
+ import { validateApplePayLoadParams } from './validation/validators/apple-pay-load-params-button-validator';
27
+ import { ApplePay } from './applepay';
28
+ import { setLoggerUsername } from './logging/logger-context';
29
+ import { logMethod } from './logging/logMethod';
30
+ import ThreeDSecure from './three_d_secure';
31
31
  export default class FatZebra {
32
32
  constructor(config) {
33
+ this.threeDSecureListenersBound = false;
33
34
  setLoggerUsername(config.username);
34
35
  this.fzConfig = config;
35
36
  window.MerchantUsername = config.username;
@@ -41,7 +42,36 @@ export default class FatZebra {
41
42
  gatewayClient: this.gatewayClient,
42
43
  });
43
44
  this.sca.loadScript();
44
- this.headless = bridge.load(process.env.PAYNOW_BRIDGE_URL);
45
+ const { el, isExisting } = bridge.load2(process.env.PAYNOW_BRIDGE_URL);
46
+ this.headless = el;
47
+ this.threeDSecure = new ThreeDSecure({
48
+ bridge: this.headless,
49
+ environment: process.env.API_ENV,
50
+ });
51
+ // bridgeReady is a single promise created once.
52
+ // After it resolves (bridge loaded), every subsequent "await this.bridgeReady"
53
+ // returns instantly — there's no re-evaluation.
54
+ // So for a SPA where the bridge is already loaded, there's zero overhead.
55
+ if (isExisting) {
56
+ console.log('headless exists');
57
+ this.bridgeReady = Promise.resolve();
58
+ this.setThreeDSecureListeners();
59
+ }
60
+ else {
61
+ this.bridgeReady = new Promise((resolve) => {
62
+ this.headless.addEventListener('load', () => {
63
+ console.log('headless loaded');
64
+ this.setThreeDSecureListeners();
65
+ resolve();
66
+ });
67
+ });
68
+ }
69
+ const message = {
70
+ channel: 'sca',
71
+ subject: BridgeEvent.READY,
72
+ data: {},
73
+ };
74
+ window.top.postMessage(message, '*');
45
75
  }
46
76
  tokenizeCard(card) {
47
77
  const channel = 'sca';
@@ -54,7 +84,7 @@ export default class FatZebra {
54
84
  card_number: card.number,
55
85
  card_expiry: `${card.expiryMonth}/${card.expiryYear}`,
56
86
  cvv: card.cvv,
57
- }
87
+ },
58
88
  };
59
89
  this.headless.contentWindow.postMessage(message, '*');
60
90
  }
@@ -62,7 +92,7 @@ export default class FatZebra {
62
92
  const channel = 'sca';
63
93
  const postMessageClient = new PostMessageClient({
64
94
  channel,
65
- target: this.headless
95
+ target: this.headless,
66
96
  });
67
97
  const handlers = {};
68
98
  handlers[BridgeEvent.TOKENIZE_CARD_RESPONSE] = (data) => {
@@ -70,66 +100,154 @@ export default class FatZebra {
70
100
  };
71
101
  postMessageClient.setEventListeners(handlers);
72
102
  }
103
+ requestThreeDSEnabled(timeout, paymentIntent) {
104
+ return __awaiter(this, void 0, void 0, function* () {
105
+ console.log('requestThreeDSEnabled');
106
+ // If the bridge loads in time, bridgeReady wins and we can continue requesting the flag.
107
+ // If not, the timeout resolves the race and we fall through
108
+ // — the postMessage is sent to an unready bridge, the response never arrives,
109
+ // and the existing window.setTimeout at the bottom fires and resolves false.
110
+ // The total worst-case wait is still bounded by timeout.
111
+ yield Promise.race([
112
+ this.bridgeReady,
113
+ new Promise((resolve) => window.setTimeout(resolve, timeout)),
114
+ ]);
115
+ return new Promise((resolve) => {
116
+ const channel = 'sca';
117
+ const postMessageClient = new PostMessageClient({
118
+ channel,
119
+ target: this.headless,
120
+ });
121
+ let resolved = false;
122
+ postMessageClient.setEventListeners({
123
+ [BridgeEvent.THREE_D_SECURE_ENABLED]: (data) => {
124
+ const enabled = typeof data === 'boolean' ? data : false;
125
+ if (!resolved) {
126
+ this.reportThreeDSecureFetched(data, paymentIntent);
127
+ resolved = true;
128
+ resolve(enabled);
129
+ }
130
+ },
131
+ });
132
+ const message = {
133
+ channel,
134
+ subject: 'fzi.is-enabled-three-d-secure-req',
135
+ data: {
136
+ merchant: this.fzConfig.username,
137
+ access_token: window.localStorage.getItem(LocalStorageAccessTokenKey),
138
+ },
139
+ };
140
+ postMessageClient.send(message);
141
+ window.setTimeout(() => {
142
+ if (!resolved) {
143
+ this.reportRequestThreedsEnabledTimeout(paymentIntent);
144
+ resolved = true;
145
+ resolve(false);
146
+ }
147
+ }, timeout);
148
+ });
149
+ });
150
+ }
73
151
  verifyCard(params) {
74
152
  return __awaiter(this, void 0, void 0, function* () {
75
- var _a;
153
+ var _a, _b;
154
+ console.log('verifyCard');
76
155
  const valid = validateVerifyCardParams(params);
77
156
  if (!valid) {
78
157
  emit(PublicEvent.VALIDATION_ERROR, {
79
158
  errors: toHumanizedErrors(validateVerifyCardParams.errors),
80
- data: null
159
+ data: null,
81
160
  });
82
161
  return;
83
162
  }
84
- const threeDSecure = new ThreeDSecure({
85
- bridge: this.headless,
86
- environment: process.env.API_ENV
87
- });
163
+ const threeDSEnabled = yield this.requestThreeDSEnabled(1000, params.paymentIntent);
88
164
  switch (params.paymentMethod.type) {
89
- case PaymentMethodType.CARD:
165
+ case PaymentMethodType.CARD: {
166
+ console.log('Verify card (new card)');
90
167
  const card = params.paymentMethod.data;
91
168
  this.cardDidTokenize((data) => __awaiter(this, void 0, void 0, function* () {
92
- var _a;
93
- threeDSecure.run({
169
+ var _a, _b;
170
+ if (threeDSEnabled) {
171
+ this.threeDSecure.run({
172
+ paymentIntent: params.paymentIntent,
173
+ cardToken: data.token,
174
+ merchantUsername: this.fzConfig.username,
175
+ challengeWindowSize: (_a = params.options) === null || _a === void 0 ? void 0 : _a.challengeWindowSize,
176
+ test: this.fzConfig.test,
177
+ tokenizeOnly: true,
178
+ });
179
+ }
180
+ else {
181
+ const bin = card.number.substr(0, 6);
182
+ this.sca.run({
183
+ cardToken: data.token,
184
+ customer: params.customer,
185
+ paymentIntent: params.paymentIntent,
186
+ bin,
187
+ challengeWindowSize: (_b = params.options) === null || _b === void 0 ? void 0 : _b.challengeWindowSize,
188
+ });
189
+ }
190
+ }));
191
+ this.tokenizeCard(card);
192
+ break;
193
+ }
194
+ case PaymentMethodType.CARD_ON_FILE: {
195
+ console.log('Verify card (card on file)');
196
+ const cardToken = params.paymentMethod.data.token;
197
+ if (threeDSEnabled) {
198
+ this.threeDSecure.run({
94
199
  paymentIntent: params.paymentIntent,
95
- cardToken: data.token,
200
+ cardToken,
96
201
  merchantUsername: this.fzConfig.username,
97
202
  challengeWindowSize: (_a = params.options) === null || _a === void 0 ? void 0 : _a.challengeWindowSize,
98
203
  test: this.fzConfig.test,
99
- tokenizeOnly: true
204
+ tokenizeOnly: true,
100
205
  });
101
- }));
102
- this.tokenizeCard(card);
103
- break;
104
- case PaymentMethodType.CARD_ON_FILE:
105
- const cardToken = params.paymentMethod.data.token;
106
- threeDSecure.run({
107
- paymentIntent: params.paymentIntent,
108
- cardToken: cardToken,
109
- merchantUsername: this.fzConfig.username,
110
- challengeWindowSize: (_a = params.options) === null || _a === void 0 ? void 0 : _a.challengeWindowSize,
111
- test: this.fzConfig.test,
112
- tokenizeOnly: true
113
- });
206
+ }
207
+ else {
208
+ const bin = (yield this.gatewayClient.getCard({
209
+ card_token: cardToken,
210
+ })).data.bin;
211
+ this.sca.run({
212
+ cardToken,
213
+ customer: params.customer,
214
+ paymentIntent: params.paymentIntent,
215
+ bin,
216
+ challengeWindowSize: (_b = params.options) === null || _b === void 0 ? void 0 : _b.challengeWindowSize,
217
+ });
218
+ }
114
219
  break;
220
+ }
115
221
  }
116
- const channel = 'sca';
117
- const postMessageClient = new PostMessageClient({
118
- channel,
119
- target: this.headless
120
- });
121
- postMessageClient.setEventListeners(threeDSecure.messageHandlers());
122
222
  });
123
223
  }
224
+ setThreeDSecureListeners() {
225
+ console.log('setThreeDSecureListeners');
226
+ if (this.threeDSecureListenersBound)
227
+ return;
228
+ const channel = 'sca';
229
+ const postMessageClient = new PostMessageClient({
230
+ channel,
231
+ target: this.headless,
232
+ });
233
+ const handlers = this.threeDSecure.messageHandlers();
234
+ postMessageClient.setEventListeners(handlers);
235
+ this.threeDSecureListenersBound = true;
236
+ }
124
237
  renderPaymentsPage(params) {
238
+ var _a;
239
+ console.log('renderPaymentsPage');
125
240
  const valid = validateHppLoadParams(params);
126
241
  if (!valid) {
127
242
  emit(PublicEvent.VALIDATION_ERROR, {
128
243
  errors: toHumanizedErrors(validateHppLoadParams.errors),
129
- data: null
244
+ data: null,
130
245
  });
131
246
  return;
132
247
  }
248
+ if ((_a = window.HPP) === null || _a === void 0 ? void 0 : _a.destroy) {
249
+ window.HPP.destroy();
250
+ }
133
251
  window.HPP = new Hpp({
134
252
  version: params.version,
135
253
  paymentIntent: params.paymentIntent,
@@ -137,6 +255,8 @@ export default class FatZebra {
137
255
  username: this.fzConfig.username,
138
256
  sca: this.sca,
139
257
  test: this.fzConfig.test,
258
+ threeDSecure: this.threeDSecure,
259
+ requestThreeDSEnabled: () => this.requestThreeDSEnabled(1000, params.paymentIntent),
140
260
  });
141
261
  window.HPP.load(params);
142
262
  }
@@ -145,19 +265,19 @@ export default class FatZebra {
145
265
  if (!valid) {
146
266
  emit(PublicEvent.VALIDATION_ERROR, {
147
267
  errors: toHumanizedErrors(validateApplePayLoadParams.errors),
148
- data: null
268
+ data: null,
149
269
  });
150
270
  return;
151
271
  }
152
272
  window.ApplePayButton = new ApplePay({
153
273
  environment: params.environment,
154
274
  paymentIntent: params.paymentIntent,
155
- username: this.fzConfig.username
275
+ username: this.fzConfig.username,
156
276
  });
157
277
  window.ApplePayButton.load({
158
278
  containerId: params.containerId,
159
279
  paymentIntent: params.paymentIntent,
160
- options: params.options
280
+ options: params.options,
161
281
  });
162
282
  }
163
283
  renderClickToPay(params) {
@@ -165,7 +285,7 @@ export default class FatZebra {
165
285
  if (!valid) {
166
286
  emit(PublicEvent.VALIDATION_ERROR, {
167
287
  errors: toHumanizedErrors(validateClickToPayLoadParams.errors),
168
- data: null
288
+ data: null,
169
289
  });
170
290
  return;
171
291
  }
@@ -176,6 +296,15 @@ export default class FatZebra {
176
296
  });
177
297
  window.HPP.load(params);
178
298
  }
299
+ reportThreeDSecureFetchedOnInit(data) {
300
+ console.log("three_d_secure fetched on init", data);
301
+ }
302
+ reportThreeDSecureFetched(data, paymentIntent) {
303
+ console.log("three_d_secure fetched", data);
304
+ }
305
+ reportRequestThreedsEnabledTimeout(paymentIntent) {
306
+ console.log("3DS enabled check timed out");
307
+ }
179
308
  checkout() {
180
309
  window.HPP.purchase();
181
310
  }
@@ -189,6 +318,18 @@ export default class FatZebra {
189
318
  onOnce(event, callback);
190
319
  }
191
320
  }
321
+ __decorate([
322
+ logMethod({
323
+ mapArgs: (args) => {
324
+ const params = args[0];
325
+ return [
326
+ {
327
+ payment_intent: params === null || params === void 0 ? void 0 : params.paymentIntent
328
+ },
329
+ ];
330
+ },
331
+ })
332
+ ], FatZebra.prototype, "requestThreeDSEnabled", null);
192
333
  __decorate([
193
334
  logMethod({
194
335
  mapArgs: (args) => {
@@ -204,4 +345,53 @@ __decorate([
204
345
  },
205
346
  })
206
347
  ], FatZebra.prototype, "verifyCard", null);
348
+ __decorate([
349
+ logMethod({
350
+ mapArgs: (args) => {
351
+ const params = args[0];
352
+ return [
353
+ {
354
+ payment_intent: params.paymentIntent,
355
+ version: params.version
356
+ },
357
+ ];
358
+ },
359
+ })
360
+ ], FatZebra.prototype, "renderPaymentsPage", null);
361
+ __decorate([
362
+ logMethod({
363
+ mapArgs: (args) => {
364
+ const data = args[0];
365
+ return [
366
+ {
367
+ data
368
+ },
369
+ ];
370
+ },
371
+ })
372
+ ], FatZebra.prototype, "reportThreeDSecureFetchedOnInit", null);
373
+ __decorate([
374
+ logMethod({
375
+ mapArgs: (args) => {
376
+ const data = args[0];
377
+ return [
378
+ {
379
+ data
380
+ },
381
+ ];
382
+ },
383
+ })
384
+ ], FatZebra.prototype, "reportThreeDSecureFetched", null);
385
+ __decorate([
386
+ logMethod({
387
+ mapArgs: (args) => {
388
+ const data = args[0];
389
+ return [
390
+ {
391
+ data
392
+ },
393
+ ];
394
+ },
395
+ })
396
+ ], FatZebra.prototype, "reportRequestThreedsEnabledTimeout", null);
207
397
  export { FatZebra, };
@@ -5,8 +5,12 @@ import Sca from "../sca";
5
5
  import GatewayClient from "../shared/api-gateway-client";
6
6
  import { generateVerifyURL } from "./verifyUrl";
7
7
  import useMessage from "./useMessage";
8
- import { instrumentFunction } from "../logging/instrument";
9
- const logUseFatZebra = instrumentFunction("useFatZebra", (meta) => meta, { mapArgs: ([meta]) => [meta] });
8
+ import { configureLogger, instrumentFunction } from "../logging/instrument";
9
+ import env from "../shared/env";
10
+ const logUseFatZebra = instrumentFunction("useFatZebra", (meta) => meta, {
11
+ mapArgs: ([meta]) => meta,
12
+ endpoint: (meta) => `${env[meta.environment].payNowUrl}/log_sdk`,
13
+ });
10
14
  const useFatZebra = ({ config, handlers, cardToken }) => {
11
15
  const { options, accessToken, paymentIntent, username } = config;
12
16
  const sca = useMemo(() => {
@@ -25,6 +29,9 @@ const useFatZebra = ({ config, handlers, cardToken }) => {
25
29
  config
26
30
  });
27
31
  useEffect(() => {
32
+ configureLogger({
33
+ baseUrl: env[config.environment].payNowUrl
34
+ });
28
35
  logUseFatZebra({
29
36
  environment: config.environment,
30
37
  reference: config.paymentIntent.payment.reference,
@@ -40,12 +40,14 @@ const useMessage = ({ paymentIntent, options, handlers, sca, config }) => {
40
40
  });
41
41
  }
42
42
  if (options && options.sca_enabled && threeDSecureEnabled) {
43
+ const iframe = document.querySelector('[name="renderIframe"]');
43
44
  threeDSecureRef.current.run({
44
45
  paymentIntent,
45
46
  cardToken: data.token,
46
47
  merchantUsername: config.username,
47
48
  test: config.environment !== Environment.production,
48
- tokenizeOnly: config.options.tokenize_only
49
+ tokenizeOnly: config.options.tokenize_only,
50
+ iframe: iframe
49
51
  });
50
52
  return;
51
53
  }
@@ -67,13 +69,11 @@ const useMessage = ({ paymentIntent, options, handlers, sca, config }) => {
67
69
  const headless = el;
68
70
  let onMessage;
69
71
  headless.onload = () => {
70
- const iframe = document.querySelector('[name="renderIframe"]');
71
72
  const threeDS = new ThreeDSecure({
72
73
  successCallback,
73
74
  failureCallback,
74
75
  bridge: headless,
75
76
  environment: config.environment,
76
- iframe: iframe
77
77
  });
78
78
  threeDSecureRef.current = threeDS;
79
79
  const messages = threeDS.messageHandlers(); // { [subject]: (payload) => void }
package/dist/sca/index.js CHANGED
@@ -58,6 +58,7 @@ class Sca {
58
58
  }
59
59
  run(config) {
60
60
  return __awaiter(this, void 0, void 0, function* () {
61
+ console.log('Running 3DS (SCA)');
61
62
  try {
62
63
  if (!this._cardinal) {
63
64
  this._cardinal = new CardinalManager();
@@ -1,7 +1,7 @@
1
- declare const bridgeUrl = "https://paynow.test/sdk/bridge";
1
+ declare const bridgeUrl = "http://localhost:3006/sdk/bridge";
2
2
  declare const apiUrl = "https://api.test/sdk";
3
3
  declare const payNowUrl = "https://paynow.test";
4
4
  declare const songbirdUrl = "https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js";
5
5
  declare const cybersourceUrl = "https://centinelapistag.cardinalcommerce.com";
6
- declare const returnCybersourceUrl = "https://paynow.test/return";
6
+ declare const returnCybersourceUrl = "https://48e5-115-130-65-211.ngrok-free.app/return";
7
7
  export { bridgeUrl, apiUrl, payNowUrl, songbirdUrl, cybersourceUrl, returnCybersourceUrl };
@@ -1,7 +1,7 @@
1
- const bridgeUrl = "https://paynow.test/sdk/bridge";
1
+ const bridgeUrl = "http://localhost:3006/sdk/bridge";
2
2
  const apiUrl = "https://api.test/sdk";
3
3
  const payNowUrl = "https://paynow.test";
4
4
  const songbirdUrl = "https://songbirdstag.cardinalcommerce.com/edge/v1/songbird.js";
5
5
  const cybersourceUrl = "https://centinelapistag.cardinalcommerce.com";
6
- const returnCybersourceUrl = "https://paynow.test/return";
6
+ const returnCybersourceUrl = "https://48e5-115-130-65-211.ngrok-free.app/return";
7
7
  export { bridgeUrl, apiUrl, payNowUrl, songbirdUrl, cybersourceUrl, returnCybersourceUrl };
@@ -22,14 +22,15 @@ declare class ThreeDSecure {
22
22
  private failureCallback;
23
23
  private tokenizeOnly;
24
24
  private iframe?;
25
- constructor({ successCallback, failureCallback, environment, bridge, iframe }: ThreeDSecureConfig);
26
- run({ paymentIntent, cardToken, merchantUsername, challengeWindowSize, test, tokenizeOnly }: {
25
+ constructor({ successCallback, failureCallback, environment, bridge }: ThreeDSecureConfig);
26
+ run({ paymentIntent, cardToken, merchantUsername, challengeWindowSize, test, tokenizeOnly, iframe }: {
27
27
  paymentIntent: PaymentIntent;
28
28
  cardToken: string;
29
29
  merchantUsername: string;
30
30
  challengeWindowSize?: ChallengeWindowSize;
31
31
  test: boolean;
32
32
  tokenizeOnly?: boolean;
33
+ iframe?: HTMLIFrameElement;
33
34
  }): void;
34
35
  setupResponse(data: DeviceDataCollectionMessage): void;
35
36
  messageHandlers(): {
@@ -43,6 +44,7 @@ declare class ThreeDSecure {
43
44
  private validateAuthentication;
44
45
  private validationAuthenticationResponse;
45
46
  private createPurchase;
47
+ private listenDeviceCollectionReady;
46
48
  private setLoading;
47
49
  }
48
50
  export default ThreeDSecure;
@@ -18,16 +18,18 @@ import { getThreeDSecureValidationResult } from "./utility/getValidationResult";
18
18
  import { ChallengeWindowSize } from "../sca/types";
19
19
  import * as util from "../shared/util";
20
20
  class ThreeDSecure {
21
- constructor({ successCallback, failureCallback, environment, bridge, iframe }) {
21
+ constructor({ successCallback, failureCallback, environment, bridge }) {
22
22
  this.tokenizeOnly = false;
23
23
  this.headlessBridge = bridge;
24
24
  this.environment = environment;
25
25
  this.successCallback = successCallback;
26
26
  this.failureCallback = failureCallback;
27
- this.iframe = iframe;
28
27
  DeviceDataCollection.listenDataCollectionResponse(environment);
28
+ this.listenDeviceCollectionReady();
29
29
  }
30
- run({ paymentIntent, cardToken, merchantUsername, challengeWindowSize, test, tokenizeOnly }) {
30
+ run({ paymentIntent, cardToken, merchantUsername, challengeWindowSize, test, tokenizeOnly, iframe }) {
31
+ console.log('Running 3DS (ThreeDSecure)');
32
+ this.iframe = iframe;
31
33
  this.tokenizeOnly = tokenizeOnly;
32
34
  this.setLoading();
33
35
  this.paymentIntent = paymentIntent;
@@ -47,12 +49,6 @@ class ThreeDSecure {
47
49
  handlers[BridgeEvent.SETUP_THREE_D_SECURE_SUCCESS_RESPONSE] = (data) => {
48
50
  this.setupResponse(data);
49
51
  };
50
- on(PublicEvent.DEVICE_PROFILE_READY_THREE_D_SECURE_EVENT, () => this.checkEnrollment({
51
- paymentIntent: this.paymentIntent,
52
- cardToken: this.cardToken,
53
- merchantUsername: this.merchantUsername,
54
- cybersourceReferenceId: this.cybersourceReferenceId,
55
- }));
56
52
  handlers[BridgeEvent.ENROL_THREE_D_SECURE_RESPONSE] = (data) => {
57
53
  this.enrolmentResponse(data);
58
54
  };
@@ -63,7 +59,7 @@ class ThreeDSecure {
63
59
  this.validationAuthenticationResponse(data);
64
60
  };
65
61
  handlers[BridgeEvent.THREE_D_SECURE_FAILURE_RESPONSE] = (data) => {
66
- emit(PublicEvent.SCA_ERROR, { errors: [data.errors], data: data });
62
+ emit(PublicEvent.SCA_ERROR, { errors: [data.errors], data });
67
63
  };
68
64
  return handlers;
69
65
  }
@@ -125,9 +121,9 @@ class ThreeDSecure {
125
121
  }
126
122
  if (scenario.outcome.success) {
127
123
  this.reportSuccess(`FatZebra.3DS: 3DS success - ${scenario.description}.`, threeDSecureData);
128
- const extra = util.toObjectWithSnakeCaseKeys(threeDSecureData);
129
124
  if (this.tokenizeOnly)
130
125
  return; // DO NO process purchase if tokenizing only.
126
+ const extra = util.toObjectWithSnakeCaseKeys(threeDSecureData);
131
127
  this.createPurchase(extra);
132
128
  return;
133
129
  }
@@ -182,6 +178,14 @@ class ThreeDSecure {
182
178
  message.data.extra = Object.assign(Object.assign({}, extra), { sli: toFzSli(extra.eci) });
183
179
  this.headlessBridge.contentWindow.postMessage(message, '*');
184
180
  }
181
+ listenDeviceCollectionReady() {
182
+ on(PublicEvent.DEVICE_PROFILE_READY_THREE_D_SECURE_EVENT, () => this.checkEnrollment({
183
+ paymentIntent: this.paymentIntent,
184
+ cardToken: this.cardToken,
185
+ merchantUsername: this.merchantUsername,
186
+ cybersourceReferenceId: this.cybersourceReferenceId,
187
+ }));
188
+ }
185
189
  setLoading(loading = true) {
186
190
  var _a;
187
191
  if ((_a = this === null || this === void 0 ? void 0 : this.iframe) === null || _a === void 0 ? void 0 : _a.contentWindow) {
@@ -12,8 +12,8 @@ export default class DeviceDataCollection {
12
12
  private static readonly INPUT_ID;
13
13
  createIframe(): void;
14
14
  static listenDataCollectionResponse(environment: Environment): void;
15
- private static hasEmittedProfileReady;
16
15
  private static handleDataCollectionResponse;
16
+ private static handleCollectionResponse;
17
17
  static collectDeviceData(): DeviceDataType;
18
18
  static setIframeUrl(url: string, jwt: string): void;
19
19
  static getForm(): HTMLFormElement | null;
@@ -1,6 +1,13 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
1
7
  import { PublicEvent } from "../../shared/types";
2
8
  import { emit } from "../../shared/event-manager";
3
9
  import env from "../../shared/env";
10
+ import { logMethod } from "../../logging/logMethod";
4
11
  class DeviceDataCollection {
5
12
  // Create elements if they don't already exist
6
13
  createIframe() {
@@ -43,17 +50,17 @@ class DeviceDataCollection {
43
50
  // https://developer.cybersource.com/docs/cybs/en-us/payer-authentication/developer/all/so/payer-auth/pa2-ccdc-ddc-intro.html#reference_qmk_jrl_xpb
44
51
  if (event.origin !== env[environment].cybersourceUrl)
45
52
  return;
46
- if (this.hasEmittedProfileReady)
47
- return;
53
+ this.handleCollectionResponse(event);
54
+ }
55
+ static handleCollectionResponse(event) {
48
56
  const response = JSON.parse(event.data);
49
57
  if (response["MessageType"] == "profile.completed") {
50
58
  emit(PublicEvent.DEVICE_PROFILE_READY_THREE_D_SECURE_EVENT, { message: null, data: null });
51
59
  }
52
- // Still proceed, even if status is false (as per recommendations from cybersource support team.
53
- if (response["Status"] === false) {
60
+ else if (response["Status"] == false) {
61
+ // Still proceed, even if status is false (as per recommendations from cybersource support team.
54
62
  emit(PublicEvent.DEVICE_PROFILE_READY_THREE_D_SECURE_EVENT, { message: null, data: null });
55
63
  }
56
- this.hasEmittedProfileReady = true;
57
64
  }
58
65
  static collectDeviceData() {
59
66
  var _a, _b, _c, _d;
@@ -115,5 +122,12 @@ DeviceDataCollection.IFRAME_ID = "cardinal_collection_iframe";
115
122
  DeviceDataCollection.IFRAME_NAME = "collectionIframe";
116
123
  DeviceDataCollection.FORM_ID = "cardinal_collection_form";
117
124
  DeviceDataCollection.INPUT_ID = "cardinal_collection_form_input";
118
- DeviceDataCollection.hasEmittedProfileReady = false;
119
125
  export default DeviceDataCollection;
126
+ __decorate([
127
+ logMethod({
128
+ mapArgs: (args) => {
129
+ const params = args[0]; // grab the first argument.
130
+ return JSON.parse(params.data);
131
+ },
132
+ })
133
+ ], DeviceDataCollection, "handleCollectionResponse", null);
@@ -66,11 +66,6 @@ class ThreeDSecureChallengeWindow {
66
66
  });
67
67
  content.appendChild(frameWrap);
68
68
  overlay.appendChild(content);
69
- // Backdrop click to close (optional)
70
- overlay.addEventListener("click", (e) => {
71
- if (e.target === overlay)
72
- ThreeDSecureChallengeWindow.hide();
73
- });
74
69
  document.body.appendChild(overlay);
75
70
  return { overlay, content, frameWrap };
76
71
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fat-zebra/sdk",
3
- "version": "2.0.1-beta.0",
3
+ "version": "2.0.1-beta.10",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -63,7 +63,7 @@
63
63
  "ajv": "^8.17.1",
64
64
  "ajv-formats": "^3.0.1",
65
65
  "ajv-keywords": "^5.1.0",
66
- "axios": "1.15.0",
66
+ "axios": "1.16.0",
67
67
  "custom-event-polyfill": "^1.0.7",
68
68
  "glob": "^13.0.6",
69
69
  "ts-polyfill": "^3.8.2",