Getting started with Stripe – part 2
This is a follow-up to my introductory post on Stripe. I covered Stripe’s merchant and marketplace products in the first post, and in this one we’ll try building some basic web apps that use Stripe Checkout and Stripe.js.
Note that to keep the focus on the API I kept things as minimal as possible, which meant omitting most error checking, so do not use any of the code from this post as-is in production. At the very least, you need to add comprehensive error handling and use HTTPS for both the frontend and the backend.
Backend: Node.js + Express
We’ll use a common node.js + Express backend for all the examples, so let’s cover that first.
Making a charge against a credit/debit card using the Stripe API requires a surprisingly small amount of code. The following is a fully-functional Node.js/Express app that will make a $10 charge against a card token supplied in an HTTP POST request to http://<server>:3000/charge
, and respond with either an HTTP 204 OK or an HTTP 500 error depending on whether the card was successfully charged or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
var express = require('express'); var bodyParser = require('body-parser'); var stripe = require('stripe')('sk_MY_SECRET_KEY'); var app = express(); app.use(bodyParser()); app.post('/charge', function(req, res) { var stripeToken = req.body.stripeToken; var amount = 1000; stripe.charges.create({ card: stripeToken, currency: 'usd', amount: amount }, function(err, charge) { if (err) { res.send(500, err); } else { res.send(204); } }); }); app.use(express.static(__dirname)); app.listen(process.env.PORT || 3000); |
To test, save the above code into a file called index.js
, replacing sk_MY_SECRET_KEY
with your Stripe secret key (if you don’t have one, sign up for an account with Stripe). Then setup and run it like you would any Express application, i.e.:
1 2 3 |
npm init npm install --save stripe express body-parser node index.js |
Your backend is now running at http://localhost:3000
This backend can accept a Stripe card token and make a $10 charge against it. Sweet! We now need to build a frontend that accepts card information, converts that into a card token, and sends it to the backend.
Read More