-
Notifications
You must be signed in to change notification settings - Fork 8
/
script.js
234 lines (224 loc) · 9.26 KB
/
script.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
223
224
225
226
227
228
229
230
231
232
233
234
// Helper / Utility functions
let current_customer_id;
let order_id;
let script_to_head = (attributes_object) => {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
for (const name of Object.keys(attributes_object)) {
script.setAttribute(name, attributes_object[name]);
}
document.head.appendChild(script);
script.addEventListener('load', resolve);
script.addEventListener('error', reject);
});
}
let reset_purchase_button = () => {
document.querySelector("#card-form").querySelector("input[type='submit']").removeAttribute("disabled");
document.querySelector("#card-form").querySelector("input[type='submit']").value = "Purchase";
}
const is_user_logged_in = () => {
return new Promise((resolve) => {
customer_id = localStorage.getItem("logged_in_user_id") || "";
resolve();
});
}
const get_client_token = () => {
return new Promise(async (resolve, reject) => {
try {
const response = await fetch("http://localhost:3000/get_client_token", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ "customer_id": current_customer_id }),
});
const client_token = await response.text();
resolve(client_token);
} catch (error) {
reject(error);
}
});
}
let handle_close = (event) => {
event.target.closest(".ms-alert").remove();
}
let handle_click = (event) => {
if (event.target.classList.contains("ms-close")) {
handle_close(event);
}
}
document.addEventListener("click", handle_click);
const paypal_sdk_url = "https://www.paypal.com/sdk/js";
const client_id = "REPLACE_WITH_YOUR_CLIENT_ID";
const currency = "USD";
const intent = "capture";
let display_error_alert = () => {
document.getElementById("alerts").innerHTML = `<div class="ms-alert ms-action2 ms-small"><span class="ms-close"></span><p>An Error Ocurred! (View console for more info)</p> </div>`;
}
let display_success_message = (object) => {
order_details = object.order_details;
paypal_buttons = object.paypal_buttons;
console.log(order_details); //https://developer.paypal.com/docs/api/orders/v2/#orders_capture!c=201&path=create_time&t=response
let intent_object = intent === "authorize" ? "authorizations" : "captures";
//Custom Successful Message
document.getElementById("alerts").innerHTML = `<div class=\'ms-alert ms-action\'>Thank you ` + (order_details?.payer?.name?.given_name || ``) + ` ` + (order_details?.payer?.name?.surname || ``) + ` for your payment of ` + order_details.purchase_units[0].payments[intent_object][0].amount.value + ` ` + order_details.purchase_units[0].payments[intent_object][0].amount.currency_code + `!</div>`;
//Close out the PayPal buttons that were rendered
paypal_buttons.close();
document.getElementById("card-form").classList.add("hide");
}
//PayPal Code
is_user_logged_in()
.then(() => {
return get_client_token();
})
.then((client_token) => {
//https://developer.paypal.com/sdk/js/configuration/#link-queryparameters
return script_to_head({"src": paypal_sdk_url + "?client-id=" + client_id + "&enable-funding=venmo¤cy=" + currency + "&intent=" + intent + "&components=buttons,hosted-fields", "data-client-token": client_token}) //https://developer.paypal.com/sdk/js/configuration/#link-configureandcustomizeyourintegration
})
.then(() => {
//Handle loading spinner
document.getElementById("loading").classList.add("hide");
document.getElementById("content").classList.remove("hide");
let paypal_buttons = paypal.Buttons({ // https://developer.paypal.com/sdk/js/reference
onClick: (data) => { // https://developer.paypal.com/sdk/js/reference/#link-oninitonclick
//Custom JS here
},
style: { //https://developer.paypal.com/sdk/js/reference/#link-style
shape: 'rect',
color: 'gold',
layout: 'vertical',
label: 'paypal'
},
createOrder: function(data, actions) { //https://developer.paypal.com/docs/api/orders/v2/#orders_create
return fetch("http://localhost:3000/create_order", {
method: "post", headers: { "Content-Type": "application/json; charset=utf-8" },
body: JSON.stringify({ "intent": intent })
})
.then((response) => response.json())
.then((order) => { return order.id; });
},
onApprove: function(data, actions) {
order_id = data.orderID;
console.log(data);
return fetch("http://localhost:3000/complete_order", {
method: "post", headers: { "Content-Type": "application/json; charset=utf-8" },
body: JSON.stringify({
"intent": intent,
"order_id": order_id
})
})
.then((response) => response.json())
.then((order_details) => {
display_success_message({"order_details": order_details, "paypal_buttons": paypal_buttons});
})
.catch((error) => {
console.log(error);
display_error_alert()
});
},
onCancel: function (data) {
document.getElementById("alerts").innerHTML = `<div class="ms-alert ms-action2 ms-small"><span class="ms-close"></span><p>Order cancelled!</p> </div>`;
},
onError: function(err) {
console.log(err);
}
});
paypal_buttons.render('#payment_options');
//Hosted Fields
if (paypal.HostedFields.isEligible()) {
// Renders card fields
paypal_hosted_fields = paypal.HostedFields.render({
// Call your server to set up the transaction
createOrder: () => {
return fetch("http://localhost:3000/create_order", {
method: "post", headers: { "Content-Type": "application/json; charset=utf-8" },
body: JSON.stringify({ "intent": intent })
})
.then((response) => response.json())
.then((order) => { order_id = order.id; return order.id; });
},
styles: {
'.valid': {
color: 'green'
},
'.invalid': {
color: 'red'
},
'input': {
'font-size': '16pt',
'color': '#ffffff'
},
},
fields: {
number: {
selector: "#card-number",
placeholder: "4111 1111 1111 1111"
},
cvv: {
selector: "#cvv",
placeholder: "123"
},
expirationDate: {
selector: "#expiration-date",
placeholder: "MM/YY"
}
}
}).then((card_fields) => {
document.querySelector("#card-form").addEventListener("submit", (event) => {
event.preventDefault();
document.querySelector("#card-form").querySelector("input[type='submit']").setAttribute("disabled", "");
document.querySelector("#card-form").querySelector("input[type='submit']").value = "Loading...";
card_fields
.submit(
//Customer Data BEGIN
//This wasn't part of the video guide originally, but I've included it here
//So you can reference how you could send customer data, which may
//be a requirement of your project to pass this info to card issuers
{
// Cardholder's first and last name
cardholderName: "Raúl Uriarte, Jr.",
// Billing Address
billingAddress: {
// Street address, line 1
streetAddress: "123 Springfield Rd",
// Street address, line 2 (Ex: Unit, Apartment, etc.)
extendedAddress: "",
// State
region: "AZ",
// City
locality: "CHANDLER",
// Postal Code
postalCode: "85224",
// Country Code
countryCodeAlpha2: "US",
},
}
//Customer Data END
)
.then(() => {
return fetch("http://localhost:3000/complete_order", {
method: "post", headers: { "Content-Type": "application/json; charset=utf-8" },
body: JSON.stringify({
"intent": intent,
"order_id": order_id,
"email": document.getElementById("email").value
})
})
.then((response) => response.json())
.then((order_details) => {
display_success_message({"order_details": order_details, "paypal_buttons": paypal_buttons});
})
.catch((error) => {
console.log(error);
display_error_alert();
});
})
.catch((err) => {
console.log(err);
reset_purchase_button();
display_error_alert();
});
});
});
}
})
.catch((error) => {
reset_purchase_button();
});