-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathpurchase.js
70 lines (57 loc) · 1.44 KB
/
purchase.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
require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const statusCode = 200;
const headers = {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "Content-Type"
};
exports.handler = function(event, context, callback) {
//-- We only care to do anything if this is our POST request.
if(event.httpMethod !== 'POST' || !event.body) {
callback(null, {
statusCode,
headers,
body: ''
});
}
//-- Parse the body contents into an object.
const data = JSON.parse(event.body);
//-- Make sure we have all required data. Otherwise, escape.
if(
!data.token ||
!data.amount ||
!data.idempotency_key
) {
console.error('Required information is missing.');
callback(null, {
statusCode,
headers,
body: JSON.stringify({status: 'missing-information'})
});
return;
}
stripe.charges.create(
{
currency: 'usd',
amount: data.amount,
source: data.token.id,
receipt_email: data.token.email,
description: `charge for a widget`
},
{
idempotency_key: data.idempotency_key
}, (err, charge) => {
if(err !== null) {
console.log(err);
}
let status = (charge === null || charge.status !== 'succeeded')
? 'failed'
: charge.status;
callback(null, {
statusCode,
headers,
body: JSON.stringify({status})
});
}
);
}