Skip to content

Instantly share code, notes, and snippets.

@reggie3
Last active November 2, 2021 11:20
Show Gist options
  • Save reggie3/ebadc652b3859fcd9f57fdb15e04ed58 to your computer and use it in GitHub Desktop.
Save reggie3/ebadc652b3859fcd9f57fdb15e04ed58 to your computer and use it in GitHub Desktop.
Braintree Node Server Lambda
/***********************************************************************************
AWS Lambda boilerplate for API functions
This boilerplate is designed to be used with AWS API gateway and to return information
to a client
***********************************************************************************/
const util = require("util");
// - provide access to aws-sdk
//const AWS = require('aws-sdk');
// - provide access to mysql databases
// const mysql = require('mysql');
// - unmarshal a DynamodDB item to standard JSON
// const parse = AWS.DynamoDB.Converter.output;
// - used to create unique IDs. requires installation of uuid npm package
// const uuidv1 = require('uuid/v1');
// - set up a docClient to use with dynamoDB store
/* let docClient = new AWS
.DynamoDB
.DocumentClient(); */
// - access an environmental variable
// let host = process.env.dbHost;
// create a Braintree gateway
var braintree = require("braintree");
var gateway = braintree.connect({
environment: braintree.Environment.Sandbox, // either Sandbox or Production
merchantId: process.env.merchantID, // these come from the Lambda's environmental variables
publicKey: process.env.publicKey,
privateKey: process.env.privateKey
});
exports.handler = (event, context, callback) => {
const done = (err, response) => {
// return the required callback function
callback(null, {
headers: {
"Access-Control-Allow-Origin": "*", // need if calling API from WebView which is just a browser
"Content-Type": "application/json",
"Access-Control-Allow-Headers":
"Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token"
},
statusCode: err ? "400" : "200",
body: err
? JSON.stringify({
type: "error",
err
})
: JSON.stringify({
type: "success",
response
})
});
};
/*************************************************
* Braintree related functions based on documentation at
* https://developers.braintreepayments.com/start/hello-server/node
*/
/////////////////////////////////////
// get a client token from Braintree and send it to the client
/////////////////////////////////////
const getClientToken = (options = {}) => {
console.log("getting client token"); // console.logs will show up in AWS Cloudwatch
let customerId = options && options.hasOwnProperty("customerID")
? options.customerID
: null;
let merchantAccountId = options && options.hasOwnProperty("merchantAccountID")
? options.merchantAccountID
: null;
gateway.clientToken
.generate({
customerId: customerId,
merchantAccountId: merchantAccountId
})
.then(result => {
if (!result.success) {
done(result.message); // call the done function to return an error message to the client
} else {
// view the successful response
console.log(
"result: ",
util.inspect(result, {
showHidden: false,
depth: null
})
);
// pass the successful response to the client
done(null, { result });
}
})
.catch(function(err) {
console.log("+++++++++++++++");
console.error(err);
done(err);
});
};
/////////////////////////////////////
// purchase an item using Braintree's transaction method
/////////////////////////////////////
const purchaseItem = purchaseInformation => {
/* console.log(
"purchaseInformation: ",
util.inspect(purchaseInformation, { showHidden: false, depth: null })
); */
gateway.transaction.sale(
{
amount: purchaseInformation.amount,
paymentMethodNonce: purchaseInformation.nonce,
options: {
submitForSettlement: true
}
},
function(err, response) {
console.log(response);
if (err) {
console.log("*********");
console.log({ err });
done(err);
} else {
if (response.success === false) {
console.log("#################");
console.log(response.result);
done({ msg: "Error validating payment server information" });
} else {
console.log("~~~~~~~~~~~");
console.log(response.ErrorResponse);
done(null, response);
}
}
}
);
};
/*************************************************
* Enter here
*/
// view the event that was received
console.log(
"event: ",
util.inspect(event, {
showHidden: false,
depth: null
})
);
// try to execute API calls
try {
switch (event.queryStringParameters.action) {
case "get-client-token":
// call getClientToken with the parsed version of optional body if present, otherwise call it with nothing
getClientToken(
event.hasOwnProperty("body") ? JSON.parse(event.body) : null
);
break;
case "purchase-item":
console.log("purchasing item");
purchaseItem(JSON.parse(event.body));
break;
default:
done("invalid query string");
break;
}
} catch (error) {
done(error);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment