使用原生 JavaScript 生成二维码并检测支付状态
// 生成二维码
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();
}
说明:
- 使用
document.getElementById('qrcode').innerHTML将二维码图片嵌入到qrcode元素中。 - 使用
XMLHttpRequest对象发送 AJAX 请求,每 3 秒轮询一次,检测支付状态。 - 使用
setTimeout设置定时器,5 分钟后停止轮询,避免长时间占用资源。 - 如果支付成功,页面将跳转到
/cart.php?a=complete页面。
注意:
{$qr_url}需要替换成实际的二维码链接。- 代码中使用
\s匹配空格,避免正则表达式错误。 - 代码中的
alert可以根据实际情况进行调整,例如使用其他提示方式。
更多参考:
- https://api.qrserver.com/
- https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
- https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
- https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
原文地址: http://www.cveoy.top/t/topic/i7tB 著作权归作者所有。请勿转载和采集!