export default async function main(args) {
const logs = [];
// Extract input variables from args
const { customerIdentifier, accessToken, shopDomain } = args.inputVars;
logs.push(`Extracted inputs - customerIdentifier: ${customerIdentifier}, accessToken: ${accessToken ? 'PROVIDED' : 'MISSING'}, shopDomain: ${shopDomain}`);
// Validate that the required input variables are provided
if (!customerIdentifier || !accessToken || !shopDomain) {
logs.push("Error: Missing required input variables: customerIdentifier, accessToken, or shopDomain");
return {
next: { path: 'error' },
};
}
// Determine endpoint based on whether the customerIdentifier contains '@' (email) or not (ID)
let url;
if (customerIdentifier.includes("@")) {
const encodedEmail = encodeURIComponent(`email:${customerIdentifier}`);
url = `https://${shopDomain}/admin/api/2024-01/customers/search.json?query=${encodedEmail}`;
logs.push(`Querying by email: ${url}`);
} else {
url = `https://${shopDomain}/admin/api/2024-01/customers/${customerIdentifier}.json`;
logs.push(`Querying by customer ID: ${url}`);
}
// Configure the fetch request
const config = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': accessToken,
},
};
try {
// Make the API call
logs.push(`Making API call to URL: ${url}`);
const response = await fetch(url, config);
// Check if the response status is OK
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Extract the JSON body from the response
const responseBody = response.json;
logs.push("Extracting JSON from the response:", responseBody.customers);
// If searching by email, response body structure would be different
const customerData = customerIdentifier.includes("@") ? responseBody.customers[0] : responseBody.customer;
logs.push("Extracting customer data:", JSON.stringify(customerData));
// Validate the responseBody structure as expected
if (!customerData || typeof customerData !== 'object') {
throw new Error("Invalid or missing response body from the API");
}
// Extract required customer details
const customerEmail = customerData?.email || "";
const customerFirstName = customerData?.first_name || "";
const customerLastName = customerData?.last_name || "";
const customerOrdersCount = customerData?.orders_count || "";
const customerTotalSpent = customerData?.total_spent || "";
const customerLastOrderId = customerData?.last_order_id || "";
const customerID = customerData?.id || "";
logs.push(`Customer data retrieved: Email - ${customerEmail}, Name - ${customerFirstName} ${customerLastName} ${customerID}`);
// Create the success return object with extracted data
return {
outputVars: {
response: JSON.stringify(responseBody),
customerEmail,
customerFirstName,
customerLastName,
customerOrdersCount,
customerTotalSpent,
customerLastOrderId,
customerID
},
next: { path: 'success' },
};
} catch (error) {
logs.push(`Error: ${error.message}`);
return {
next: { path: 'error' },
};
}
}