Skip to content

Instantly share code, notes, and snippets.

@mootrichard
Last active August 10, 2018 21:57
Show Gist options
  • Save mootrichard/0aecaa23eff8864d69e8df652520e9dd to your computer and use it in GitHub Desktop.
Save mootrichard/0aecaa23eff8864d69e8df652520e9dd to your computer and use it in GitHub Desktop.
Our final Serverless function for creating checkouts
const SquareConnect = require('square-connect');
const crypto = require('crypto');
const querystring = require('querystring');
module.exports.checkout = (event, context, callback) => {
(SquareConnect.ApiClient.instance).authentications["oauth2"].accessToken = process.env.ACCESS_TOKEN;
const formData = querystring.parse(event.body);
const locationId = process.env.LOCATION_ID;
const checkoutRequest = {
idempotency_key: crypto.randomBytes(48).toString('base64'),
order: {
idempotency_key: crypto.randomBytes(48).toString('base64'),
reference_id: Date.now().toString(),
line_items: [
{
catalog_object_id: formData.itemVarID,
quantity: "1"
}
]
},
merchant_support_email: "support@squareup.com"
};
const checkoutApi = new SquareConnect.CheckoutApi();
checkoutApi.createCheckout(locationId, checkoutRequest).then((checkoutResponse)=>{
const response = {
statusCode: 302,
headers: { Location: `${checkoutResponse.checkout.checkout_page_url}` }
};
callback(null, response);
}).catch(error => {
console.log(JSON.stringify(error, null, 2));
callback(error)
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment