// 生成二维码
document.getElementById('qrcode').innerHTML = '<img src='https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=' + encodeURIComponent('{$qr_url}') + ''>';

// 设置定时器,5分钟后停止轮询
setTimeout(stop, 300000);
function stop() {
  clearInterval(paid_timeout);
}

// 每3秒轮询一次,检测支付状态
var paid_timeout = setInterval(go, 3000);
function go() {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      var data = xhr.responseText;
      if (data.search(/<span\sclass=.paid.>/ ) != -1) {
        clearInterval(paid_timeout);
        alert('支付完成');
        window.location.href = '/cart.php?a=complete';
      }
    }
  };
  xhr.open('GET', window.location.href, true);
  xhr.send();
}

说明:

  1. 使用 document.getElementById('qrcode').innerHTML 将二维码图片嵌入到 qrcode 元素中。
  2. 使用 XMLHttpRequest 对象发送 AJAX 请求,每 3 秒轮询一次,检测支付状态。
  3. 使用 setTimeout 设置定时器,5 分钟后停止轮询,避免长时间占用资源。
  4. 如果支付成功,页面将跳转到 /cart.php?a=complete 页面。

注意:

  • {$qr_url} 需要替换成实际的二维码链接。
  • 代码中使用 \s 匹配空格,避免正则表达式错误。
  • 代码中的 alert 可以根据实际情况进行调整,例如使用其他提示方式。

更多参考:

使用原生 JavaScript 生成二维码并检测支付状态

原文地址: http://www.cveoy.top/t/topic/i7tB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录