//native
/**
* Create Customer
* Create a customer. Needs at least an email, a phone (E.164, e.g. +33612345678) or a name. The optional address becomes the default address. email_marketing records email marketing consent (single opt-in).
*/
export async function main(
auth: RT.Shopify,
email: string | undefined,
phone: string | undefined,
first_name: string | undefined,
last_name: string | undefined,
tags: string[] | undefined,
note: string | undefined,
address:
| {
firstName?: string
lastName?: string
company?: string
address1?: string
address2?: string
city?: string
provinceCode?: string
zip?: string
countryCode?: string
phone?: string
}
| undefined,
email_marketing: "SUBSCRIBED" | "NOT_SUBSCRIBED" | undefined
) {
const endpoint = `https://${auth.store_name}.myshopify.com/admin/api/2026-10/graphql.json`
const call = async (body: { query: string; variables?: object }) => {
const response = await fetch(endpoint, {
method: "POST",
headers: {
"X-Shopify-Access-Token": auth.token,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(body),
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const { data, errors } = await response.json()
if (errors) {
throw new Error(JSON.stringify(errors))
}
return data
}
const data = await call({
query: `mutation ($input: CustomerInput!) { customerCreate(input: $input) { customer { id } userErrors { field message } } }`,
variables: {
input: {
email: email || undefined,
phone: phone || undefined,
firstName: first_name || undefined,
lastName: last_name || undefined,
tags: tags?.length ? tags : undefined,
note: note || undefined,
emailMarketingConsent:
email && email_marketing
? {
marketingState: email_marketing,
marketingOptInLevel: "SINGLE_OPT_IN",
}
: undefined,
},
},
})
if (data.customerCreate.userErrors.length) {
throw new Error(JSON.stringify(data.customerCreate.userErrors))
}
const id = data.customerCreate.customer.id
// CustomerInput has no address field in this API version.
if (address && Object.keys(address).length) {
const added = await call({
query: `mutation ($customerId: ID!, $address: MailingAddressInput!) { customerAddressCreate(customerId: $customerId, address: $address, setAsDefault: true) { address { id } userErrors { field message } } }`,
variables: { customerId: id, address },
})
if (added.customerAddressCreate.userErrors.length) {
throw new Error(JSON.stringify(added.customerAddressCreate.userErrors))
}
}
return (
await call({
query: `query ($id: ID!) { customer(id: $id) { id legacyResourceId displayName firstName lastName state tags note locale verifiedEmail taxExempt numberOfOrders amountSpent { amount currencyCode } createdAt updatedAt defaultEmailAddress { emailAddress marketingState marketingOptInLevel } defaultPhoneNumber { phoneNumber } defaultAddress { name firstName lastName company address1 address2 city provinceCode zip countryCodeV2 phone } } }`,
variables: { id },
})
).customer
}
Submitted by hugo989 3 hours ago