-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
102 lines (87 loc) · 2.87 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cors = require('cors')({ origin: true });
const app = express();
// TODO: Remember to set token using >> firebase functions:config:set stripe.token="SECRET_STRIPE_TOKEN_HERE"
const stripe = require('stripe')(functions.config().stripe.token);
function stripeCharge(req, res) {
const body = JSON.parse(req.body);
const token = body.token.id;
const amount = body.charge.amount;
const currency = body.charge.currency;
console.log(`tokenid ${token}`)
console.log(`amount ${amount}`)
console.log(`currency ${currency}`)
// Charge card
stripe.charges.create({
amount,
currency,
description: 'Firebase Example',
source: token,
}).then(charge => {
send(res, 200, {
message: 'Success',
charge,
});
}).catch(error => {
console.error(error);
send(res, 500, {
error: err.message,
});
});
}
function send(res, code, body) {
res.send({
statusCode: code,
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify(body),
});
}
app.use(cors);
app.post('/', (req, res) => {
// Catch any unexpected errors to prevent crashing
try {
stripeCharge(req, res);
} catch (error) {
console.error(error);
send(res, 500, {
error: `The server received an unexpected error. Please try again and contact the site admin if the error persists.`,
});
}
});
exports.stripeCharge = functions.https.onRequest(app);
exports.stripeChargeCallable = functions.https.onCall((data, context) => {
const token = data.token_id;
const amount = data.amount;
const currency = data.currency;
const description = data.description;
// console.log(`tokenId ${token}`)
// console.log(`amount ${amount}`)
// console.log(`currency ${currency}`)
// Charge card
return stripe.charges.create({
'amount': amount,
'currency': currency,
'description': description,
'source': token,
}).then(charge => {
console.log(charge)
return {'charge': JSON.stringify(charge)};
}).catch(error => {
console.error(error);
throw new functions.https.HttpsError('aborted', error.message, error.stringify);
});
});
exports.retrieveStripeToken = functions.https.onCall((data, context) => {
const tokenId = data.token_id;
// console.log(`tokenId ${tokenId}`)
return stripe.tokens.retrieve(tokenId).then(token => {
console.log(token)
return {'token': JSON.stringify(token)};
}).catch(error => {
console.error(error);
throw new functions.https.HttpsError('aborted', error.message, error.stringify);
});
});