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

集成2checkout-nodejs时遇2Checkout API JSON解析错误求助

解决2checkout-nodejs集成时的JSON解析错误

以下是针对你遇到的Error: Error parsing JSON response from 2Checkout API错误的具体修复步骤:

  • 参数传递格式错误
    tco.checkout.authorize方法要求直接传入JavaScript对象,不需要手动转为JSON字符串。你当前使用JSON.stringify(params)传递参数,会导致API接收到格式错误的请求,返回非预期的响应内容,进而触发JSON解析失败。
    修正后的调用代码(回调方式):

    tco.checkout.authorize(params, (error, data) => {
      if (error) {
        console.log({ error });
        res.status(400).json({ error: error.message, data });
      } else {
        // 处理支付成功逻辑
      }
    });
    

    若使用async/await(Promise方式):

    try {
      const data = await tco.checkout.authorize(params);
      // 处理支付成功逻辑
    } catch (error) {
      console.log({ error });
      res.status(400).json({ error: error.message, data: null });
    }
    
  • 初始化配置重复冲突
    初始化代码中同时设置了secretKey和secretWord,这两个配置项重复冗余,根据2checkout-nodejs的规范,只需保留secretWord(对应后台设置的Secret Word)即可,删除多余的secretKey配置:

    const tco = new Twocheckout({   
      apiUser: "my-username",   
      apiPass: "my-password",   
      sellerId: "my-seller-id",   
      privateKey: "my-private-key",   
      secretWord: "secret-word",   
      demo: false,   
      sandbox: true, 
    });
    
  • 参数占位符未替换为有效值
    你的请求参数中存在多个无效占位符(如li_0_price: "price"、qty: "quantity"、currency_code: "currency code"),这些值会导致API返回非合法JSON的错误响应,必须替换为真实有效的内容:

    • li_0_price:改为数字格式的字符串,例如"19.99"
    • qty:改为数字字符串,例如"1"
    • currency_code:改为标准货币代码,例如"USD"或"EUR"
  • HTTP状态码使用错误
    错误场景下返回301(重定向状态码)不符合HTTP规范,应改为400(请求参数错误)或500(服务器内部错误)类的状态码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:17:30