Reference:
--:--
const API_BASE = 'https://qr.phnpay.com';
const $=id=>document.getElementById(id);
let data=null,started=0,deadline=0,ready=false,tickTimer=0,pollTimer=0,done=false;
const labels={th:{pay:'โปรดชำระเงินตามยอดที่แสดง',currency:'บาท',timer:'ระยะเวลาการชำระเงิน',count:'โปรดชำระเงินภายใน',expired:'หมดเวลาที่แสดงแล้ว',language:'ภาษา',footer:'สแกนง่าย จ่ายสะดวก',warnings:['โปรดระวังการได้รับ QR Code จากบุคคลที่สาม','ควรชำระเงินเพียงครั้งเดียวต่อรายการ','ตรวจสอบชื่อผู้รับและยอดเงินก่อนยืนยัน','ตรวจสอบสถานะรายการก่อนชำระเงินซ้ำ'],successGo:'ชำระเงินสำเร็จ กำลังนำทางกลับไปยังร้านค้า',successStay:'รายการชำระเงินสำเร็จ กรุณาปิดหน้าต่างนี้ หรือกลับไปยังร้านค้าของท่าน'},en:{pay:'Please pay the amount shown',currency:'THB',timer:'Payment time',count:'Please pay within',expired:'Displayed time has ended',language:'Language',footer:'Scan and pay conveniently',warnings:['Beware of QR codes from third parties','Pay only once per order','Verify recipient and amount before confirming','Check payment status before paying again'],successGo:'Payment successful. Returning to the shop.',successStay:'Payment successful. Please close this window or return to your shop.'}};
const locale=()=>labels[$('lang').value]||labels.th;
const time=t=>new Date(t).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit',timeZone:'Asia/Bangkok'});
function show404(){done=true;clearInterval(tickTimer);clearInterval(pollTimer);$('pay').style.display='none';$('success').style.display='none';$('notfound').style.display='block';}
function tick(){if(!data||data.status==='SUCCESS')return;const l=locale(),ms=Math.max(0,deadline-Date.now()),s=Math.ceil(ms/1000);$('bar').style.width=Math.min(100,100*ms/Math.max(1,deadline-started))+'%';$('count').textContent=ms?l.count+' '+String(Math.floor(s/60)).padStart(2,'0')+':'+String(s%60).padStart(2,'0'):l.expired;$('download').disabled=!ready||!ms;$('qr').style.opacity=ms? '1':'.25';}
function translate(){const l=locale();document.documentElement.lang=$('lang').value;$('paylabel').textContent=l.pay;$('timerlabel').textContent=l.timer;$('langlabel').textContent=l.language;$('footertext').textContent=l.footer;$('warning').replaceChildren(...l.warnings.map(w=>{const d=document.createElement('div');d.textContent='- '+w;return d}));if(data&&data.status!=='SUCCESS')$('amount').textContent=Number(data.amount).toLocaleString('en-US',{minimumFractionDigits:2,maximumFractionDigits:2})+' '+l.currency;tick();}
async function drawQr(text){$('qr').replaceChildren();if(!text)return;if(!window.QRCode)await new Promise((resolve,reject)=>{const s=document.createElement('script');s.src='https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js';s.onload=resolve;s.onerror=reject;document.head.append(s)});const el=document.createElement('div');new QRCode(el,{text,width:400,height:400,correctLevel:QRCode.CorrectLevel.M});const raw=el.querySelector('canvas');const out=document.createElement('canvas');out.width=out.height=480;const ctx=out.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,480,480);ctx.drawImage(raw,40,40);$('qr').append(out);ready=true;}
function showSuccess(order){done=true;clearInterval(tickTimer);clearInterval(pollTimer);const l=locale();const redirect=(order.member_redirect_url||'').trim();$('pay').style.display='none';$('notfound').style.display='none';$('success').style.display='block';$('successTitle').textContent=$('lang').value==='en'?'Payment successful':'ชำระเงินสำเร็จ';$('successText').textContent=redirect?l.successGo:l.successStay;if(redirect)setTimeout(()=>{location.href=redirect},3000);}
async function render(order){if(order.status==='SUCCESS'){showSuccess(order);return;}data=order;ready=false;$('notfound').style.display='none';$('success').style.display='none';$('pay').style.display='';$('error').textContent='';$('ref').textContent=order.order_no||'—';started=Date.parse(order.created_at);deadline=Date.parse(order.expires_at);if(!Number.isFinite(started))started=Date.now();if(!Number.isFinite(deadline))deadline=started+300000;$('start').textContent=time(started);$('end').textContent=time(deadline);$('hint').textContent='';translate();try{await drawQr(order.qrcode||'');}catch(e){$('error').textContent='Unable to generate QR code';}tick();}
async function load(ref){const res=await fetch(API_BASE+'/qrcode?ref='+encodeURIComponent(ref),{cache:'no-store'});if(res.status===404){show404();return null;}if(!res.ok)throw new Error('status '+res.status);const body=await res.json();if(!body||body.found===false){show404();return null;}return body;}
async function start(){const ref=new URLSearchParams(location.search).get('ref')||'';if(!ref.trim()){show404();return;}try{const order=await load(ref);if(!order)return;await render(order);pollTimer=setInterval(async()=>{if(done)return;try{const next=await load(ref);if(next)await render(next);}catch(e){}},3000);tickTimer=setInterval(tick,250);}catch(e){$('error').textContent='Unable to load payment';}}
$('lang').onchange=translate;$('download').onclick=()=>{if(!ready||$('download').disabled)return;const c=$('qr').querySelector('canvas');if(!c)return;const a=document.createElement('a');a.href=c.toDataURL('image/png');a.download='payment-qr-'+(data&&data.order_no||'order')+'.png';a.click()};
start();