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

React中使用google-pay/button-react集成Square网关至Google Pay的咨询

问题解答

一、能否不借助网关在GooglePayButton中实现支付?

不行。Google Pay本身只是支付方式的采集工具,它仅负责收集用户的支付信息并返回支付令牌,不处理资金清算、交易路由等核心支付流程。必须依赖支付网关(比如Square、Stripe等)来完成后续的资金划转、订单处理等操作,没有网关的话,Google Pay返回的支付令牌无法被用来完成实际扣款。

二、Square网关获取Source ID的核心逻辑

Square的Source API是处理非卡片支付方式(包括Google Pay)的关键入口,获取Source ID必须通过以下步骤:

  1. 在Square开发者后台开启Google Pay支付权限,绑定正确的商户账号,确保应用配置合规。
  2. 前端通过Google Pay获取到**支付令牌(payment token)**后,将令牌发送到你的后端服务(禁止前端直接调用Square API,避免暴露密钥)。
  3. 后端调用Square的CreateSource API,将Google Pay令牌作为参数传入,请求成功即可得到Source ID。

三、使用google-pay/button-react集成Square + Google Pay的方案

1. 安装依赖

npm install @google-pay/button-react

2. 前端组件实现

import React from 'react';
import { GooglePayButton } from '@google-pay/button-react';

const GooglePaySquareIntegration = () => {
  const handlePaymentSuccess = async (paymentData) => {
    // 提取Google Pay返回的支付令牌
    const googlePayToken = paymentData.paymentMethodData.tokenizationData.token;
    
    try {
      // 发送令牌到后端请求Square Source ID
      const response = await fetch('/api/create-square-source', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          googlePayToken,
          amount: 100, // 金额,单位为最小货币单位(如美分)
          currency: 'USD'
        })
      });

      const data = await response.json();
      if (data.success) {
        // 获取到Source ID后,可调用Square Payment API完成扣款
        console.log('Square Source ID:', data.sourceId);
        // 这里添加订单确认等后续逻辑
      } else {
        throw new Error(data.error);
      }
    } catch (err) {
      console.error('获取Source ID失败:', err.message);
    }
  };

  return (
    <GooglePayButton
      environment="TEST" // 正式环境改为"PRODUCTION"
      paymentRequest={{
        apiVersion: 2,
        apiVersionMinor: 0,
        allowedPaymentMethods: [
          {
            type: 'CARD',
            parameters: {
              allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
              allowedCardNetworks: ['AMEX', 'DISCOVER', 'MASTERCARD', 'VISA']
            },
            tokenizationSpecification: {
              type: 'PAYMENT_GATEWAY',
              parameters: {
                gateway: 'square',
                gatewayMerchantId: '你的Square商户ID'
              }
            }
          }
        ],
        merchantInfo: {
          merchantId: '你的Google Pay商户ID', // 需在Google Pay控制台配置
          merchantName: '你的商户名称'
        },
        transactionInfo: {
          totalPriceStatus: 'FINAL',
          totalPriceLabel: '总计',
          totalPrice: '1.00', // 前端显示金额,对应后端最小单位金额
          currencyCode: 'USD'
        }
      }}
      onLoadPaymentData={handlePaymentSuccess}
    />
  );
};

export default GooglePaySquareIntegration;

3. 后端实现(Node.js示例)

const square = require('square');
const { v4: uuidv4 } = require('uuid');

// 初始化Square客户端
const client = new square.Client({
  accessToken: '你的Square访问令牌',
  environment: square.Environment.Sandbox // 正式环境改为Production
});

// 处理前端请求,创建Square Source
app.post('/api/create-square-source', async (req, res) => {
  const { googlePayToken, amount, currency } = req.body;

  try {
    const { result } = await client.paymentsApi.createSource({
      idempotencyKey: uuidv4(), // 幂等键,确保请求不重复执行
      source: {
        type: 'CARD',
        card: {
          nonce: googlePayToken // 传入Google Pay令牌
        }
      },
      amountMoney: {
        amount: amount,
        currency: currency
      }
    });

    res.json({
      success: true,
      sourceId: result.source.id
    });
  } catch (err) {
    res.json({
      success: false,
      error: err.message
    });
  }
});

4. 关键注意事项

  • 需在Square开发者后台完成Google Pay商户ID与Square商户ID的关联配置。
  • 测试阶段使用Square沙箱账号和Google Pay测试卡片,避免产生真实交易。
  • 正式上线前,将environment从TEST/Sandbox切换为PRODUCTION,并完成Google Pay和Square的生产环境审核。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:57:39