שימוש בהמלצות מוצרים באמצעות API עבור Shopify
ההמלצות מוצרים של פלאשי עוזרות להגדיל את המכירות באמצעות המלצות מוצרים חכמות שמתבססות על כל פרטי המבקרים והלקוחות החוזרים באתר.
באמצעות ה API תוכלו להגיע למקסימום יכולות בעיצוב והתאמות לאתר שלכם ולעשות כמעט כל דבר שתרצו באמצעות מספר קודים פשוטים.
בשופיפיי יש לבצע שלב מקדים לפני שעובדים על הקוד שהוא בעצם לקבל גישה לקרוא את המוצרים שלכם
באמצעות Storefront API בסרטון אני מסביר את הנושא בהרחבה.
מהניסיון שלנו עם חברות פיתוח שונות, הערכת השעות לעבודה מהסוג הזה היא בין 5-8 שעות פיתוח, חשוב לקחת את זה בחשבון בהחלטה על שיטת היישום. תמיד ניתן לבצע הטמעה באמצעות DIV ולא באמצעות API.
שלב ההטמעה
יצרנו עבורכם מחלקה ב JS שמדגימה איך לבצע את זה שתוכלו להשתמש בה, בנוסף לסרטון שמופיע במאמר, יש לצפות בסרטון לפרטים נוספים.
להלן המחלקה עם כל האפשרויות שיצרנו עבורכם.
<script>
window.FlashyProductRecommendations = class FlashyProductRecommendations {
constructor(popupId, productsContainer = 'home-recommendations') {
this.popupId = popupId;
this.container = document.getElementById(productsContainer);
}
// Fetch product recommendations
async fetchRecommendations() {
try {
const recommendations = await flashy.recommendations.get(this.popupId);
return this.getItemIds(recommendations.products);
} catch (error) {
console.warning("Error fetching flashy recommendations:", error);
}
}
// Fetch product details from Shopify
async fetchProductDetails(productNumericIds) {
const productGlobalIds = productNumericIds.map(id => `gid://shopify/Product/${id}`);
const productQuery = `
query ProductsQuery($ids: [ID!]!) {
nodes(ids: $ids) {
... on Product {
id
title
handle
descriptionHtml
createdAt
productType
vendor
tags
images(first: 2) {
edges {
node {
id
originalSrc
altText
}
}
}
variants(first: 2) {
edges {
node {
id
title
priceV2 {
amount
currencyCode
}
availableForSale
sku
compareAtPriceV2 {
amount
currencyCode
}
}
}
}
}
}
}
`;
try {
const response = await fetch(`//${window.Shopify.shop}/api/2022-01/graphql.json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': 'your-storefront-access-token',
},
body: JSON.stringify({
query: productQuery,
variables: { ids: productGlobalIds },
}),
});
const { data, errors } = await response.json();
if (errors) {
console.error('GraphQL Errors:', errors);
return null;
}
return data.nodes;
} catch (error) {
console.error('Fetch Error:', error);
return null;
}
}
getProductTemplate(product) {
return `
<div class="product-item">
<img src="${product.images.edges[0].node.originalSrc}" alt="Product Image" class="product-image">
<div class="product-title">${product.title}</div>
<a href="/products/${product.handle}" class="product-button view-product">View Product</a>
<button class="product-button add-to-cart">Add to Cart</button>
</div>
`;
}
// Render product details
async displayProducts() {
const recommendations = await this.fetchRecommendations();
const productsDetails = await this.fetchProductDetails(recommendations);
productsDetails.forEach(product => {
const productHTML = this.getProductTemplate(product);
// Insert the product HTML directly into the container
this.container.insertAdjacentHTML('beforeend', productHTML);
const lastProductItem = this.container.lastElementChild;
// Add event listener for the Click or Add to Cart events
const links = lastProductItem.querySelectorAll('a'); // Selects all <a> tags within the item
// For any links events
links.forEach(link => {
link.addEventListener('click', (e) => {
this.trackProductInteraction('amplify:Click', this.getItemId(product.id));
});
});
// If you are using Add To Cart directly from the product
// lastProductItem.querySelector('.add-to-cart').addEventListener('click', (e) => {
// this.trackProductInteraction('amplify:AddToCart', this.getItemId(product.id), product.variants[0].price);
// });
});
}
// Track product interactions
trackProductInteraction(eventType, productId, value = null, currency = 'ILS') {
const eventData = {
'popup_id': this.popupId,
'content_ids': [productId]
};
if (eventType === 'amplify:AddToCart') {
eventData.value = value; // Assuming value is provided for Add to Cart events
eventData.currency = currency;
}
flashy(eventType, eventData);
}
getItemIds(obj) {
const ids = [];
for (const key in obj) {
if (obj.hasOwnProperty(key) && typeof obj[key] === 'object' && obj[key] !== null && 'id' in obj[key]) {
ids.push(obj[key].id);
}
}
return ids;
}
getItemId(globalId) {
return globalId.split('/').pop();
}
// Initialize the recommendations display
init() {
this.displayProducts();
}
}
</script>
<script>
window.addEventListener('onFlashy', function() {
(new FlashyProductRecommendations(18880)).init();
});
</script>
כאשר נרצה להכניס את המוצרים למיקום מסויים נשתמש בקוד הבא:
<script>
window.addEventListener('onFlashy', function() {
(new FlashyProductRecommendations(__WEBLAYER_ID__)).init();
});
</script>