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

如何为Stripe配置Content-Security-Policy并解决内联脚本拦截报错?

修复Stripe集成时的Content Security Policy错误

1. 先修正配置的语法错误

你提供的CSP配置存在严重语法问题:把<script>标签写进了meta标签的content属性里,且属性引号未闭合,这直接导致配置无效。正确的写法是将meta标签和script标签分开:

<meta http-equiv="Content-Security-Policy" 
      content="script-src 'self' https://js.stripe.com; style-src 'self' https://js.stripe.com; frame-src https://js.stripe.com https://hooks.stripe.com;">
<script type="text/javascript" src="https://js.stripe.com/v3/"></script>

2. 解决inline脚本被阻止的问题

错误提示明确是inline脚本被拦截,Stripe的部分功能(比如初始化代码、支付元素渲染)需要执行inline脚本,你需要根据环境选择对应的解决方案:

开发环境(localhost)临时方案

直接在script-src中添加'unsafe-inline'(仅开发环境使用,生产环境禁止):

<meta http-equiv="Content-Security-Policy" 
      content="script-src 'self' https://js.stripe.com 'unsafe-inline'; style-src 'self' https://js.stripe.com; frame-src https://js.stripe.com https://hooks.stripe.com;">

生产环境推荐方案

使用**nonce(随机数)**来安全允许指定的inline脚本:

  1. 生成一个随机的nonce值(建议服务器端每次请求生成唯一值)
  2. 在CSP规则中添加'nonce-你的随机值'
  3. 给所有需要执行的inline脚本标签添加nonce属性

示例代码:

<!-- 服务器端生成nonce值,这里用abc123示例 -->
<meta http-equiv="Content-Security-Policy" 
      content="script-src 'self' https://js.stripe.com 'nonce-abc123'; style-src 'self' https://js.stripe.com; frame-src https://js.stripe.com https://hooks.stripe.com;">

<!-- 引入Stripe脚本 -->
<script type="text/javascript" src="https://js.stripe.com/v3/"></script>

<!-- 带有nonce的Stripe初始化脚本 -->
<script nonce="abc123">
  const stripe = Stripe('你的Stripe公钥');
  // 后续Stripe相关代码
</script>

3. 检查Firefox开发者版的特殊设置

打开Firefox的about:config页面,搜索security.csp相关配置,确认没有启用强制严格CSP的自定义选项(比如security.csp.policy会覆盖页面配置),确保浏览器规则未干扰页面的CSP设置。

4. 排查服务器端CSP头冲突

如果页面的meta标签配置后仍无效,检查你的服务器是否发送了Content-Security-Policy响应头。当服务器和页面同时设置CSP时,服务器端的规则会优先生效,此时需要修改服务器的CSP配置,添加Stripe相关的域名和inline脚本允许规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:25:51