你有几个问题。在回答之前,重要的是要澄清我从您的措辞和示例代码中假设的一些误解。有 3 种类型Shopify 应用程序 https://shopify.dev/concepts/apps.
- Public
- Custom
- Private
因此,如果您正在构建私有应用程序,则提供的代码将无法用于创建产品,因为私有应用程序使用基本身份验证,而公共和自定义应用程序使用 OAuth 2.0 管理身份验证。
我在我的项目中使用同构 Fetch,它应该可以在服务器和
客户端。
尽管它适用于服务器和客户端,但请勿从客户端调用 Shopify API,因为这会暴露您的私人应用程序凭据。
要实现您想要做的事情,您需要修改 React App 以及后端代码。
- 为 Button 添加事件监听器
- 向后端服务器发送POST请求
- 通过 API 在 Shopify 上创建产品
- 使用上一步返回的 ID 将产品添加到购物车
- 返回购物车 URL 作为响应
React 中的示例代码如下所示
function Product() {
const addProduct = async () => {
const cart = await fetch("/your-end-point", {
method: "post",
body: JSON.stringify({
// add product params
}),
});
};
return <button onClick={addProduct}>Add Product</button>;
}
ReactDOM.render(<Product />, document.getElementById("root"));
然后在 Node.js 应用程序中处理 Shopify API 部分。我建议使用而不是使用 fetchShopify 的官方 Node.js 模块 https://www.npmjs.com/package/shopify-api-node.
示例代码如下所示
const Shopify = require("shopify-api-node");
router.post("/your-end-point", async (req, res) => {
try {
const shopify = new Shopify({
shopName: "your-shop-name",
apiKey: "your-api-key",
password: "your-app-password",
});
const product = await shopify.product.create(req.body);
// use product ID from previous request
const checkout = await shopify.checkout.create({
/*checkout params */
});
res.status(200).send(checkout);
} catch (ex) {
console.log(ex);
}
});