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

基于Square API的前端JavaScript实现订单、支付及客户创建咨询

前端实现Square支付、订单及客户创建方案

核心前提说明

Square官方不建议在前端直接调用需要私钥的API(比如订单、客户创建),因为私钥暴露会导致账户风险。但如果必须纯前端实现,需使用Square提供的**前端SDK(Square.js/Web Payments SDK)**处理支付,同时通过OAuth获取临时访问令牌来调用其他API(需注意令牌的安全存储)。


1. 集成Square Web Payments SDK(支付流程)

这是前端安全处理银行卡支付的唯一官方方式,替代你现有后端调用的逻辑:

步骤1:引入Square.js

在结账页面的<head>中添加:

<script src="https://sandbox.web.squarecdn.com/v1/square.js"></script>
<!-- 生产环境替换为:https://web.squarecdn.com/v1/square.js -->

步骤2:初始化支付表单

// 替换为你的Square应用ID(沙盒/生产)
const applicationId = 'YOUR_APPLICATION_ID';
const locationId = 'YOUR_LOCATION_ID';

async function initPaymentForm() {
  const payments = Square.payments(applicationId, locationId);
  
  // 创建银行卡支付组件
  const card = await payments.card();
  await card.attach('#card-container'); // 绑定到页面的银行卡输入容器
  
  // 监听表单提交事件
  document.getElementById('checkout-form').addEventListener('submit', async (event) => {
    event.preventDefault();
    
    try {
      // 生成支付令牌(sourceId)
      const result = await card.tokenize();
      if (result.status === 'OK') {
        // 调用Square Payments API创建支付
        await createSquarePayment(result.token);
        // 支付成功后创建订单和客户
        const customerId = await createSquareCustomer();
        await createSquareOrder(customerId);
        alert('支付、订单、客户创建成功');
      } else {
        throw new Error(result.errors[0].message);
      }
    } catch (error) {
      console.error('支付失败:', error);
    }
  });
}

// 页面加载完成后初始化
window.addEventListener('load', initPaymentForm);

步骤3:前端直接创建支付(需认证)

这里需要使用Square的OAuth访问令牌(不能用私钥),示例代码:

async function createSquarePayment(token) {
  const paymentData = {
    amount_money: {
      amount: 100, // 单位:分,比如1美元=100
      currency: 'USD' // 替换为你的货币类型,比如CNY
    },
    source_id: token,
    location_id: locationId,
    idempotency_key: crypto.randomUUID() // 生成唯一幂等键,防止重复支付
  };

  const response = await fetch('https://connect.squareupsandbox.com/v2/payments', {
    // 生产环境替换为:https://connect.squareup.com/v2/payments
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer YOUR_OAUTH_ACCESS_TOKEN` // 替换为OAuth访问令牌
    },
    body: JSON.stringify(paymentData)
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.errors[0].message);
  }
  return response.json();
}

2. 前端创建Square客户

使用Square Customers API,同样需要OAuth访问令牌:

async function createSquareCustomer() {
  // 从表单获取客户信息
  const customerData = {
    given_name: document.getElementById('first-name').value,
    family_name: document.getElementById('last-name').value,
    email_address: document.getElementById('email').value,
    phone_number: document.getElementById('phone').value
  };

  const response = await fetch('https://connect.squareupsandbox.com/v2/customers', {
    // 生产环境替换为:https://connect.squareup.com/v2/customers
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer YOUR_OAUTH_ACCESS_TOKEN`
    },
    body: JSON.stringify(customerData)
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.errors[0].message);
  }
  const result = await response.json();
  return result.customer.id; // 返回创建的客户ID,用于关联订单
}

3. 前端创建Square订单

关联已创建的客户ID,使用Orders API:

async function createSquareOrder(customerId) {
  // 从购物车获取商品信息,示例结构
  const lineItems = [
    {
      name: '招牌汉堡',
      quantity: '1',
      base_price_money: {
        amount: 1500, // 15美元
        currency: 'USD'
      }
    }
  ];

  const orderData = {
    location_id: locationId,
    customer_id: customerId,
    line_items: lineItems,
    idempotency_key: crypto.randomUUID()
  };

  const response = await fetch('https://connect.squareupsandbox.com/v2/orders', {
    // 生产环境替换为:https://connect.squareup.com/v2/orders
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer YOUR_OAUTH_ACCESS_TOKEN`
    },
    body: JSON.stringify({ order: orderData })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.errors[0].message);
  }
  return response.json();
}

关键注意事项

  • OAuth访问令牌获取:需在Square开发者控制台创建OAuth应用,通过授权流程获取访问令牌(仅限你的店铺),绝对不能在前端代码中硬编码私钥。
  • 沙盒测试:先使用沙盒环境测试,确保所有流程正常后再切换到生产环境。
  • 风险提示:前端直接调用Square API存在令牌泄露风险,建议仅在内部使用场景采用,公网环境优先使用后端中转。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:59:57