Sample Code for Adding/Removing Customer Tags with Shopify REST Admin API - Google Apps Script (GAS) Edition
I wrote Google Apps Script (GAS) sample code for adding/removing customer tags with Shopify REST Admin API, so I’ll introduce it.
I wanted to add/remove customer tags using Shopify REST Admin API, so I wrote sample code with Google Apps Script.
This is a continuation of Shopify REST Admin API で Customer を email 検索するサンプルコード - Google Apps Script (GAS) 編 - CodeNote.
The sample code for calling Shopify REST Admin API PUT /admin/api/${api_version}/customers/${customer_id}.json
from Google Apps Script to add/remove tags to customer information is as follows:
function main(){
const customerV1 = findCustomerByEmail('[email protected]');
Logger.log(customerV1.tags);
const customerV2 = addTagToCustomer(customerV1, 'VIP');
Logger.log(customerV2.tags);
const customerV3 = removeTagToCustomer(customerV2, 'VIP');
Logger.log(customerV3.tags);
}
const SHOPIFY_API_KEY = PropertiesService.getScriptProperties().getProperty('SHOPIFY_API_KEY');
const SHOPIFY_PASSWORD = PropertiesService.getScriptProperties().getProperty('SHOPIFY_PASSWORD');
const SHOPIFY_API_URL = PropertiesService.getScriptProperties().getProperty('SHOPIFY_API_URL');
function requestShopifyAPI_(url, method, params) {
const options = {
method: method,
payload: JSON.stringify(params),
headers: {
"Authorization": "Basic " + Utilities.base64Encode(`${SHOPIFY_API_KEY}:${SHOPIFY_PASSWORD}`),
"Content-type": 'application/json',
},
muteHttpExceptions: false,
};
const response = UrlFetchApp.fetch(`${SHOPIFY_API_URL}${url}`, options);
return JSON.parse(response.getContentText());
}
function searchCustomersByEmail(email) {
const response = requestShopifyAPI_(`/customers/search.json?query=email:${email}`, 'get');
return response.customers;
}
function findCustomerByEmail(email) {
const customers = searchCustomersByEmail(email);
const customer = customers.find(c => c.email === email);
return customer;
}
function updateCustomerTags_(customerId, tags) {
const response = requestShopifyAPI_(
`/customers/${customerId}.json`,
'put',
{
customer: {
id: customerId,
tags: tags
}
}
);
return response.customer;
}
function addTagToCustomer(customer, tag) {
const currentTags = customer.tags.split(',');
currentTags.push(tag);
const tags = currentTags.join(',');
return updateCustomerTags_(customer.id, tags);
}
function removeTagToCustomer(customer, tag) {
const currentTags = customer.tags.split(',');
const tags = currentTags.filter(t => t.trim() !== tag).join(',');
return updateCustomerTags_(customer.id, tags);
}
Above, I wrote Google Apps Script (GAS) sample code for adding/removing customer tags with Shopify REST Admin API.
That’s all from the Gemba.