Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Changing a shopify order's location based on the shipping address of the order using order.created/order.updated webhooks
// For posterity, I'm saving/sharing some code I wrote for a shopify app I ran
// in which I had two physical warehouses: one in Maryland, and one in California.
// Each of these was its own "Location" in Shopify, and I wanted every order
// to be automatically assigned to one or the other based on the shipping address.
// I ran this webhook on Autocode: https://autocode.com/
// which makes it really easy to stand up a webhook without futzing with servers.
const Shopify = require('shopify-api-node');
const shopify = new Shopify({
shopName: 'my-shop-name',
apiKey: process.env.SHOPIFY_API_KEY,
password: process.env.SHOPIFY_API_PW,
});
const californiaLocationId = 'XYZ123';
const marylandLocationId = 'XYZ456';
const westCoastStates = new Set([
// Based on https://www.ups.com/using/services/servicemaps/maps25/map_0774_FEB21.gif
// and (from MD): https://www.ups.com/using/services/servicemaps/maps25/map_0140_FEB21.gif
// 1-2 day
'CA',
'NV',
// 2 days
'WA',
'OR',
'AZ',
'UT',
'HI',
// 2-3 days
'ID',
'WY',
// 3 days
'AK',
'NM',
//'CO', keep on MD for now.
// 3-4 days
'MT',
]);
module.exports = async (context) => {
const {
id,
order_number,
created_at,
updated_at,
shipping_address,
fulfillment_status,
line_items,
} = context.params;
console.log({
id,
order_number,
created_at,
updated_at,
shipping_address,
fulfillment_status,
tags,
});
if (
shipping_address.country_code === 'US' &&
westCoastStates.has(shipping_address.province_code) &&
fulfillment_status !== 'fulfilled' &&
fulfillment_status !== 'partial'
) {
console.log('CA order found!');
const fulfillmentOrders = await shopify.order.fulfillmentOrders(id);
console.log('fulfillmentOrders:');
console.log(fulfillmentOrders.map(({id, status, assigned_location: {name}}) => ({id, status, name})));
if (fulfillmentOrders.length === 1) {
const fulfillmentOrder = fulfillmentOrders[0];
console.log(`Moving fulfillment ${fulfillmentOrder.id} to ${californiaLocationId}`);
await shopify.fulfillmentOrder.move(fulfillmentOrder.id, californiaLocationId);
} else {
console.log('Too many fulfillments; assuming a human has been at work, leaving it be.')
}
}
return `ok`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment