· 8 years ago · Jan 05, 2018, 12:34 AM
1const Stripe = require('stripe');
2const Promise = require('bluebird');
3
4class StripeService {
5
6 constructor(server) {
7 this.server = server;
8 this.logger = server.plugins.core.LoggerService.tagged('StripeService');
9 const secretKey = this.server.app.config.get('/payments/stripe/secretKey');
10 if (!secretKey) {
11 throw new Error('Unable to find stripe secretKey');
12 }
13 this.stripe = Stripe(secretKey);
14 }
15
16 static init(...args) {
17 if (this.instance) return this.instance;
18 this.instance = new this(...args);
19 return this.instance;
20 }
21
22 _getMetadata(opts){
23 if(!opts || !opts.customer){
24 this.logger.warn('Unable to resolve metadata. Missing opts.customer');
25 }
26
27 return {
28 customerId: opts.customer.id,
29 fullName: opts.customer.fullName
30 };
31 }
32
33 createStripeCustomer(token) {
34 return Promise.resolve()
35 .then(() => {
36 return this.stripe.customers.create({
37 email: token.email,
38 source: token.id
39 });
40 })
41 .catch((err) => {
42 this.logger.error(err);
43 throw err;
44 });
45 }
46
47 charge(token, opts) {
48 return Promise.resolve()
49 .then(() => {
50 return this.stripe.charges.create({
51 amount: opts.amount,
52 description: opts.description,
53 metadata: this._getMetadata(opts),
54 currency: 'usd',
55 customer: opts.user.stripeCustomerId
56 });
57 })
58 .catch((err) => {
59 this.logger.error(err);
60 throw err;
61 });
62 }
63
64}
65
66module.exports = StripeService;