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

Stripe支付链接创建失败报错排查及版本查询求助

问题解析与解决方案

一、报错原因与代码修正

这个报错是代码逻辑与传入的JSON结构不匹配导致的,和Stripe API内部无关,具体问题点如下:

  1. line_items读取错误
    传入的JSON里line_items是单个对象,但代码里用data.line_items[0].price尝试读取数组的第一个元素,而data.line_items并不是数组,所以data.line_items[0]是undefined,访问price时触发报错。同时Stripe Payment Links API要求line_items为数组格式,建议统一成数组结构。

  2. after_completion参数拼接错误
    代码里写的after_completion[1][confirmation]完全不符合API要求,Stripe的参数应该是after_completion[type],而且传入的after_completion是对象而非数组,用索引访问也是错误的。

修正后的代码

async createPaymentlink(data) {
  try {
    const params = new URLSearchParams();
    // 兼容单个对象或数组的line_items,优先按数组处理
    const targetLineItem = Array.isArray(data.line_items) ? data.line_items[0] : data.line_items;
    params.append('line_items[0][price]', targetLineItem.price);
    params.append('line_items[0][quantity]', targetLineItem.quantity);
    // 修正after_completion参数格式
    params.append('after_completion[type]', data.after_completion.type);

    // 补充完整的Stripe Payment Links API地址
    const response = await fetch('https://api.stripe.com/v1/payment_links', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: params
    });
    // 解析返回的JSON数据(原代码返回的是Response对象,无法直接拿到业务数据)
    const responseData = await response.json();
    return { data: responseData };
  } catch (err) {
    return { error: err.message };
  }
}

修正后的JSON请求体

{
  "line_items": [
    {
      "price": "price_1PtUNVA15zK6SDK7f0llFJ3v",
      "quantity": 1
    }
  ],
  "after_completion": {
    "type": "confirmation"
  }
}

如果不想修改JSON结构,也可以把代码里的data.line_items[0].price改成data.line_items.price,但更推荐按数组格式传参,方便后续添加多个商品项。

二、查询Stripe版本的方法

如果是通过npm安装的Stripe SDK,有两种方式查询版本:

  • 命令行方式:在项目根目录执行
    # 查看详细依赖树里的Stripe版本
    npm list stripe
    # 或者直接从package.json里提取版本
    grep stripe package.json
    
  • 代码方式:在NodeJS代码中打印版本
    const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
    console.log('当前Stripe版本:', stripe.VERSION);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:38:16