NuxtJS v3集成Mollie支付报错:Cannot read properties of undefined (reading 'custom')
解决Nuxt3集成Mollie API出现的"Cannot read properties of undefined (reading 'custom')"错误
核心问题分析
这个错误根源在于你直接在前端组件中运行Mollie的API客户端:
@mollie/api-client是为Node.js环境设计的,前端浏览器环境缺少部分依赖或API支持,导致客户端内部处理响应时触发未定义属性的报错。- 更重要的是,前端硬编码并暴露API密钥存在严重安全风险,恶意用户可直接获取密钥操作支付。
解决方案:将Mollie调用移至Nuxt服务器端
把支付创建逻辑放到Nuxt的服务器路由中,前端通过调用内部API获取结账URL,具体步骤如下:
- 创建服务器端API路由
在项目根目录的server/api文件夹下新建mollie-payment.ts文件:
import createMollieClient from "@mollie/api-client"; export default defineEventHandler(async (event) => { // 建议从环境变量读取API密钥,避免硬编码 const mollieClient = createMollieClient({ apiKey: process.env.MOLLIE_API_KEY || "test_WpjrT**********JTV8j4zDy", }); try { const payment = await mollieClient.payments.create({ amount: { value: "10.00", currency: "EUR", }, description: "My first API payment", redirectUrl: "https://url.com/order/123456", webhookUrl: "https://url.com/webhook", }); return { checkoutUrl: payment.getCheckoutUrl() }; } catch (error) { console.error("创建支付失败:", error); throw createError({ statusCode: 500, statusMessage: "支付创建失败" }); } });
- 前端组件调用服务器API
修改你的Product组件代码,通过useFetch调用刚才创建的内部API:
export default defineComponent({ name: "Product", async setup() { const { data: paymentData } = await useFetch("/api/mollie-payment"); return { redUrl: paymentData.value?.checkoutUrl }; }, })
额外排查点
- 确保环境变量
MOLLIE_API_KEY已正确配置在项目的.env文件中,服务器端能正常读取。 - 直接访问
http://localhost:4444/api/mollie-payment,检查服务器API是否能返回正确的结账URL,确认Mollie API调用本身无问题。 - 若仍报错,查看服务器端日志,确认Mollie返回的支付对象结构是否完整,
getCheckoutUrl()依赖的_links.checkout字段是否存在。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

