You need to enable JavaScript to run this app. Angular对接Stripe云函数报错:Customer|DeletedCustomer无sources属性
优惠活动
大模型
产品
解决方案
定价
更多

Angular对接Stripe云函数报错:Customer|DeletedCustomer无sources属性

报错根因

该报错是TypeScript静态类型检查的拦截,并非运行时执行错误:

  • Stripe Node SDK 中 stripe.customers.retrieve() 的官方返回类型被定义为 Customer | DeletedCustomer 联合类型
  • 其中 DeletedCustomer 仅包含 deleted、id、object 三个基础字段,不存在 sources 属性
  • 只要不对联合类型做收窄,直接访问 customer.sources 就会在编译阶段抛出对应错误,哪怕实际运行时拿到的是正常客户对象
修复方案
  • 第一步:在getOrCreateCustomer函数内对retrieve的返回值做删除状态校验,完成类型收窄,同时适配新版SDK的字段拉取逻辑
    将原有逻辑替换为带校验的版本:
    export const getOrCreateCustomer = async (uid: string) => {
      const user = await getUser(uid);
      const customerId = user && user.stripeCustomerId;
      if (!customerId) {
        return createCustomer(uid);
      }
      // 新版SDK需要主动声明拉取sources字段,避免运行时取不到值
      const customer = await stripe.customers.retrieve(customerId, {
        expand: ['sources']
      });
      // 过滤DeletedCustomer类型,完成类型收窄
      if (customer.deleted) {
        throw new Error(`关联的Stripe客户${customerId}已被删除,无法绑定支付来源`);
      }
      return customer;
    };
    
  • 第二步:完成上述调整后,函数的返回类型会被TypeScript自动收窄为纯Customer类型,此时回到attachSource函数里调用customer.sources.data就不会再触发类型报错
  • 第三步:额外注意事项:新版Stripe SDK已逐步引导使用Payment Methods替代旧的Source对象,如果后续遇到createSource的废弃提示,可对应替换为Payment Method的绑定逻辑,现有类型校验的部分不需要改动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.03 04:06:05