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

Asp.net Core MVC集成Square .NET Web Payments报Tokenization处理中错误

解决ASP.NET Core MVC中Square Web Payments Tokenization重复请求错误

以下是针对你遇到的Tokenization has failed,the tokenization request is already in process错误的具体排查和修复方案:

1. 阻止按钮重复点击触发多次请求

MVC视图中按钮点击事件可能被重复绑定,或者用户快速点击导致多次发起tokenization请求。在触发支付逻辑时立即禁用按钮,错误时恢复:

document.getElementById('pay-btn').addEventListener('click', async function(e) {
  e.preventDefault();
  this.disabled = true; // 禁用按钮防止重复提交
  
  try {
    const tokenResult = await square.paymentRequest.cardTokenize();
    if (tokenResult.status === 'OK') {
      // 将token写入隐藏字段并提交表单
      document.getElementById('cardToken').value = tokenResult.token;
      document.getElementById('payment-form').submit();
    } else {
      throw new Error(tokenResult.errorMessage);
    }
  } catch (err) {
    this.disabled = false; // 错误时重新启用按钮
    alert(err.message);
  }
});

2. 确保Square SDK只初始化一次

在MVC布局页或视图中,避免因局部视图渲染重复加载Square脚本或重复初始化SDK:

<script src="https://sandbox.web.squarecdn.com/v1/square.js"></script>
<script>
  // 仅在未初始化时创建Square实例
  if (!window.squareInstance) {
    window.squareInstance = new Square({
      applicationId: '@Configuration["Square:ApplicationId"]',
      locationId: '@Configuration["Square:LocationId"]'
    });
  }
</script>

3. 规范表单提交的异步流程

确保token生成完成后再发起后端请求,避免并行触发导致的冲突:

async function processPayment() {
  const paymentRequest = window.squareInstance.paymentRequest({
    countryCode: 'US',
    currencyCode: 'USD',
    total: { amount: '15.00', label: 'Order Total' }
  });

  const tokenizeResult = await paymentRequest.cardTokenize();
  if (tokenizeResult.status !== 'OK') {
    console.error(tokenizeResult.errorMessage);
    return;
  }

  // 仅在token生成成功后调用后端接口
  await fetch('/Checkout/CompletePayment', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token: tokenizeResult.token, locationId: '@Configuration["Square:LocationId"]' })
  });
}

4. 验证后端Square客户端配置

确保ASP.NET Core中Square客户端使用正确的环境和配置,避免环境不匹配导致的隐性错误:

builder.Services.AddSingleton<SquareClient>(sp =>
{
  var config = sp.GetRequiredService<IConfiguration>();
  return new SquareClient.Builder()
    .AccessToken(config["Square:AccessToken"])
    .Environment(Square.Environment.Sandbox) // 测试用沙箱,生产切换为Production
    .Build();
});

5. 排查浏览器端重复请求

打开浏览器开发者工具(F12)的Network标签,检查是否有多次POST /v1/paymentMethods请求。若存在,检查视图中是否重复绑定了点击/提交事件,可使用once: true确保事件仅触发一次:

document.getElementById('pay-btn').addEventListener('click', processPayment, { once: true });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:33:27