-
Notifications
You must be signed in to change notification settings - Fork 576
/
Copy pathutils.js
222 lines (210 loc) · 6.5 KB
/
utils.js
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
/* @flow */
import { request, memoize } from "@krakenjs/belter/src";
import {
buildDPoPHeaders,
getSDKHost,
getClientID,
getMerchantID as getSDKMerchantID,
} from "@paypal/sdk-client/src";
import { FUNDING } from "@paypal/sdk-constants/src";
import type {
ButtonVariables,
CreateAccessToken,
CreateOrder,
GetCallbackProps,
HostedButtonDetailsParams,
OnApprove,
RenderForm,
} from "./types";
const entryPoint = "SDK";
const baseUrl = `https://${getSDKHost()}`;
const apiUrl = baseUrl.replace("www", "api");
const getHeaders = (accessToken?: string) => ({
...(accessToken && { Authorization: `Bearer ${accessToken}` }),
"Content-Type": "application/json",
"PayPal-Entry-Point": entryPoint,
});
export const getMerchantID = (): string | void => {
// The SDK supports mutiple merchant IDs, but hosted buttons only
// have one merchant id as a query parameter to the SDK script.
// https://github.com/paypal/paypal-sdk-client/blob/c58e35f8f7adbab76523eb25b9c10543449d2d29/src/script.js#L144
const merchantIds = getSDKMerchantID();
if (merchantIds.length > 1) {
throw new Error("Multiple merchant-ids are not supported.");
}
return merchantIds[0];
};
export const createAccessToken: CreateAccessToken = memoize<CreateAccessToken>(
async ({ clientId, enableDPoP }) => {
const url = `${apiUrl}/v1/oauth2/token`;
const method = "POST";
const DPoPHeaders = enableDPoP
? await buildDPoPHeaders({
uri: url,
method,
})
: {};
const response = await request({
url,
method,
body: "grant_type=client_credentials",
// $FlowIssue optional properties are not compatible with [key: string]: string
headers: {
Authorization: `Basic ${btoa(clientId)}`,
"Content-Type": "application/json",
// $FlowIssue exponential-spread
...DPoPHeaders,
},
});
// $FlowIssue request returns ZalgoPromise
const { access_token: accessToken, nonce } = response.body;
return {
accessToken,
nonce,
};
}
);
const getButtonVariable = (variables: ButtonVariables, key: string): string =>
variables?.find((variable) => variable.name === key)?.value ?? "";
export const getHostedButtonDetails: HostedButtonDetailsParams = async ({
hostedButtonId,
}) => {
const response = await request({
url: `${baseUrl}/ncp/api/form-fields/${hostedButtonId}`,
headers: getHeaders(),
});
// $FlowIssue request returns ZalgoPromise
const { body } = response;
const variables = body.button_details.link_variables;
return {
style: {
layout: getButtonVariable(variables, "layout"),
shape: getButtonVariable(variables, "shape"),
color: getButtonVariable(variables, "color"),
label: getButtonVariable(variables, "button_text"),
},
html: body.html,
htmlScript: body.html_script,
};
};
/**
* Attaches form fields (html) to the given selector, and
* initializes window.__pp_form_fields (htmlScript).
*/
export const renderForm: RenderForm = ({
hostedButtonId,
html,
htmlScript,
selector,
}) => {
const elm =
typeof selector === "string" ? document.querySelector(selector) : selector;
if (elm) {
elm.innerHTML = html + htmlScript;
const newScriptEl = document.createElement("script");
const oldScriptEl = elm.querySelector("script");
newScriptEl.innerHTML = oldScriptEl?.innerHTML ?? "";
oldScriptEl?.parentNode?.replaceChild(newScriptEl, oldScriptEl);
}
return {
// disable the button, listen for input changes,
// and enable the button when the form is valid
// using actions.disable() and actions.enable()
onInit: window[`__pp_form_fields_${hostedButtonId}`]?.onInit,
// render form errors, if present
onClick: window[`__pp_form_fields_${hostedButtonId}`]?.onClick,
};
};
export const buildHostedButtonCreateOrder = ({
enableDPoP,
hostedButtonId,
merchantId,
}: GetCallbackProps): CreateOrder => {
return async (data) => {
const userInputs =
window[`__pp_form_fields_${hostedButtonId}`]?.getUserInputs?.() || {};
const onError = window[`__pp_form_fields_${hostedButtonId}`]?.onError;
const { accessToken, nonce } = await createAccessToken({
clientId: getClientID(),
enableDPoP,
});
try {
const url = `${apiUrl}/v1/checkout/links/${hostedButtonId}/create-context`;
const method = "POST";
const DPoPHeaders = enableDPoP
? await buildDPoPHeaders({
uri: url,
method,
accessToken,
nonce,
})
: {};
const response = await request({
url,
// $FlowIssue optional properties are not compatible with [key: string]: string
headers: {
...getHeaders(accessToken),
// $FlowIssue exponential-spread
...DPoPHeaders,
},
method,
body: JSON.stringify({
entry_point: entryPoint,
funding_source: data.paymentSource.toUpperCase(),
merchant_id: merchantId,
...userInputs,
}),
});
// $FlowIssue request returns ZalgoPromise
const { body } = response;
return body.context_id || onError(body.name);
} catch (e) {
return onError("REQUEST_FAILED");
}
};
};
export const buildHostedButtonOnApprove = ({
enableDPoP,
hostedButtonId,
merchantId,
}: GetCallbackProps): OnApprove => {
return async (data) => {
const { accessToken, nonce } = await createAccessToken({
clientId: getClientID(),
enableDPoP,
});
const url = `${apiUrl}/v1/checkout/links/${hostedButtonId}/pay`;
const method = "POST";
const DPoPHeaders = enableDPoP
? await buildDPoPHeaders({
uri: url,
method,
accessToken,
nonce,
})
: {};
return request({
url,
// $FlowIssue optional properties are not compatible with [key: string]: string
headers: {
...getHeaders(accessToken),
// $FlowIssue exponential-spread
...DPoPHeaders,
},
method,
body: JSON.stringify({
entry_point: entryPoint,
merchant_id: merchantId,
context_id: data.orderID,
}),
}).then((response) => {
// The "Debit or Credit Card" button does not open a popup
// so we need to redirect to the thank you page for buyers who complete
// a checkout via "Debit or Credit Card".
if (data.paymentSource === FUNDING.CARD) {
window.location = `${baseUrl}/ncp/payment/${hostedButtonId}/${data.orderID}`;
}
return response;
});
};
};