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

Rails 7集成Stripe支付报错:Failed to execute 'postMessage' on 'DOMWindow'

Rails 7集成Stripe支付表单不显示的解决方案

错误信息

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://js.stripe.com') does not match the recipient window's origin ('http://localhost:3000').


问题分析与修复步骤

1. 修复JavaScript笔误(核心问题)

你的application.js中存在方法调用错误:将Stripe Elements的挂载方法mount()误写为amount(),这直接导致卡片组件无法渲染到页面上。

修改后的application.js代码:

document.addEventListener("turbo:load", () => {
  const public_key = document.querySelector("meta[name='stripe-key']").getAttribute("content")
  const stripe = Stripe(public_key)
  const form = document.getElementById("payment-form")
  
  // 初始化Elements时传入必要配置
  const elements = stripe.elements({
    clientSecret: form.dataset.paymentIntentId,
    origin: "http://localhost:3000" // 解决origin不匹配问题
  })
  
  const card = elements.create('card')
  card.mount('#card-element') // 修正为正确的mount方法

  card.addEventListener("change", (event) => {
    var displayError = document.getElementById('card-errors')
    if (event.error) {
      displayError.textContent = event.error.message
    } else {
      displayError.textContent = ''
    }
  })
})

2. 解决Origin跨域不匹配问题

Stripe Elements在HTTP环境(如http://localhost:3000)下会触发跨域验证错误,有两种有效解决方式:

  • 方式一:使用HTTPS启动本地服务
    生成本地SSL证书后,通过HTTPS启动Rails服务器:
    bin/rails server -b 'ssl://localhost:3000?key=config/localhost.key&cert=config/localhost.crt'
    
    可借助rails-ssl-certificate gem快速生成本地证书。
  • 方式二:初始化Elements时指定允许的Origin
    如上述修改后的代码所示,在stripe.elements()配置中添加origin: "http://localhost:3000",明确告知Stripe允许当前域名的请求。

3. 确保Stripe JS正确加载

Rails 7默认使用Turbo,需避免SDK加载受Turbo影响:

  • 直接在视图中引入:
    <%= javascript_include_tag "https://js.stripe.com/v3/", "data-turbo-track": "reload" %>
    
  • 或通过Importmap配置(config/importmap.rb):
    pin "stripe", to: "https://js.stripe.com/v3/"
    
    然后在application.js顶部添加:
    import Stripe from "stripe"
    

验证修改

重启Rails服务器后刷新页面,检查浏览器控制台是否还有错误,Stripe卡片表单应能正常渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 03:46:08