I’m working on the Shopify store. I want to update the customer details. I have tried the storefront API. But, they are asking for “customerAccessToken” and “X-Shopify-Storefront-Access-Token”.
To fetch the “Customer Access Token”, you have to enter your email and password, but my authentication flow is email with OTP or Mobile number with OTP. So, how can I fetch it?
Is this the only way for customers to update their own data?
sample code :
const accessToken = "CUSTOMER_ACCESS_TOKEN";
const storefrontApiUrl = "https://your_shop.myshopify.com/api/2023-10/graphql.json";
const firstName = document.getElementById("first_name").value;
const lastName = document.getElementById("last_name").value;
const email = document.getElementById("email").value;
const phone = document.getElementById("phone").value;
const mutation = `
mutation customerUpdate($customerAccessToken: String!, $customer: CustomerUpdateInput!) {
customerUpdate(customerAccessToken: $customerAccessToken, customer: $customer) {
customer {
id
firstName
lastName
email
phone
}
userErrors {
field
message
}
}
}
`;
const variables = {
customerAccessToken: accessToken,
customer: {
firstName,
lastName,
email,
phone,
},
};
try {
const response = await fetch(storefrontApiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Storefront-Access-Token": "YOUR_STOREFRONT_ACCESS_TOKEN",
},
body: JSON.stringify({ query: mutation, variables }),
});
const result = await response.json();
const updateMessage = document.getElementById("update_message");
if (result.data.customerUpdate.userErrors.length > 0) {
updateMessage.innerHTML = result.data.customerUpdate.userErrors
.map((error) => `<p>Error: ${error.message}</p>`)
.join("");
} else {
updateMessage.innerHTML = "<p>Profile updated successfully!</p>";
}
} catch (error) {
console.error("Error updating customer:", error);
document.getElementById("update_message").innerHTML = "<p>Failed to update profile. Please try again.</p>";
}