-
Notifications
You must be signed in to change notification settings - Fork 576
/
Copy pathcomponent.jsx
265 lines (240 loc) · 7.89 KB
/
component.jsx
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
/* @flow */
/* eslint-disable eslint-comments/disable-enable-pair */
/* eslint-disable no-restricted-globals, promise/no-native */
import { type LoggerType } from "@krakenjs/beaver-logger/src";
import { type ZoidComponent } from "@krakenjs/zoid/src";
import { ZalgoPromise } from "@krakenjs/zalgo-promise/src";
import { FPTI_KEY, CURRENCY } from "@paypal/sdk-constants/src";
import { PAYMENT_3DS_VERIFICATION } from "../constants/api";
import { ValidationError } from "../lib";
import type {
requestData,
GqlResponse,
MerchantPayloadData,
SdkConfig,
ThreeDSResponse,
TDSProps,
} from "./types";
import { getThreeDS } from "./utils";
import type { GraphQLClient, RestClient } from "./api";
const parseSdkConfig = ({ sdkConfig, logger }): SdkConfig => {
if (!sdkConfig.authenticationToken) {
throw new ValidationError(
`script data attribute sdk-client-token is required but was not passed`
);
}
logger.info("three domain secure v2 invoked").track({
[FPTI_KEY.TRANSITION]: "three_DS_auth_v2",
});
return sdkConfig;
};
const parseMerchantPayload = ({
merchantPayload,
}: {|
merchantPayload: MerchantPayloadData,
|}): requestData => {
const { threeDSRequested, amount, currency, nonce, transactionContext } =
merchantPayload;
return {
intent: "THREE_DS_VERIFICATION",
payment_source: {
card: {
single_use_token: nonce,
verification_method: threeDSRequested
? "SCA_ALWAYS"
: "SCA_WHEN_REQUIRED",
},
},
amount: {
currency_code: currency,
value: amount,
},
...transactionContext,
};
};
export interface ThreeDomainSecureComponentInterface {
isEligible(payload: MerchantPayloadData): Promise<boolean>;
show(): Promise<ThreeDSResponse>;
}
export class ThreeDomainSecureComponent {
fastlaneNonce: string;
logger: LoggerType;
restClient: RestClient;
graphQLClient: GraphQLClient;
sdkConfig: SdkConfig;
authenticationURL: string;
threeDSIframe: ZoidComponent<TDSProps>;
constructor({
logger,
restClient,
graphQLClient,
sdkConfig,
}: {|
logger: LoggerType,
restClient: RestClient,
graphQLClient: GraphQLClient,
sdkConfig: SdkConfig,
|}) {
this.logger = logger;
this.restClient = restClient;
this.graphQLClient = graphQLClient;
this.sdkConfig = parseSdkConfig({ sdkConfig, logger });
}
async isEligible(merchantPayload: MerchantPayloadData): Promise<boolean> {
this.validateMerchantPayload(merchantPayload);
const data = parseMerchantPayload({ merchantPayload });
this.fastlaneNonce = merchantPayload.nonce;
try {
// $FlowFixMe
const { status, links } = await this.restClient.request({
method: "POST",
baseURL: `${this.sdkConfig.paypalApiDomain}/${PAYMENT_3DS_VERIFICATION}`,
data,
});
let responseStatus = false;
if (status === "PAYER_ACTION_REQUIRED") {
this.authenticationURL = links.find(
(link) => link.rel === "payer-action"
).href;
responseStatus = true;
this.threeDSIframe = getThreeDS();
}
return responseStatus;
} catch (error) {
this.logger.warn(error);
throw error;
}
}
// eslint-disable-next-line require-await
async show(): Promise<ThreeDSResponse> {
if (!this.threeDSIframe) {
return Promise.reject(
new ValidationError(`Ineligible for three domain secure`)
);
}
// eslint-disable-next-line compat/compat
return new Promise((resolve, reject) => {
let authenticationState,
liabilityShift = "false";
const cancelThreeDS = () => {
return ZalgoPromise.try(() => {
this.logger.warn("3DS Cancelled");
}).then(() => {
// eslint-disable-next-line no-use-before-define
instance.close();
resolve({
authenticationState: "cancelled",
liabilityShift: "false",
nonce: this.fastlaneNonce,
});
});
};
const instance = this.threeDSIframe({
payerActionUrl: this.authenticationURL,
onSuccess: async (res) => {
const { reference_id, liability_shift, success } = res;
let enrichedNonce;
// Helios returns a boolen parameter: "success"
// It will be true for all cases where liability is shifted to merchant
// and false for downstream failures and errors
authenticationState = success ? "succeeded" : "errored";
liabilityShift = liability_shift ? liability_shift : "false";
// call BT mutation to update fastlaneNonce with 3ds data
// reference_id will be available for all usecases(success/failure)
if (reference_id) {
const gqlResponse = await this.updateNonceWith3dsData(reference_id);
const { data, errors } = gqlResponse;
if (data) {
enrichedNonce =
data.updateTokenizedCreditCardWithExternalThreeDSecure
.paymentMethod.id;
} else if (errors && errors[0]) {
// $FlowFixMe incompatible type payload
this.logger.warn(JSON.stringify(errors[0]));
}
}
// Resolve the parent promise with enriched nonce if available
// else, return the original nonce that the merchant sent
resolve({
authenticationState,
liabilityShift,
nonce: enrichedNonce || this.fastlaneNonce,
});
},
onCancel: cancelThreeDS,
onError: (err) => {
instance.close();
reject(new Error(err));
},
});
// Render the iframe
instance.render("body").catch(() => {
instance.close();
});
});
}
validateMerchantPayload(merchantPayload: MerchantPayloadData): void {
// TODO we have a ticket to standardize client-side validations
// eslint-disable-next-line flowtype/no-weak-types
const isRequired = (value: any) => Boolean(value);
// eslint-disable-next-line flowtype/no-weak-types
const isString = (value: any) => typeof value === "string";
const validations = {
amount: {
test: [isString, isRequired],
message: (value) =>
`[amount] is required and must be a string. received: ${value}`,
},
currency: {
test: [(value) => value in CURRENCY, isRequired],
message: (value) =>
`[currency] is required and must be a valid currency. received: ${value}`,
},
nonce: {
test: [isString, isRequired],
message: (value) =>
`[nonce] is required and must be a string. received: ${value}`,
},
};
const errors = [];
// eslint-disable-next-line flowtype/no-weak-types
Object.entries(validations).forEach(([key, value]: [string, any]) => {
const paramValue = merchantPayload[key];
if (!value.test?.every((validation) => validation(paramValue))) {
errors.push(value.message(paramValue));
}
});
if (errors.length) {
const joinedErrors = errors.join("\n");
this.logger.warn(joinedErrors);
throw new ValidationError(joinedErrors);
}
}
updateNonceWith3dsData(threeDSRefID: string): Promise<GqlResponse> {
// $FlowFixMe Zalgopromise not recognized
return this.graphQLClient.request({
headers: {
"Braintree-Version": "2023-09-28",
},
data: {
query: `
mutation UpdateTokenizedCreditCardWithExternalThreeDSecure($input: UpdateTokenizedCreditCardWithExternalThreeDSecureInput!) {
updateTokenizedCreditCardWithExternalThreeDSecure(input: $input) {
paymentMethod {
id
}
}
}
`,
variables: {
input: {
paymentMethodId: this.fastlaneNonce,
externalThreeDSecureMetadata: {
externalAuthenticationId: threeDSRefID,
},
},
},
},
});
}
}