Skip to content

Instantly share code, notes, and snippets.

@furiousdavid
Created May 16, 2019 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save furiousdavid/788e3f94c81aa716812468355389d33d to your computer and use it in GitHub Desktop.
Save furiousdavid/788e3f94c81aa716812468355389d33d to your computer and use it in GitHub Desktop.
// formkeep-stripe-checkout.js on webtask.io
// Load NPM dependencies (specified in the settings)
const webtask = require('webtask-tools');
const express = require('express');
const axios = require('axios');
// Add new dependencies
const bodyParser = require('body-parser');
const stripe = require('stripe');
// Initialize an express app
const app = express();
// Use the `body-parser` middleware to easily parse the from from the request
app.use(bodyParser.urlencoded({ extended: false }));
// Add a single endpoint at the root, to handle the request
app.post('', (req, res) => {
// Grab the amount from the request body
const amount = parseInt(req.body.amount);
// Initialize a helper to connect with the Stripe API
const stripeConnection = stripe(req.webtaskContext.secrets.stripeKey);
// Grab the Stripe token from the request body
// (this is the placeholder for the customer's card that Stripe gives us)
const stripeToken = req.body.stripeToken;
const formkeepUrl = req.webtaskContext.secrets.formkeepUrl;
const formkeepHeaders = { "Content-Type": "application/json" };
const formkeepData = {
// Use the actual form data to store the donor's info in FormKeep
email: req.body.stripeEmail,
amount: `$${amount / 100.0}`,
phone: req.body.phone,
message: req.body.message
};
// REMOVE:
// return axios.post(formkeepUrl, formkeepData, { headers: formkeepHeaders })
// Create the charge in Stripe
return stripeConnection.charges.create({
amount,
currency: 'usd',
source: stripeToken,
description: 'Donation to our cause'
})
.then(function() {
// If the charge succeeds, post the information to FormKeep
// There you can query all the data, export it and setup "thank you" emails
return axios.post(formkeepUrl, formkeepData, { headers: formkeepHeaders });
})
.then(function() {
// If it succeeds, redirect to the FormKeep thank you page
// (you can then add a different page to thank your donors)
res.redirect(301, `https://formkeep.com/thanks?h=Thanks&s=Your donation was received`);
})
.catch(function(err) {
// If it fails, redirect to the FormKeep thank you page
// (but with an error message)
console.error(err);
res.redirect(301, `https://formkeep.com/thanks?h=Sorry&s=Your payment couldn't be processed`);
});
});
// Use webtask helpers to export the express app as webtask serverless function
module.exports = webtask.fromExpress(app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment