Skip to content

Instantly share code, notes, and snippets.

@Teepheh-Git
Last active July 4, 2025 12:05
Show Gist options
  • Select an option

  • Save Teepheh-Git/8b91d0312e4cbcf8408e55972fc9028e to your computer and use it in GitHub Desktop.

Select an option

Save Teepheh-Git/8b91d0312e4cbcf8408e55972fc9028e to your computer and use it in GitHub Desktop.
.ts
import axios from 'axios';
import { gql, request } from 'graphql-request';
import { BASE_URL } from '@/utils/config';
// Keeping the interfaces unchanged as they are not dependent on the HTTP client used
const SHOPIFY_API_VERSION = '2024-04';
export interface GenericShopifyAPIPayload {
url: string;
}
export interface GetShopifyProductPayload extends GenericShopifyAPIPayload {
productId: string;
accessToken: string;
}
export interface GetShopifyProductResponse {
products: Products;
}
export interface Products {
edges: Edge[];
}
export interface Edge {
node: Node;
}
export interface Node {
variants: Variants;
}
export interface Variants {
edges: Edge2[];
}
export interface Edge2 {
node: Node2;
}
export interface Node2 {
id: string;
product: Product;
price: Price;
}
export interface Product {
availableForSale: boolean;
createdAt: string;
description: string;
handle: string;
id: string;
onlineStoreUrl: any;
productType: string;
publishedAt: string;
requiresSellingPlan: boolean;
tags: any[];
title: string;
totalInventory: number;
trackingParameters: any;
updatedAt: string;
vendor: string;
}
export interface Price {
amount: string;
currencyCode: string;
}
/**
* Updated to reflect cartCreate API
*/
export type CreateCheckoutResponse = {
cartCreate: {
cart: {
id: string;
checkoutUrl: string;
lines: {
edges: Array<{
node: {
id: string;
quantity: number;
merchandise: {
id: string;
title: string;
};
};
}>;
};
};
userErrors: Array<{
field: string[];
message: string;
}>;
};
};
/**
* Updated to reflect cartDiscountCodesUpdate API
*/
export interface AddCouponPayload extends GenericShopifyAPIPayload {
cartId: string;
couponCode: string;
accessToken: string;
}
export type AddCouponResponse = {
cartDiscountCodesUpdate: {
cart: {
id: string;
discountCodes: Array<{
code: string;
applicable: boolean;
}>;
checkoutUrl: string;
};
userErrors: Array<{
field: string[];
message: string;
}>;
};
};
export function formatUrl(url: string): string {
try {
const trimmedUrl = url.trim();
if (!trimmedUrl.startsWith('http://') && !trimmedUrl.startsWith('https://')) {
return `https://${trimmedUrl}`;
}
return trimmedUrl;
} catch (error) {
console.error('Invalid URL:', error);
return '';
}
}
export interface CreateShopifyCheckoutPayload extends GenericShopifyAPIPayload {
productVariantId: string;
accessToken: string;
quantity: number;
}
export async function getShopifyVariant({ url, accessToken, productId }: GetShopifyProductPayload) {
const graphqlQuery = gql`
{
products(first: 1, query: "id:${productId}") {
edges {
node {
variants(first: 1) {
edges {
node {
id
product {
availableForSale
createdAt
description
handle
id
onlineStoreUrl
productType
publishedAt
requiresSellingPlan
tags
title
totalInventory
trackingParameters
updatedAt
vendor
}
price {
amount
currencyCode
}
}
}
}
}
}
}
}
`;
const headers = {
'X-Shopify-Storefront-Access-Token': accessToken,
};
url = formatUrl(url);
const data = await request<GetShopifyProductResponse>({
url: `${url}/api/${SHOPIFY_API_VERSION}/graphql.json`,
document: graphqlQuery,
requestHeaders: headers,
}).then((response) => {
console.log('response', response);
return response;
});
return { data: data };
}
export function formatShopifyId(id: string) {
return `gid://shopify/ProductVariant/${id}`;
}
export async function createShopifyCheckout({
url,
productVariantId,
accessToken,
quantity,
}: CreateShopifyCheckoutPayload) {
url = formatUrl(url);
const graphqlQuery = gql`
mutation {
cartCreate(input: {
lines: [
{
merchandiseId: "${formatShopifyId(productVariantId)}",
quantity: ${quantity}
}
]
}) {
cart {
id
checkoutUrl
lines(first: 5) {
edges {
node {
id
quantity
merchandise {
... on ProductVariant {
id
title
}
}
}
}
}
}
userErrors {
field
message
}
}
}
`;
const headers = {
'X-Shopify-Storefront-Access-Token': accessToken,
};
const data = await request({
url: `${url}/api/${SHOPIFY_API_VERSION}/graphql.json`,
document: graphqlQuery,
requestHeaders: headers,
});
return { data } as { data: CreateCheckoutResponse };
}
export async function addCoupon({ url, cartId, couponCode, accessToken }: AddCouponPayload) {
url = formatUrl(url);
const graphqlQuery = gql`
mutation {
cartDiscountCodesUpdate(
cartId: "${cartId}",
discountCodes: ["${couponCode}"]
) {
cart {
id
discountCodes {
code
applicable
}
checkoutUrl
}
userErrors {
field
message
}
}
}
`;
const headers = {
'X-Shopify-Storefront-Access-Token': accessToken,
};
const data = await request({
url: `${url}/api/${SHOPIFY_API_VERSION}/graphql.json`,
document: graphqlQuery,
requestHeaders: headers,
});
return { data } as { data: AddCouponResponse };
}
export async function getShopifyToken({ brandId, token }: any) {
const { data } = await axios.get(`${BASE_URL}/order/shopify-token/retrieve/?brand=${brandId}`, {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
});
return data?.data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment