You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建仅作用于单个页面、支持服务器端API调用的Shopify应用?

解决方案指导

核心思路

采用「Shopify自定义应用(后端API)+ 主题单页面嵌入」的组合方案,既实现服务器端隐藏第三方API调用,又仅在指定页面生效。

第一步:创建Shopify自定义应用(带后端)

  • 用Shopify CLI初始化一个基于Node.js的自定义应用(新手友好),执行命令:
    shopify app init my-frontend-app --template node
    
  • 完成初始化后,在Shopify后台配置应用权限:只需开启基础的前台访问权限,若需读取店铺基础数据,可额外申请Storefront API权限。
  • 安装应用到目标店铺,获取应用的公网访问域名(本地开发可用shopify app tunnel start生成临时隧道域名)。

第二步:搭建后端API路由(隐藏第三方API调用)

在应用的Express后端中,新增一个处理第三方API调用的接口,示例代码:

const express = require('express');
const cors = require('cors');
const app = express();

// 配置CORS,允许目标Shopify店铺域名访问
app.use(cors({ origin: 'https://你的店铺域名.myshopify.com' }));
app.use(express.json());

// 处理第三方API调用的接口
app.post('/api/third-party-fetch', async (req, res) => {
  const userInput = req.body.userInput;
  try {
    // 服务器端发起第三方API请求
    const thirdPartyRes = await fetch('https://第三方API地址', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ input: userInput })
    });
    const result = await thirdPartyRes.json();
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: '请求第三方服务失败' });
  }
});

app.listen(process.env.PORT || 3000);

第三步:在主题单页面嵌入前端交互

  • 进入Shopify后台「在线商店」→「主题」→ 目标主题「操作」→「编辑代码」。
  • 创建新页面模板(如page.custom-app.liquid),或编辑现有页面模板,嵌入以下代码实现用户输入和API调用:
<div class="custom-app-section">
  <input type="text" id="userInput" placeholder="请输入内容" />
  <button id="submitBtn">提交查询</button>
  <div id="resultDisplay" class="result-area"></div>
</div>

<script>
  document.getElementById('submitBtn').addEventListener('click', async () => {
    const inputVal = document.getElementById('userInput').value.trim();
    const resultEl = document.getElementById('resultDisplay');
    if (!inputVal) return;

    resultEl.textContent = '查询中...';
    try {
      // 调用自定义应用的后端API
      const res = await fetch('https://你的应用域名/api/third-party-fetch', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userInput: inputVal })
      });
      const data = await res.json();
      resultEl.textContent = `查询结果:${JSON.stringify(data)}`;
    } catch (err) {
      resultEl.textContent = '查询失败,请重试';
    }
  });
</script>
  • 在Shopify后台创建新页面,选择刚才的custom-app模板发布,该页面将单独加载你的自定义功能,其他页面不受影响。

第四步:部署与测试

  • 将自定义应用部署到Shopify App Platform或第三方平台(如Vercel、Heroku),确保后端API可公网访问。
  • 访问店铺中创建的自定义页面,测试输入提交和结果返回流程,验证第三方API调用是否仅在服务器端执行。

内容的提问来源于stack exchange,提问作者codePie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 01:30:21