Shopify REST Admin API で Customer のタグ追加・削除 サンプルコード – Google Apps Script (GAS) 編

Shopify REST Admin API で Customer のタグを追加・削除する Google Apps Script (GAS) サンプルコードを書いたのでご紹介します。

Shopify | ショッピファイ

背景 Shopify REST Admin API で Customer のタグを追加・削除したい

Shopify REST Admin API で Customer のタグを追加・削除するために Google Apps Script でサンプルコードを書いてみました。

Shopify REST Admin API で Customer を email 検索するサンプルコード – Google Apps Script (GAS) 編 – CodeNote の続きです。

サンプルコード Shopify REST Admin API で Customer のタグ追加・削除

Shopify REST Admin API PUT /admin/api/${api_version}/customers/${customer_id}.json を Google Apps Script から呼び出して、顧客情報にタグを追加・削除するサンプルコードは以下のとおりです。

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);
}

以上、Shopify REST Admin API で Customer のタグを追加・削除する Google Apps Script (GAS) サンプルコードを書いてみた、現場からお送りしました。

参考情報