上次實作了撈取假資料的互動
現在來嘗試撈真的商品資料
我本以為會很簡單 因為商品資料都是公開的不是嗎?
卻發現其實 shopify 沒有很歡迎外部去撈店家的商品資料
所以 其實需要 app 授權
在 toml 檔案裡面 remix 預設是
scopes = "write_products"
要改成
scopes = "write_products,unauthenticated_read_product_listings"
如果用我的架構 就是 shopify.app.development.toml
shopify.app.production.toml
兩個檔案都要修改
而且都要部署到 shopify 喔
在跑 npm run dev 跟 npm run deploy 的時候要 tweak 一下
加好權限之後 要去 admin panel 打開 app 會看到 shopify 跳通知 要求更新授權內容
以下是我實際取得商品資料的範例
import { unauthenticated } from "../shopify.server";
async function fetchRecommendationsFromDB({ recommendationSetId }) {
const { storefront } = await unauthenticated.storefront(
'akawaselect.myshopify.com'
);
const ids = [
"gid://shopify/Product/7583115968595",
"gid://shopify/Product/7583114526803"
];
const response = await storefront.graphql(
`#graphql
query GetProducts($ids: [ID!]!) {
nodes(ids: $ids) {
... on Product {
id
title
handle
featuredImage {
url
}
}
}
}`,
{
variables: { ids }
}
);
const data = await response.json();
const nodes = data.data.nodes;
let recommendations = nodes.map((node) => {
return {
title: node.title,
override_price: "100", // 假設價格,實際應從資料庫或其他來源獲取
image: node.featuredImage ? node.featuredImage.url : "https://cdn.shopify.com/s/files/1/0533/2089/files/placeholder-images-image_large.png",
};
});
return recommendations;
}
出來的成果如圖,非常成功!
老話一句 我覺得這流程開發起來 門檻很高!
😂