Last active
June 16, 2019 20:25
-
-
Save reichert621/734cd7c4f0f52d8ae1c1d75dc1ed4139 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
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); | |
const app = express(); | |
app.use(bodyParser.json()); | |
app.use(bodyParser.urlencoded({ extended: true })); | |
const createOrder = (skuId, { email, name, address }) => { | |
return stripe.orders.create({ | |
currency: 'usd', | |
email, | |
items: [ | |
{ | |
type: 'sku', | |
parent: skuId, | |
quantity: 1 | |
} | |
], | |
shipping: { | |
name, | |
address | |
} | |
}); | |
}; | |
app.post('/api/orders', (req, res) => { | |
const { body } = req; | |
const { skuId, email, name, address } = body; | |
return createOrder(skuId, { email, name, address }) | |
.then(order => { | |
res.status(200).json({ order }); | |
}) | |
.catch(error => { | |
res.status(500).json({ error }); | |
}); | |
}); | |
const payForOrder = (orderId, token) => { | |
return stripe.orders.pay(orderId, { | |
source: token | |
}); | |
}; | |
app.post('/api/orders/:id/pay', (req, res) => { | |
const { body, params } = req; | |
const { id: orderId } = params; | |
const { token } = body; | |
return payForOrder(orderId, token) | |
.then(order => { | |
res.status(200).json({ order }); | |
}) | |
.catch(error => { | |
res.status(500).json({ error }); | |
}); | |
}); | |
const port = process.env.PORT || 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