-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
74 lines (67 loc) · 2.61 KB
/
app.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
window.paypal.Buttons({
style: {
shape: "rect",
layout: "vertical",
color: "gold",
label: "paypal",
},
async createOrder() {
try {
const response = await fetch("/api/orders", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
cart: [
{
id: "YOUR_PRODUCT_ID",
quantity: "total",
},
],
}),
});
const orderData = await response.json();
if (orderData.id) {
return orderData.id;
}
const errorDetail = orderData?.details?.[0];
const errorMessage = errorDetail
? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
: JSON.stringify(orderData);
throw new Error(errorMessage);
} catch (error) {
console.error(error);
}
},
async onApprove(data, actions) {
try {
const response = await fetch(`/api/orders/${data.orderID}/capture`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const orderData = await response.json();
const errorDetail = orderData?.details?.[0];
if (errorDetail?.issue === "INSTRUMENT_DECLINED") {
return actions.restart();
} else if (errorDetail) {
throw new Error(`${errorDetail.description} (${orderData.debug_id})`);
} else if (!orderData.purchase_units) {
throw new Error(JSON.stringify(orderData));
} else {
const transaction = orderData?.purchase_units?.[0]?.payments?.captures?.[0] ||
orderData?.purchase_units?.[0]?.payments?.authorizations?.[0];
document.getElementById('result-message').innerHTML =
`Transaction ${transaction.status}: ${transaction.id}<br>
<br>See console for all available details`;
console.log("Capture result", orderData, JSON.stringify(orderData, null, 2));
}
} catch (error) {
console.error(error);
document.getElementById('result-message').innerHTML =
`Sorry, your transaction could not be processed...<br><br>${error}`;
}
}
}).render("#paypal-button-container");