-
Notifications
You must be signed in to change notification settings - Fork 560
/
rest.js
151 lines (114 loc) · 4.77 KB
/
rest.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
/* @flow */
import { getLogger, getPayPalDomain, getIntent, getCurrency, getPartnerAttributionID, isPayPalDomain } from 'paypal-braintree-web-client/src';
import { ZalgoPromise } from 'zalgo-promise/src';
import { on, send } from 'post-robot/src';
import { getAncestor, isSameDomain } from 'cross-domain-utils/src';
import { memoize, request, base64encode } from 'belter/src';
import { FPTI_KEY, SDK_QUERY_KEYS } from 'paypal-sdk-constants/src';
import { getOrderAPIUrl, getAuthAPIUrl } from '../config';
import { FPTI_STATE, FPTI_CONTEXT_TYPE, FPTI_TRANSITION } from '../constants';
type ProxyRest = {
[string] : (...args : $ReadOnlyArray<mixed>) => ZalgoPromise<*>
};
let proxyRest : ProxyRest = {};
export type OrderCreateRequest = {|
intent? : 'CAPTURE' | 'AUTHORIZE',
purchase_units : $ReadOnlyArray<{
amount : {
currency_code : string,
value : string
}
}>
|};
export type OrderCaptureResponse = {||};
export type OrderGetResponse = {||};
export type OrderAuthorizeResponse = {||};
export const createAccessToken = memoize((clientID : string) : ZalgoPromise<string> => {
getLogger().info(`rest_api_create_access_token`);
if (proxyRest.createAccessToken && !proxyRest.createAccessToken.source.closed) {
return proxyRest.createAccessToken(clientID);
}
const basicAuth : string = base64encode(`${ clientID }:`);
return request({
method: `post`,
url: getAuthAPIUrl(),
headers: {
Authorization: `Basic ${ basicAuth }`
},
data: {
grant_type: `client_credentials`
}
}).then(({ body }) => {
if (body && body.error === 'invalid_client') {
throw new Error(`Auth Api invalid client id: ${ clientID }:\n\n${ JSON.stringify(body, null, 4) }`);
}
if (!body || !body.access_token) {
throw new Error(`Auth Api response error:\n\n${ JSON.stringify(body, null, 4) }`);
}
return body.access_token;
});
}, { time: 10 * 60 * 1000 });
function logOrderResponse(orderID) {
getLogger().track({
[ FPTI_KEY.STATE ]: FPTI_STATE.BUTTON,
[ FPTI_KEY.TRANSITION ]: FPTI_TRANSITION.CREATE_ORDER,
[ FPTI_KEY.CONTEXT_TYPE ]: FPTI_CONTEXT_TYPE.ORDER_ID,
[ FPTI_KEY.TOKEN ]: orderID,
[ FPTI_KEY.CONTEXT_ID ]: orderID
});
}
export function createOrder(clientID : string, order : OrderCreateRequest) : ZalgoPromise<string> {
getLogger().info(`rest_api_create_order_token`);
if (!clientID) {
throw new Error(`Client ID not passed`);
}
if (proxyRest.createOrder && !proxyRest.createOrder.source.closed) {
return proxyRest.createOrder(clientID, order);
}
if (!order) {
throw new Error(`Expected order details to be passed`);
}
const currency = window.xprops ? window.xprops.currency : getCurrency();
const intent = window.xprops ? window.xprops.intent : getIntent();
order = { ...order };
if (order.intent && order.intent !== intent) {
throw new Error(`Unexpected intent: ${ order.intent } passed to order.create. Please ensure you are passing /sdk/js?${ SDK_QUERY_KEYS.ORDER_INTENT }=${ order.intent } in the paypal script tag.`);
}
// $FlowFixMe
order = { ...order, intent: intent.toUpperCase() };
order.purchase_units = order.purchase_units.map(unit => {
if (unit.amount.currency_code && unit.amount.currency_code !== currency) {
throw new Error(`Unexpected currency: ${ unit.amount.currency_code } passed to order.create. Please ensure you are passing /sdk/js?${ SDK_QUERY_KEYS.ORDER_CURRENCY }=${ unit.amount.currency_code } in the paypal script tag.`);
}
return { ...unit, amount: { ...unit.amount, currency_code: currency } };
});
return createAccessToken(clientID).then((accessToken) : ZalgoPromise<Object> => {
const headers : Object = {
'Authorization': `Bearer ${ accessToken }`,
'PayPal-Partner-Attribution-Id': getPartnerAttributionID()
};
return request({
method: `post`,
url: getOrderAPIUrl(),
headers,
json: order
});
}).then(({ body }) : string => {
logOrderResponse(body.id);
if (body && body.id) {
return body.id;
}
throw new Error(`Order Api response error:\n\n${ JSON.stringify(body, null, 4) }`);
});
}
const PROXY_REST = `proxy_rest`;
const parentWin = getAncestor();
on(PROXY_REST, { domain: getPayPalDomain() }, ({ data }) => {
proxyRest = data;
});
if (parentWin && isPayPalDomain() && !isSameDomain(parentWin)) {
send(parentWin, PROXY_REST, { createAccessToken, createOrder })
.catch(() => {
// pass
});
}