Last active
August 12, 2018 20:47
-
-
Save darasus/ee6ba388c2d4814f3829ca44629ffe83 to your computer and use it in GitHub Desktop.
Handle Stripe charge with source using express.js
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_SECRET = 'STRIPE_SECRET'; | |
// const keyPublishable = 'pk_test_19ahJzPH2xE2Dd9zhqv6R6fR'; | |
const STRIPE_SECRET = 'sk_test_ZqMsK6wX4raLqGcICamzZiP9'; | |
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const path = require('path'); | |
const stripe = require('stripe')(STRIPE_SECRET); | |
const app = express(); | |
app.use(bodyParser.json()); | |
app.use(bodyParser.urlencoded({ extended: true })); | |
app.use(express.static(path.join(__dirname, 'www'))); | |
app.use((req, res, next) => { | |
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000'); | |
res.setHeader('Access-Control-Allow-Methods', 'POST'); | |
res.setHeader( | |
'Access-Control-Allow-Headers', | |
'X-Requested-With,content-type', | |
); | |
next(); | |
}); | |
const makeCharge = (res, sourceId, amount, currency) => | |
stripe.charges.create( | |
{ | |
amount, | |
currency, | |
source: sourceId, | |
}, | |
(err, charge) => { | |
if (err !== null) { | |
res.status(500).send({ error: 'Purchase Failed. Please try again.' }); | |
} else { | |
res.send(charge); | |
} | |
}, | |
); | |
const retrieveSource = (sourceId, callback) => | |
stripe.sources.retrieve(sourceId, (err, source) => callback(source)); | |
app.post('/charge', (req, res) => { | |
const { sourceId } = req.body; | |
retrieveSource(sourceId, ({ amount, currency }) => { | |
makeCharge(res, sourceId, amount, currency); | |
}); | |
}); | |
app.listen(3000, (req, res) => { | |
console.log( | |
'Server is running. Point your browser to: http://localhost:3000', | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment