Last active
January 5, 2017 14:39
-
-
Save thecolorblue/11217d293096f86e2e4118e65d642ee3 to your computer and use it in GitHub Desktop.
Receive a webhook from WooCommerce and push each product/line item into Zapier (which then puts them into a Google Spreadsheet). This is a great example, not because its particularly well written, but because it is so function.
This file contains hidden or 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
| 'use strict'; | |
| var https = require('https'); | |
| var request = require('request-promise'); | |
| var Promise = require("bluebird"); | |
| /** | |
| * Pass the data to send as `event.data`, and the request options as | |
| * `event.options`. For more information see the HTTPS module documentation | |
| * at https://nodejs.org/api/https.html. | |
| * | |
| * Will succeed with the response body. | |
| */ | |
| exports.handler = (event, context, callback) => { | |
| var body = typeof event.body === 'string' ? JSON.parse(event.body): event.body; | |
| if (!body || Object.keys(body).length === 0 || body.order.line_items.length === 0) { | |
| return callback(null, { | |
| "statusCode": "200", | |
| "headers": { }, | |
| "body": "no order or no line items." | |
| }); | |
| } | |
| try { | |
| var order = body.order; | |
| var rows = order.line_items.map((item)=>{ | |
| var dow = item.meta.filter((m)=>m.label === "Delivery Day")[0] && item.meta.filter((m)=>m.label === "Delivery Day")[0].value; | |
| var name = item.name; | |
| if (item.meta.length > 0) | |
| name += ' - ' + item.meta.map((m)=>{ | |
| if (m.label !== "Delivery Day") return m.value; | |
| }).filter((m)=>!!m).join(' - '); | |
| return { | |
| dow: dow, | |
| product_name: name, | |
| order_id: order.id, | |
| created_at: order.created_at, | |
| total: order.total, | |
| location: order.shipping_methods, | |
| customer_name: order.billing_address.first_name + ' ' + order.billing_address.last_name, | |
| customer_email: order.billing_address.email, | |
| customer_phone: order.billing_address.phone, | |
| id: order.id + '' + item.product_id, | |
| quantity: item.quantity | |
| }; | |
| }).map((row)=>request.post({ url:'https://hooks.zapier.com/hooks/catch/1732959/6xah52/', json:true, body: row })); | |
| } catch(e) { | |
| console.error(e); | |
| return callback(e); | |
| } | |
| Promise.all(rows) | |
| .then((response)=>{ | |
| callback(null, { | |
| "statusCode": "200", | |
| "headers": { }, | |
| "body": JSON.stringify(response) | |
| }); | |
| }) | |
| .catch((error)=>{ callback(error) }) | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment