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

使用原生Fetch调用Stripe API(暂停收款)返回400错误码的问题排查

问题分析与修复方案

你的代码有两个关键问题导致了400错误,我帮你拆解一下:

  • 无效的授权凭证:你把username变量的赋值代码注释掉了,这会让Buffer.from(${username}:)里的username变成undefined,生成的Base64授权字符串完全无效。Stripe API要求你用测试/生产模式的API密钥作为Basic Auth的用户名(密码部分留空即可),所以必须确保这个变量正确赋值为你的Stripe密钥。
  • 参数字段拼写错误:Stripe的API字段采用美式英语拼写,你写的pause_collection[behaviour]是英式拼写,正确的字段名应该是pause_collection[behavior]。这个拼写错误会让Stripe无法识别你要设置的暂停收款行为,直接返回400请求错误。

下面是修正后的完整代码:

import fetch from 'node-fetch';

test("y", async () => {
  const username = "rk_test_xyz"; // 确保这里是你的有效Stripe测试API密钥
  const encoded = Buffer.from(`${username}:`, 'utf-8').toString('base64');
  const params = new URLSearchParams();
  params.append('pause_collection[behavior]', 'void'); // 修正拼写为美式behavior
  const response = await fetch('https://api.stripe.com/v1/subscriptions/sub_1LFkzDH2RPqITCMjvjz9RCOJ', {
    method: 'POST',
    body: params,
    headers: {
      'Authorization': `Basic ${encoded}`,
      "Content-type": `application/x-www-form-urlencoded`
    }
  });
  const status = response.status;
  const responseBody = await response.json(); // 建议打印响应体,能看到Stripe更详细的错误信息
  console.log({status, responseBody});
})

另外建议你在请求后打印响应的JSON内容,Stripe的400错误通常会返回具体的错误原因(比如哪个参数无效),这能帮你更快定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 20:57:41