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

如何在Strapi CMS中集成Square支付网关?已尝试多法未成功

在Strapi CMS中集成Square支付网关的实操步骤

1. 准备Square开发者凭证

  • 登录Square开发者平台创建应用,获取沙盒/生产环境的ACCESS_TOKEN和LOCATION_ID,优先用沙盒环境测试。
  • 安装Square Node.js SDK:
    npm install square
    # 或 yarn add square
    

2. 编写Strapi支付服务(核心逻辑)

在Strapi项目的./src/api/payment/services/payment.js创建自定义服务,封装Square支付逻辑:

const { Client, Environment } = require('square');

// 初始化Square客户端
const squareClient = new Client({
  accessToken: process.env.SQUARE_ACCESS_TOKEN,
  environment: process.env.SQUARE_ENVIRONMENT === 'production' ? Environment.Production : Environment.Sandbox,
});

module.exports = {
  /**
   * 创建Square支付
   * @param {number} amount 支付金额(单位:分,如100代表1美元)
   * @param {string} currency 货币代码,如"USD"
   * @param {string} sourceId 前端生成的支付token
   * @returns {Promise<Object>} 支付结果
   */
  async createPayment(amount, currency, sourceId) {
    try {
      const { result } = await squareClient.paymentsApi.createPayment({
        sourceId,
        amountMoney: { amount, currency },
        locationId: process.env.SQUARE_LOCATION_ID,
        idempotencyKey: Date.now().toString(), // 防止重复提交
      });
      return result.payment;
    } catch (error) {
      throw new Error(error.message);
    }
  },
};

3. 配置环境变量

在项目根目录的.env文件中添加Square凭证:

SQUARE_ACCESS_TOKEN=你的沙盒/生产access token
SQUARE_LOCATION_ID=你的location id
SQUARE_ENVIRONMENT=sandbox # 生产环境改为production

4. 创建支付API端点

编写控制器

在./src/api/payment/controllers/payment.js中创建处理支付请求的控制器:

const { createPayment } = require('../services/payment');

module.exports = {
  async processPayment(ctx) {
    try {
      const { amount, currency, sourceId } = ctx.request.body;
      const payment = await createPayment(amount, currency, sourceId);
      ctx.send({ success: true, payment });
    } catch (error) {
      ctx.badRequest('支付处理失败', { error: error.message });
    }
  },
};

配置路由

在./src/api/payment/routes/payment.js中注册支付接口:

module.exports = {
  routes: [
    {
      method: 'POST',
      path: '/payments/process',
      handler: 'payment.processPayment',
      config: {
        policies: [], // 根据需求添加权限验证策略(如用户认证)
      },
    },
  ],
};

5. 前端集成Square支付表单

前端使用Square Web Payments SDK生成支付token(sourceId),示例代码:

<div id="card-container"></div>
<button id="pay-button">确认支付</button>

<script src="https://sandbox.web.squarecdn.com/v1/square.js"></script>
<script>
  const squareAppId = '你的Square应用ID';
  const squareLocationId = '你的location id';

  async function initCardPayment() {
    const payments = Square.payments(squareAppId, squareLocationId);
    const card = await payments.card();
    await card.attach('#card-container');

    document.getElementById('pay-button').addEventListener('click', async () => {
      try {
        const tokenResult = await card.tokenize();
        if (tokenResult.status === 'OK') {
          // 调用Strapi支付接口
          const response = await fetch('/api/payments/process', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              amount: 100, // 示例:1美元
              currency: 'USD',
              sourceId: tokenResult.token
            })
          });
          const data = await response.json();
          console.log('支付成功:', data);
        } else {
          console.error('Token生成失败:', tokenResult.errors);
        }
      } catch (err) {
        console.error('支付出错:', err);
      }
    });
  }

  initCardPayment();
</script>

6. 常见问题排查

  • 版本兼容:确保Node.js版本符合Strapi要求(v4需16+),Square SDK版本无冲突。
  • 测试卡号:沙盒环境使用Square官方测试卡,如4111 1111 1111 1111(过期日期选未来任意时间,CVV填任意3位)。
  • 日志排查:支付失败时查看Square开发者平台的交易日志,定位具体错误(如金额格式错误、权限不足)。
  • 环境变量:确认Strapi启动时已正确加载.env中的凭证,可在服务中打印process.env验证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:50:40