-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
88 lines (84 loc) · 2.55 KB
/
index.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
const SquareConnect = require('square-connect');
const defaultClient = SquareConnect.ApiClient.instance;
const crypto = require('crypto');
let oauth2 = defaultClient.authentications['oauth2'];
oauth2.accessToken = process.env.ACCESS_TOKEN;
const transactionsApi = new SquareConnect.TransactionsApi();
const ordersApi = new SquareConnect.OrdersApi();
const locationId = process.env.LOC_ID;
exports.handler = async (event) => {
const eventBody = JSON.parse(event.body);
const order = await ordersApi.createOrder(locationId, {
idempotency_key: crypto.randomBytes(12).toString('hex'),
line_items: [
{
name: "Cookie",
quantity: "1",
base_price_money: {
amount: 100,
currency: "USD"
}
}
]
});
const body = {
idempotency_key: crypto.randomBytes(12).toString('hex'),
amount_money: {
amount: order.order.line_items[0].total_money.amount,
currency: 'USD'
},
order_id: order.order.id,
card_nonce: eventBody.nonce
};
try {
const transaction = await transactionsApi.charge(locationId, body);
console.log(transaction.transaction);
return {
"statusCode": 200,
"body": JSON.stringify(transaction.transaction)
}
} catch (e) {
delete e.response.req.headers;
delete e.response.req._header;
console.log(e);
const errorMessages = (JSON.parse(e.response.text)).errors;
console.log(errorMessages);
switch(errorMessages[0].code) {
case "VERIFY_CVV_FAILURE":
return {
"statusCode": 400,
"body": JSON.stringify({
errorMessage: "Invalid CVV. Please re-enter card information."
})
}
case "VERIFY_AVS_FAILURE":
return {
"statusCode": 400,
"body": JSON.stringify({
errorMessage: "Invalid Postal Code. Please re-enter card information."
})
}
case "INVALID_EXPIRATION":
return {
"statusCode": 400,
"body": JSON.stringify({
errorMessage: "Card declined."
})
}
case "CARD_TOKEN_USED":
return {
"statusCode": 400,
"body": JSON.stringify({
errorMessage: "Card token already used; Please try re-entering card details."
})
}
default:
return {
"statusCode": 400,
"body": JSON.stringify({
errorMessage: "Payment error. Please contact support if issue persists."
})
}
}
}
};