// ==UserScript== // @name Globe eSIM — 解锁信用卡/借记卡支付 // @namespace https://shop.globe.com.ph/ // @version 2.4.0 // @description 在 shop.globe.com.ph/esim 恢复站点自带的信用卡/借记卡支付入口,并自动补发已付款但未下发的 eSIM。 // @author security-research // @match https://shop.globe.com.ph/esim* // @run-at document-start // @grant none // @noframes // ==/UserScript== /* * 站点把卡付入口写死隐藏了(模板 ``),但卡付链路本身完整可用: * 卡表单 offcanvas、Xendit.card.createToken、3DS、建单、出卡都在。 * 本脚本只做三件事,不复制任何支付逻辑: * 1) 把原生卡付 radio 重新渲染出来,点选即弹出官方卡表单; * 2) 站点卡付建单漏传 settlementInformation[].emailAddress(服务端 required,400), * 在 fetch/XHR 出口补齐; * 3) 站点支付回调只查一次状态,命中中间态就不出卡。本脚本轮询到授权后自动补发。 */ (function () { 'use strict'; const LOG = '[eSIM]'; const API_SESSIONS = /\/api\/payment-service\/payments\/sessions(\?|$)/; const API_STATUS = (t) => `/api/payment-service/payments/status?channel=esimweb&paymentTokenId=${encodeURIComponent(t)}`; const API_VALIDATE = '/api/esim-web/api/validate-payment'; const LS_MAIL = 'esim.email'; const LS_ISSUED = 'esim.issued'; const MAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/; const log = (...a) => console.log(LOG, ...a); // ═══════════════ 邮箱 ═══════════════ let mailCache = ''; // 页面输入框里的邮箱最可信:用户当场敲的 function mailFromPage() { const el = document.querySelector('input[type=email]'); const v = el ? String(el.value || '').trim() : ''; return MAIL_RE.test(v) ? v : ''; } // 优先取页面输入框(用户当场填的);其次 sessionStorage(站点自己写的)。 // 本脚本的 localStorage 缓存只用于跨刷新提示,不直接填请求 —— // 否则可能把上一次支付用过的邮箱塞进这一次,串号到别人的 eSIM。 let mailFresh = false; function mail() { const page = mailFromPage(); if (page) return page; try { const s = sessionStorage.getItem('emailAddress'); if (s && MAIL_RE.test(s)) return s; } catch (e) { /* ignore */ } return mailFresh ? mailCache : ''; } function mailSave(v) { v = String(v || '').trim(); if (!MAIL_RE.test(v)) return; mailCache = v; mailFresh = true; try { localStorage.setItem(LS_MAIL, v); } catch (e) { /* ignore */ } } try { mailCache = localStorage.getItem(LS_MAIL) || ''; } catch (e) { /* ignore */ } // 补齐 payments/sessions 的 emailAddress;不需要改则返回 null function patchBody(raw) { if (typeof raw !== 'string' || !raw) return null; let o; try { o = JSON.parse(raw); } catch (e) { return null; } const si = o && o.settlementInformation; if (!Array.isArray(si) || !si.length) return null; let changed = false; for (const it of si) { if (!it || typeof it !== 'object') continue; if (MAIL_RE.test(String(it.emailAddress || '').trim())) continue; const v = mail(); if (!v) return null; // 拿不到邮箱就原样放行,绝不填假的 it.emailAddress = v; changed = true; } if (!changed) return null; log('补齐 emailAddress:', mail()); return JSON.stringify(o); } // ═══════════════ 网络 hook ═══════════════ // 拿到 paymentTokenId 后启动轮询 function onSession(parse) { try { const b = JSON.parse(parse); const tok = b && b.data && b.data.paymentTokenId; if (tok) startWatch(tok); } catch (e) { /* ignore */ } } function hookFetch() { if (window.__esimHookedFetch) return; window.__esimHookedFetch = true; const orig = window.fetch; window.fetch = function (input, init) { const url = typeof input === 'string' ? input : (input && input.url) || ''; if (!API_SESSIONS.test(url)) return orig.apply(this, arguments); const body = (init && init.body) || (typeof input === 'object' && input && input.body); if (typeof body === 'string') { const p = patchBody(body); if (p) { const next = Object.assign({}, init || {}, { body: p }); return orig.call(this, url, next).then(track); } } return orig.apply(this, arguments).then(track); function track(resp) { resp.clone().text().then(onSession).catch(() => {}); return resp; } }; } function hookXHR() { if (window.__esimHookedXHR) return; if (!window.XMLHttpRequest) return; window.__esimHookedXHR = true; const P = XMLHttpRequest.prototype; const open = P.open; const send = P.send; P.open = function (m, u) { this.__esimUrl = String(u || ''); return open.apply(this, arguments); }; P.send = function (body) { if (API_SESSIONS.test(this.__esimUrl || '')) { if (typeof body === 'string') { const p = patchBody(body); if (p) body = p; } this.addEventListener('load', () => onSession(this.responseText)); } return send.call(this, body); }; } // ═══════════════ 支付看护 ═══════════════ const SUCCESS = ['XENDIT_AUTHORISED', 'GCASH_AUTHORISED']; const PENDING = ['PROCESSING', 'XENDIT_RECEIVED', 'GCASH_RECEIVED', 'REQUIRES_ACTION', 'PENDING', 'IN_REVIEW']; const FAILED = ['XENDIT_REFUSED', 'XENDIT_CANCELLED', 'XENDIT_ERROR', 'GCASH_REFUSED', 'GCASH_CANCELLED', 'GCASH_ERROR']; const W = { token: null, timer: null, tries: 0, state: 'idle', // idle | polling | issued | failed detail: '', result: null, hud: null, }; async function api(url, init) { const r = await fetch(url, Object.assign({ credentials: 'include' }, init || {})); let body = null; try { body = await r.json(); } catch (e) { body = null; } return { ok: r.ok, status: r.status, body }; } function startWatch(token) { if (!token || W.state === 'issued' || (W.token === token && W.timer)) return; clearInterval(W.timer); W.token = token; W.tries = 0; W.state = 'polling'; W.detail = ''; W.result = null; hudShow(); log('开始轮询支付状态:', token); const stop = (state, detail) => { clearInterval(W.timer); W.timer = null; W.state = state; if (detail) W.detail = detail; hudRender(); }; const tick = async () => { W.tries++; let r; try { r = await api(API_STATUS(token)); } catch (e) { if (W.tries >= 6) stop('failed', '网络异常,已停止'); return; } const b = r.body || {}; const s = (b.data && b.data.status) || ''; const errCode = b.error && b.error.code; if (SUCCESS.includes(s)) { clearInterval(W.timer); W.timer = null; return issue(s); } if (FAILED.includes(s)) return stop('failed', '支付失败:' + s); if (s && PENDING.includes(s)) { W.detail = s + ' · 第 ' + W.tries + ' 次'; hudRender(); if (W.tries >= 120) return stop('failed', '轮询超时,如已扣款请刷新页面'); return; } // 其余一律视为终态:token 无效、未支付、未知状态 stop('failed', errCode ? '订单无效 (' + errCode + ')' : (s ? '未知状态 ' + s : '查询失败 HTTP ' + r.status)); }; tick(); W.timer = setInterval(tick, 2500); } async function issue(status) { W.state = 'polling'; W.detail = '已授权,正在下发 eSIM…'; hudRender(); const email = mail(); const token = (() => { try { return sessionStorage.getItem('actionToken') || 'x'; } catch (e) { return 'x'; } })(); let r; try { r = await api(API_VALIDATE, { method: 'POST', headers: { 'Content-Type': 'application/json', ActionToken: token }, body: JSON.stringify({ email, paymentToken: W.token }), }); } catch (e) { return fail('下发 eSIM 请求失败'); } const b = r.body || {}; if (r.ok && b.success !== false && (b.msisdn || b.actionList)) { const a0 = (b.actionList && b.actionList[0]) || {}; W.state = 'issued'; W.detail = ''; W.result = { code: a0.activationCode || '', msisdn: b.msisdn || '', qr: !!a0.QRImage, email, token: W.token, time: Date.now(), }; saveIssued(W.result); hudRender(); } else { fail(/not authorised/i.test((b && b.message) || '') ? '支付未通过授权' : '下发失败'); } function fail(msg) { W.state = 'failed'; W.detail = msg; hudRender(); } } function issuedList() { try { return JSON.parse(localStorage.getItem(LS_ISSUED) || '[]'); } catch (e) { return []; } } function saveIssued(item) { try { const list = issuedList().filter((x) => x && x.token !== item.token); list.unshift(item); localStorage.setItem(LS_ISSUED, JSON.stringify(list.slice(0, 20))); } catch (e) { /* ignore */ } } async function copy(text) { if (!text) return false; try { if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); return true; } } catch (e) { /* 回退 */ } try { const ta = document.createElement('textarea'); ta.value = text; ta.style.cssText = 'position:fixed;left:-9999px;opacity:0'; document.body.appendChild(ta); ta.select(); const ok = document.execCommand('copy'); document.body.removeChild(ta); return ok; } catch (e) { return false; } } // ═══════════════ 面板 ═══════════════ function hudShow() { if (!hudInit()) return; W.hud.style.display = 'block'; hudRender(); } function hudInit() { if (W.hud && document.body.contains(W.hud)) return true; if (!document.body) return false; const box = document.createElement('div'); box.id = 'esim-hud'; box.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:2147483000;width:300px;' + 'background:#fff;border:1px solid #d0d7e2;border-radius:10px;box-shadow:0 8px 28px rgba(0,0,0,.18);' + 'font:12px/1.45 Roboto,system-ui,sans-serif;overflow:hidden;display:none'; box.innerHTML = '
' + 'eSIM 自动补发' + '' + '
' + '
' + '
' + '
' + '
' + '
'; box.querySelector('[data-close]').onclick = () => { box.style.display = 'none'; }; document.body.appendChild(box); W.hud = box; return true; } function hudRender() { if (!hudInit()) return; const box = W.hud; box.style.display = 'block'; const tone = { polling: '#B26B00', issued: '#00A441', failed: '#B91E28' }[W.state] || '#1a458b'; const label = { idle: '', polling: '处理中', issued: 'eSIM 已下发', failed: '未完成' }[W.state] || ''; const st = box.querySelector('[data-state]'); st.textContent = label; st.style.color = tone; box.querySelector('[data-detail]').textContent = W.detail || ''; const body = box.querySelector('[data-body]'); body.textContent = ''; const list = issuedList(); if (!list.length) return; const title = document.createElement('div'); title.style.cssText = 'border-top:1px solid #e7ecf2;padding-top:6px;margin-top:6px;color:#5b6472'; title.textContent = '已保存的激活码(' + list.length + ')'; body.appendChild(title); list.forEach((it) => { const row = document.createElement('div'); row.style.cssText = 'margin-top:6px;padding:6px;background:#f7f9fc;border-radius:6px'; const code = document.createElement('div'); code.style.cssText = 'font-family:ui-monospace,monospace;font-size:11px;word-break:break-all'; code.textContent = it.code || '(无激活码)'; const meta = document.createElement('div'); meta.style.cssText = 'color:#8a93a2;font-size:10px;margin-top:2px'; meta.textContent = [it.msisdn, new Date(it.time).toLocaleString()].filter(Boolean).join(' · '); const btn = document.createElement('button'); btn.textContent = '复制'; btn.style.cssText = 'margin-top:4px;padding:4px 8px;background:#fff;color:#1a458b;' + 'border:1px solid #cfd6e0;border-radius:5px;cursor:pointer;font-size:11px'; btn.onclick = async () => { btn.textContent = await copy(it.code) ? '已复制' : '失败'; setTimeout(() => { btn.textContent = '复制'; }, 1500); }; row.append(code, meta, btn); body.appendChild(row); }); } // ═══════════════ 卡付入口 ═══════════════ const PANEL = 'esim-card-unlock'; function inject() { if (document.getElementById(PANEL)) return true; const gcash = document.querySelector('input[type=radio][name="option"][value="gcash"]'); if (!gcash) return false; const label = gcash.closest('label') || gcash.parentElement; const col = label && label.parentElement; if (!col) return false; const clone = col.cloneNode(true); clone.id = PANEL; clone.classList.remove('hide', 'd-none'); clone.querySelectorAll('[ng-reflect-model]').forEach((n) => n.removeAttribute('ng-reflect-model')); const radio = clone.querySelector('input[type=radio]'); if (!radio) return false; radio.value = 'card'; radio.id = 'esim-card-radio'; radio.checked = false; radio.removeAttribute('disabled'); // 文案替换(保留原有图标) const walker = document.createTreeWalker(clone, NodeFilter.SHOW_TEXT); while (walker.nextNode()) { const n = walker.currentNode; if (/gcash/i.test(n.nodeValue)) n.nodeValue = n.nodeValue.replace(/gcash/gi, 'Credit/Debit Card'); } if (!/credit|debit/i.test(clone.textContent)) { const span = document.createElement('span'); span.textContent = ' Credit/Debit Card'; span.style.fontWeight = '600'; clone.appendChild(span); } const pick = (e) => { e.preventDefault(); e.stopPropagation(); document.querySelectorAll('input[name="option"][type=radio]').forEach((r) => { if (r.value === 'gcash' || r.value === 'card') r.checked = (r === radio); }); radio.checked = true; // 站点只在 gcash 分支写 email,卡付链路读不到,这里先固化 mailSave(mailFromPage()); const oc = document.getElementById('offcanvasBottom'); if (!oc) return log('未找到卡表单 #offcanvasBottom,站点可能已改版'); oc.classList.add('show'); oc.style.display = 'block'; if (window.innerWidth < 500) { oc.classList.add('offcanvas-bottom'); oc.classList.remove('offcanvas-end'); } }; radio.addEventListener('click', pick); radio.addEventListener('change', pick); clone.addEventListener('click', (e) => { if (e.target !== radio) pick(e); }); col.parentElement.appendChild(clone); log('卡付入口已注入'); return true; } let tries = 0; function injectRetry() { if (inject()) return; if (tries++ > 60) return; setTimeout(injectRetry, 500); } // Angular 重渲染会冲掉注入的节点 function watchDom() { if (!document.body) return; new MutationObserver(() => { if (!document.getElementById(PANEL)) inject(); }).observe(document.body, { childList: true, subtree: true }); } // 邮箱输入框:一填就存,覆盖 SPA 换节点的情况 function watchEmail() { const bind = () => { const el = document.querySelector('input[type=email]'); if (!el || el.__esimBound) return; el.__esimBound = true; const save = () => mailSave(el.value); ['input', 'change', 'blur'].forEach((ev) => el.addEventListener(ev, save, true)); save(); }; bind(); setInterval(bind, 2000); } // ═══════════════ 启动 ═══════════════ // 网络 hook 必须立刻装:Angular 初始化时就会抓走 XHR/fetch 引用 hookFetch(); hookXHR(); // Xendit SDK 是异步加载的,稍后补挂 (function hookXendit(n) { if (window.Xendit && window.Xendit.card && window.Xendit.card.createToken) { if (window.__esimHookedXendit) return; window.__esimHookedXendit = true; const orig = window.Xendit.card.createToken; window.Xendit.card.createToken = function (d, cb) { return orig.call(this, d, (err, res) => { if (!err && res && res.status === 'IN_REVIEW') { W.state = 'polling'; W.detail = '等待 3D Secure 验证'; hudShow(); } return cb(err, res); }); }; return; } if (n > 20) return; setTimeout(() => hookXendit(n + 1), 500); })(0); // 刷新后接续未完成的支付 (function resume() { try { const tok = sessionStorage.getItem('paymentTokenId'); if (tok) startWatch(tok); } catch (e) { /* ignore */ } })(); const onReady = (fn) => (document.readyState === 'loading' ? document.addEventListener('DOMContentLoaded', fn, { once: true }) : fn()); onReady(() => { setTimeout(() => { injectRetry(); watchDom(); watchEmail(); // 有历史激活码时自动展开面板 if (issuedList().length) hudShow(); }, 1200); }); // SPA 路由切换后重新注入 let lastPath = location.pathname; setInterval(() => { if (location.pathname === lastPath) return; lastPath = location.pathname; if (lastPath.startsWith('/esim')) { tries = 0; setTimeout(injectRetry, 600); } }, 1200); // 控制台入口 window.__esim = { status: () => ({ state: W.state, token: W.token, detail: W.detail, result: W.result }), retry: () => { if (W.token) startWatch(W.token); }, issued: issuedList, clearIssued: () => { try { localStorage.removeItem(LS_ISSUED); hudRender(); return true; } catch (e) { return false; } }, email: mail, setEmail: (v) => { mailSave(v); return mail(); }, selfTest: () => ({ version: '2.4.0', fetch: !!window.__esimHookedFetch, xhr: !!window.__esimHookedXHR, panel: !!document.getElementById(PANEL), email: mail(), }), }; })();