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

如何在SweetAlert2弹窗中集成Cloudflare Turnstile验证码(PHP环境)

在SweetAlert2中集成Cloudflare Turnstile(PHP后端)

前端实现步骤

  1. 引入Cloudflare Turnstile脚本
    在HTML页面的<head>中添加Turnstile官方脚本:

    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
    
  2. 在SweetAlert2弹窗中嵌入验证组件
    通过SweetAlert2的html选项插入空容器,利用didOpen回调在弹窗加载完成后渲染Turnstile,同时监听验证完成事件获取token:

    let turnstileToken = '';
    
    Swal.fire({
      title: '请完成验证',
      html: '<div id="turnstile-container"></div>',
      showCancelButton: true,
      confirmButtonText: '提交',
      preConfirm: () => {
        if (!turnstileToken) {
          Swal.showValidationMessage('请先完成验证');
          return false;
        }
        // 将token提交到后端验证
        return fetch('/verify-turnstile.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: `token=${turnstileToken}`
        })
        .then(res => res.json())
        .then(data => {
          if (!data.success) throw new Error('验证失败,请重试');
          return data;
        });
      },
      didOpen: () => {
        // 渲染Turnstile验证组件
        window.turnstile.render('#turnstile-container', {
          sitekey: '你的站点KEY', // 替换为Cloudflare控制台生成的站点密钥
          callback: (token) => {
            turnstileToken = token;
          },
        });
      }
    }).then(result => {
      if (result.isConfirmed) {
        Swal.fire('验证成功!', '', 'success');
        // 处理验证通过后的业务逻辑
      }
    });
    

后端PHP验证逻辑

创建verify-turnstile.php文件,接收前端token并调用Cloudflare验证接口校验:

<?php
// 替换为Cloudflare控制台生成的秘密密钥
$secretKey = '你的秘密KEY';
$token = $_POST['token'] ?? '';

if (empty($token)) {
  echo json_encode(['success' => false, 'error' => '缺少验证token']);
  exit;
}

// 调用Cloudflare验证API
$verifyUrl = 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
$postData = http_build_query([
  'secret' => $secretKey,
  'response' => $token,
  'remoteip' => $_SERVER['REMOTE_ADDR'] // 可选,传入用户IP提升验证精度
]);

$options = [
  'http' => [
    'method' => 'POST',
    'header' => "Content-type: application/x-www-form-urlencoded\r\n",
    'content' => $postData
  ]
];
$context = stream_context_create($options);
$verifyResult = json_decode(file_get_contents($verifyUrl, false, $context), true);

if ($verifyResult['success']) {
  // 验证通过,执行后续业务逻辑
  echo json_encode(['success' => true]);
} else {
  // 验证失败,返回错误信息
  echo json_encode([
    'success' => false,
    'error' => '验证失败',
    'errorCodes' => $verifyResult['error-codes'] ?? []
  ]);
}
?>

关键注意事项

  • 必须替换代码中的你的站点KEY和你的秘密KEY为Cloudflare控制台生成的对应密钥
  • 依赖didOpen回调确保Turnstile容器已挂载到DOM后再渲染组件,避免渲染失败
  • 后端验证时传入用户IP可增强验证安全性
  • 若前端token获取失败,可检查Turnstile脚本是否加载完成,或站点密钥是否正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 23:55:20