Last active
September 10, 2021 15:17
-
-
Save teer823/d4385a154416f01cdb493528f4cd70dd to your computer and use it in GitHub Desktop.
WooCommerce Webhook Template - For Lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = require('crypto'); | |
function validateRequest (event) { | |
// GET Secret from Environment Variable | |
const { WC_SECRET } = process.env; | |
// Get Header with Hash to validate from header (event.header) | |
const wc_hmac_hash = event.headers ? | |
event.headers['X-WC-Webhook-Signature'] || event.headers['x-wc-webhook-signature'] | |
: ""; | |
// Calculate Hash from content (event.body) | |
const content_hmac_hash = crypto.createHmac("sha256", WC_SECRET) | |
.update(Buffer.from(event.body, "utf8")) | |
.digest("base64"); | |
if(content_hmac_hash !== wc_hmac_hash) { | |
//Request Integrity check failed; Invalid Webhook | |
console.log('Integrity of request compromised, aborting'); | |
return false; | |
} | |
// Valid Webhook | |
return true; | |
} | |
async function processPurchase(data) { | |
//Add code here to process purchase , notify user , etc | |
const { status } = data; | |
switch(status) { | |
case "processing": { | |
console.log('OnOrderUpdated'); | |
} | |
break; | |
case "completed": { | |
console.log('OnOrderCompleted'); | |
} | |
break; | |
default: { | |
//Log data | |
console.log(`Unknown event ${status}`); | |
} | |
break; | |
} | |
} | |
// Use API Gateway Lambda Proxy to include header in event object | |
exports.handler = async (event) => { | |
let response; | |
if(!validateRequest(event)) { | |
response = { | |
statusCode: 400, | |
body: JSON.stringify("Bad request"), | |
}; | |
return response; | |
} else { | |
const data = JSON.parse(event.body); | |
await processPurchase(data); | |
response = { | |
statusCode: 200, | |
body: JSON.stringify('Process Completed'), | |
}; | |
return response; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment