Created
December 29, 2017 22:24
-
-
Save adnan-i/3d8c3b4321d493f3d7a23e9cf694a568 to your computer and use it in GitHub Desktop.
Node service for stripe payments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Stripe = require('stripe'); | |
const Promise = require('bluebird'); | |
class StripeService { | |
constructor(server) { | |
this.server = server; | |
this.logger = server.plugins.core.LoggerService.tagged('StripeService'); | |
const secretKey = this.server.app.config.get('/payments/stripe/secretKey'); | |
if (!secretKey) { | |
throw new Error('Unable to find stripe secretKey'); | |
} | |
this.stripe = Stripe(secretKey); | |
} | |
static init(...args) { | |
if (this.instance) return this.instance; | |
this.instance = new this(...args); | |
return this.instance; | |
} | |
_getMetadata(opts){ | |
if(!opts || !opts.customer){ | |
this.logger.warn('Unable to resolve metadata. Missing opts.customer'); | |
} | |
return { | |
customerId: opts.customer.id, | |
fullName: opts.customer.fullName | |
}; | |
} | |
createStripeCustomer(token) { | |
return Promise.resolve() | |
.then(() => { | |
return this.stripe.customers.create({ | |
email: token.email, | |
source: token.id | |
}); | |
}) | |
.catch((err) => { | |
this.logger.error(err); | |
throw err; | |
}); | |
} | |
charge(token, opts) { | |
return Promise.resolve() | |
.then(() => { | |
return this.stripe.charges.create({ | |
amount: opts.amount, | |
description: opts.description, | |
metadata: this._getMetadata(opts), | |
currency: 'usd', | |
customer: opts.user.stripeCustomerId | |
}); | |
}) | |
.catch((err) => { | |
this.logger.error(err); | |
throw err; | |
}); | |
} | |
} | |
module.exports = StripeService; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment