lmari’s blog

Data analytics, machine learning & front end development

Node.js & Stripe - Ebook Seller

Ebook seller

f:id:lmari:20190712143408j:plain

Node.js & Stripe

https://github.com/bradtraversy/ebookseller

npm init

npm install --save express stripe express-handlebars body-parser

npm install -g nodemon

In package.json change line 7 to "start:": "node app.js"

 

1. Setup Image files

Create public > img

  • Copy book.png and marketplace.png into img folder

2. Create Frontend

At root, create app.js

const express = require('express');
const keys = require('./config/keys');
const stripe = require ('stripe')(keys.stripeSecretKey);
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');

const app = express();

// Handlebars Middleware
app.engine('handlebars', exphbs({defaultLayout:'main'}));
app.set('view engine', 'handlebars');

// Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

// Set Static Folder
app.use(express.static(`${__dirname}/public`));

// Index Route
app.get('/', (req, res) => {
res.render('index', {
stripePublishableKey: keys.stripePublishableKey
});
});

// Charge Route
app.post('/charge', (req, res) => {
const amount = 2500;

stripe.customers.create({
email: req.body.stripeEmail,
source: req.body.stripeToken
})
.then(customer => stripe.charges.create({
amount,
description:'Web Development Ebook',
currency:'usd',
customer:customer.id
}))
.then(charge => res.render('success'));
});


const port = process.env.PORT || 5000;

app.listen(port, () => {
console.log(`Server started on port ${port}`);
});

Create views

f:id:lmari:20190517235602j:plain

In views > create index.handlebars

<section class="py-2">
<div class="row">
<div class="col-md-6 text-center">
<h1 class="display-3 mt-3 pt-5">
Web Development Ebook
</h1><p class="lead">learn web development front to back</p>
<form action="/charge" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{stripePublishableKey}}"
data-amount="2500"
data-name="Web Development Ebook"
data-description="Ebook written by ABC"
data-image="/img/marketplace.png"
data-locale="auto">
</script>
<script>
// Hide default stripe button
document.getElementsByClassName('stripe-button-el')[0].style.display = 'none';
</script>
<button type="submit" class="btn btn-outline-dark text-white btn-lg">Purchase For $25</button>
</form>
</div>
<div class="col-md-6">
<img src="/img/book.png" alt="" class="img-fluid">
</div>
</div>
</section>

 Frontend completed!

f:id:lmari:20190517202121j:plain

Display success payment page

In views > create success.handlebars

<section class="py-5">
<h1 class="display-3">
Thank You
</h1>
<p class="lead">Your Ebook should be emailed to you within 1 business day</p>
<a href="/" class="btn btn-dark btn-lg">Go Back Home</a>
</section>

To see what it looks like, add highlighted bit of code in app.js:

f:id:lmari:20190517235755j:plain

Create new folder views > layouts

Create main.handlebars

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<title>Web Development Ebook</title>
</head>
<body class="bg-primary text-white">
<nav class="navbar navbar-expand-md navbar-dark bg-dark py-3">
<div class="container">
<a href="index.html" class="navbar-brand">
<h3 class="d-inline align-middle">Traversy Media</h3>
</a>
</div>
</nav>
<div class="container">
{{{body}}}
</div>
</body>
</html>

3. Deploy in server and hide keys

Create config folder at root

Create keys.js

if(process.env.NODE_ENV === 'production'){
module.exports = require('./keys_prod');
} else {
module.exports = require('./keys_dev');
}

Create keys_dev.js

module.exports ={
stripePublishableKey: 'copypublishablekeyfromstripe',
stripeSecretKey: 'copysecretkeyfromstripe'
}

Create keys_prod.js

module.exports ={
stripePublishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
stripeSecretKey: process.env.STRIPE_SECRET_KEY
}

Create .gitignore to show files to ignore

node_modules
keys_dev.js

4. Initalize as Local Repository and commit

git init

git add .

git commit -am "initial commit"

 

5. Create App and Heroku Deploy

heroku login

heroku create

heroku git:remote -a hidden-lake-17071

git push heroku master

heroku open

If problem exit, heroku logs

Everytime a file is changed, RUN:

git add .

git commit -am "fixed keys file"

git push heroku master

 Go to https://hidden-lake-17071.herokuapp.com/

Go to Heroku > Settings > Reveal Config Vars

Add STRIPE_PUBLISHABLE_KEY, STRIPE_SECRET_KEY and values from stripe.com

Verify at stripe that payment has been received

 

Tips: To take payments

  • Need SSL - Upgrade to paid dynos to configure Heroku SSL
  • Activate account at stripe.com, and get a new set of publishable keys and secret keys for bank system