2. GraphQL Schema and Cart Query Setup
The Shopify Storefront API uses GraphQL. To integrate checkout, you must define a query to retrieve the product Variant ID and a mutation to create a cart.
2.1. Querying Product List and Variant IDs
This query retrieves option IDs (Variant IDs) for available products to enable single-item purchases.
const PRODUCT_LIST_QUERY = `
query ProductListForOnePageCheckout($first: Int = 20) {
products(first: $first, sortKey: TITLE) {
edges {
node {
id
title
variants(first: 10) {
edges {
node {
id
title
availableForSale
price {
amount
currencyCode
}
}
}
}
}
}
}
}
`;
2.2. Cart Creation Mutation (cartCreate)
This mutation creates a cart populated with buyer details and shipping address to retrieve the checkoutUrl.
const CREATE_CART_MUTATION = `
mutation CreateCartWithBuyerAndAddress(
$lines: [CartLineInput!]
$email: String
$phone: String
$countryCode: CountryCode!
$firstName: String
$lastName: String
$address1: String
$address2: String
$city: String
$provinceCode: String
$zip: String
) {
cartCreate(
input: {
lines: $lines
buyerIdentity: {
email: $email
phone: $phone
countryCode: $countryCode
}
delivery: {
addresses: [
{
address: {
deliveryAddress: {
firstName: $firstName
lastName: $lastName
address1: $address1
address2: $address2
city: $city
provinceCode: $provinceCode
countryCode: $countryCode
zip: $zip
phone: $phone
}
}
selected: true
}
]
}
}
) {
cart {
id
checkoutUrl
}
userErrors {
field
message
}
}
}
`;