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

Shopify REST Admin API で Customer を email 検索する Google Apps Script (GAS) サンプルコードを書いたのでご紹介します。

Shopify | ショッピファイ

背景 Shopify REST Admin API で Customer を email 検索したい

Shopify REST Admin API で Customer を email で完全一致検索したいシチュエーションに遭遇したので Google Apps Script でサンプルコードを書いてみました。

Shopify REST Admin API を Google Apps Script (GAS) から使うサンプルコード – CodeNote の続きです。

サンプルコード Shopify REST Admin API で Customer を email 検索

Shopify REST Admin API /customers/search.json を Google Apps Script から呼び出して、顧客情報を email で完全一致検索したサンプルコードは以下のとおりです。

function main(){
  const customer = findCustomerByEmail('[email protected]');
  Logger.log(customer);
}

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

以上、Shopify REST Admin API で Customer を email 検索する Google Apps Script (GAS) サンプルコードを書いてみた、現場からお送りしました。