Sync Shopify customer data to Zendesk

Keep your Zendesk user profiles up-to-date by automatically capturing changes to customer information in Shopify. This hook handles both the creation of new profiles and updates to existing ones.

Prerequisites

  • Zendesk API token
  • Your Zendesk subdomain

Configuration

1) Set up trigger

In Cloudhooks dashboard, select "A customer is updated" trigger. This trigger fires for both new and modified customers.

2) Configure authentication

Set your Zendesk credentials in the hook code:

const API_TOKEN = 'YOUR_API_TOKEN';
const ZENDESK_SUBDOMAIN = 'YOUR_ZENDESK_SUBDOMAIN';

3) Implement the hook

Copy and paste the following code into your hook editor:

const API_TOKEN = 'YOUR_API_TOKEN';
const ZENDESK_SUBDOMAIN = 'YOUR_ZENDESK_SUBDOMAIN';

module.exports = async function(payload, actions, context) {
  let userUpdate = {
    name: payload.first_name + ' ' + payload.last_name,
    email: payload.email,
    skip_verify_email: true,
    user_fields: {
      shopifyCustomerId: payload.id.toString(),
    },
  };
  const phoneNumber = payload.phone ?? (payload.defaultAddress && payload.defaultAdddress.phone);
  const defaultAddress = payload.default_address ?? (payload.addresses && payload.addresses.find(address => address.default));

  if (phoneNumber) {
    userUpdate.phone = phoneNumber;
    userUpdate.user_fields.phoneNumber = phoneNumber;
  }

  if (defaultAddress) {
    const addressFields = {}

    defaultAddress.address1   && (addressFields.address1 = defaultAddress.address1);
    defaultAddress.address2   && (addressFields.address2 = defaultAddress.address2);
    defaultAddress.city       && (addressFields.city = defaultAddress.city);
    defaultAddress.province   && (addressFields.region = defaultAddress.province);
    defaultAddress.zip        && (addressFields.postalCode = defaultAddress.zip);
    defaultAddress.country    && (addressFields.country = defaultAddress.country);

    userUpdate.user_fields = {...userUpdate.user_fields, ...addressFields}
  }

  try {
    const result = await actions.http.post(
      `https://${ZENDESK_SUBDOMAIN}.zendesk.com/api/v2/users/create_or_update.json`,
      { user: userUpdate },
      { 
        headers: { 
        'Authorization': `Basic ${API_TOKEN}`, 'Content-type': 'application/json' 
        }
      }
    );

    if (result.status != '200' && result.status != '201' ) {
      throw new Error(result.data);
    }
  } catch (err) {
    console.error('Cannot update user in Zendesk: ', err);
  }

}