Last active
May 16, 2019 16:05
-
-
Save dmurawsky/606d4464b2cfd0ab3e23325ffa0630da to your computer and use it in GitHub Desktop.
basic next.js server with stripe
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
{ | |
"version": 2, | |
"builds": [ | |
{ "src": "api/*.js", "use": "@now/node" }, | |
{ "src": "package.json", "use": "@now/next" } | |
], | |
"env": { | |
"STRIPE_SECRET_KEY": "@acj_stripe_secret_key" | |
}, | |
"routes": [{ "src": "/blog/(?<name>[^/]+)$", "dest": "/blog?id=$name" }] | |
} |
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 cacheableResponse = require("cacheable-response"); | |
const express = require("express"); | |
const next = require("next"); | |
const bodyParser = require("body-parser"); | |
const keySecret = process.env.STRIPE_SECRET_KEY; | |
const stripe = require("stripe")(keySecret); | |
const port = parseInt(process.env.PORT, 10) || 3000; | |
const dev = process.env.NODE_ENV !== "production"; | |
const app = next({ dev }); | |
const handle = app.getRequestHandler(); | |
const ssrCache = cacheableResponse({ | |
ttl: 1000 * 60 * 60 * 72, | |
get: async ({ req, res, pagePath, queryParams }) => ({ | |
data: await app.renderToHTML(req, res, pagePath, queryParams), | |
}), | |
send: ({ data, res }) => res.send(data), | |
}); | |
app.prepare().then(() => { | |
const server = express(); | |
server.get("/", (req, res) => ssrCache({ req, res, pagePath: "/" })); | |
server.get("/about", (req, res) => | |
ssrCache({ req, res, pagePath: "/about" }), | |
); | |
server.get("/blog/:id", (req, res) => { | |
const queryParams = { id: req.params.id }; | |
const pagePath = "/blog"; | |
return ssrCache({ req, res, pagePath, queryParams }); | |
}); | |
server.get("*", (req, res) => handle(req, res)); | |
server.use(bodyParser.json()); | |
server.post("/donate", (req, res) => { | |
stripe.customers | |
.create({ | |
email: req.body.token.email, | |
card: req.body.token.id, | |
}) | |
.then(customer => | |
stripe.charges.create({ | |
amount: req.body.amount + "00", | |
description: "Donation", | |
currency: "usd", | |
customer: customer.id, | |
}), | |
) | |
.then(() => res.redirect("/thankyou")) | |
.catch(err => { | |
console.log("Error:", err); | |
res.status(500).send({ error: "Purchase Failed" }); | |
}); | |
}); | |
server.listen(port, err => { | |
if (err) throw err; | |
console.log(`> Ready on http://localhost:${port}`); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment