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

Cloudflare Worker中调用stripe.paymentIntents.create出现Stripe连接错误如何解决

问题原因

你遇到的连接报错核心是标准Node.js版Stripe SDK与Cloudflare Worker运行环境不兼容:

  • Cloudflare Worker是Edge Runtime,不支持Node.js原生的http/https网络模块,标准Stripe SDK依赖上述模块发起请求,所以无法建立与Stripe服务器的连接
  • Worker原生不支持CommonJS的require语法,你的导入方式本身就不符合Worker的运行规范
修复方案

方案1:使用Stripe官方Edge兼容版SDK

最新版stripe包已适配Edge Runtime,你需要调整导入和初始化逻辑,同时把密钥存到Worker环境变量(不要硬编码在代码中):

// 先在package.json中安装最新版stripe,使用ES模块导入
import Stripe from 'stripe';

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  // 从Worker环境变量读取Stripe密钥,不要硬编码
  const stripe = new Stripe(STRIPE_SECRET_KEY, {
    apiVersion: '2024-06-20', // 替换为你使用的Stripe API版本
    httpClient: Stripe.createFetchHttpClient(), // 强制使用Fetch API发起请求
  });

  try {
    const paymentIntent = await stripe.paymentIntents.create({
      amount: 1000,
      currency: 'cad',
      payment_method_types: ['card'],
      receipt_email: 'jenny.rosen@example.com',
    });
    // 可返回paymentIntent的client_secret给前端调用
    return new Response(JSON.stringify({ clientSecret: paymentIntent.client_secret }), {
      headers: { 'Content-Type': 'application/json' },
    })
  } catch (e) {
    return new Response(JSON.stringify({ error: e.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    })
  }
}

方案2:直接用Fetch调用Stripe REST接口(更轻量)

如果不想引入完整SDK,可以直接用Worker原生的Fetch调用Stripe接口,无额外依赖:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  try {
    const paymentIntentRes = await fetch('https://api.stripe.com/v1/payment_intents', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${STRIPE_SECRET_KEY}`,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        amount: '1000',
        currency: 'cad',
        'payment_method_types[]': 'card',
        receipt_email: 'jenny.rosen@example.com',
      })
    });

    const paymentIntent = await paymentIntentRes.json();
    if (!paymentIntentRes.ok) throw new Error(paymentIntent.error.message);

    return new Response(JSON.stringify({ clientSecret: paymentIntent.client_secret }), {
      headers: { 'Content-Type': 'application/json' },
    })
  } catch (e) {
    return new Response(JSON.stringify({ error: e.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' },
    })
  }
}
注意事项
  • 必须把Stripe密钥配置为Worker的加密环境变量,禁止硬编码在代码中避免泄露
  • 如果你要从前端直接请求这个Worker接口,需要额外配置CORS响应头处理跨域问题
  • 必须添加try/catch捕获异步请求错误,避免未处理的异常直接抛出导致Worker返回500错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:06:07