Last active
July 1, 2019 02:29
-
-
Save reichert621/02a223dc7f29eb339d6a01722f174e7b to your computer and use it in GitHub Desktop.
This file contains 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
// Load environment variables from our `.env` file | |
require('dotenv').config(); | |
const path = require('path'); | |
const express = require('express'); | |
// Make sure your STRIPE_SECRET_KEY exists as an environment variable! | |
// This should look something like `sk_test_xxxxxxxxxxxxxxxxxxxxxxxxx` | |
// and can be found at https://dashboard.stripe.com/test/apikeys | |
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); | |
// We'll use the Express framework to set up our server and API | |
const app = express(); | |
// Serve static assets from our `/client/build` directory (which will | |
// make our root path default to rendering `/client/build/index.html`) | |
app.use(express.static(path.join(__dirname, '../client/build'))); | |
// The express.json() middleware parses request bodies into JSON | |
app.use(express.json()); | |
// A simple function to create a charge using Stripe | |
const createCharge = token => { | |
return stripe.charges.create({ | |
source: token, | |
amount: 1999, // $19.99 | |
currency: 'usd', | |
description: 'Test charge' | |
}); | |
}; | |
// Set up our API endpoint for creating charges with Stripe | |
app.post('/api/charges', (req, res) => { | |
const { body } = req; | |
// Use the source token generated by Elements, or default to one | |
// of Stripe's test tokens (see https://stripe.com/docs/testing) | |
const { token = 'tok_visa' } = body; | |
return createCharge(token) | |
.then(charge => { | |
res.status(200).json({ charge }); | |
}) | |
.catch(error => { | |
res.status(500).json({ error }); | |
}); | |
}); | |
const port = process.env.PORT || 3000; | |
// Start our server on the given port (defaults to 3000) | |
app.listen(port, () => { | |
console.log(`🚀 Server listening on port ${port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment