| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042 |
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>API 服务充值 — BrainHack</title>
- <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.4/build/qrcode.min.js"></script>
- <script>
- // Fallback: if QRCode lib not loaded, provide a shim using img
- if (typeof QRCode === 'undefined') {
- console.warn('QRCode lib not loaded, will use img fallback');
- window.QRCode = null;
- }
- </script>
- <style>
- /* ═══════════════════════════════════════════════════
- BrainHack Dark Neumorphic Payment Page
- Color Palette: #0A0A0A bg, #00D4FF neon, #00B6C0 tech
- ═══════════════════════════════════════════════════ */
- :root {
- --bg: #0A0A0A;
- --surface: #141414;
- --surface-alt: #1A1A1A;
- --neon: #00D4FF;
- --neon-dim: #00B6C0;
- --neon-glow: rgba(0, 212, 255, 0.15);
- --neon-glow-s: rgba(0, 212, 255, 0.25);
- --text: #E0E0E0;
- --text-dim: #888;
- --text-bright: #FFFFFF;
- --success: #00FF88;
- --success-dim: #059660;
- --danger: #FF4D6A;
- --shadow-dark: rgba(0, 0, 0, 0.7);
- --shadow-light: rgba(255, 255, 255, 0.04);
- --radius: 12px;
- }
- * { margin: 0; padding: 0; box-sizing: border-box; }
- body {
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
- background: var(--bg);
- color: var(--text);
- min-height: 100vh;
- display: flex;
- flex-direction: column;
- align-items: center;
- overflow-x: hidden;
- }
- /* ─── Background Grid Effect ─── */
- body::before {
- content: '';
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- background-image:
- radial-gradient(ellipse 600px 400px at 50% 0%, rgba(0,212,255,0.06) 0%, transparent 70%),
- linear-gradient(rgba(0,212,255,0.03) 1px, transparent 1px),
- linear-gradient(90deg, rgba(0,212,255,0.03) 1px, transparent 1px);
- background-size: 100% 100%, 40px 40px, 40px 40px;
- pointer-events: none;
- z-index: 0;
- }
- /* ─── Neumorphic Mixins (Dark Mode) ─── */
- .neu-raised {
- background: var(--surface);
- background-image: linear-gradient(145deg, rgba(255,255,255,0.03), rgba(0,0,0,0.2));
- border-radius: var(--radius);
- box-shadow:
- 4px 4px 8px var(--shadow-dark),
- -4px -4px 8px var(--shadow-light);
- transition: box-shadow 0.25s ease, background 0.25s ease, transform 0.15s ease;
- }
- .neu-raised:hover {
- box-shadow:
- 2px 2px 5px var(--shadow-dark),
- -2px -2px 5px var(--shadow-light);
- }
- .neu-pressed {
- box-shadow:
- inset 3px 3px 6px var(--shadow-dark),
- inset -3px -3px 6px var(--shadow-light);
- background-image: linear-gradient(145deg, rgba(0,0,0,0.25), rgba(255,255,255,0.02));
- }
- .neu-groove {
- background: rgba(10,10,10,0.6);
- box-shadow:
- inset 2px 2px 4px rgba(0,0,0,0.5),
- inset -2px -2px 4px rgba(255,255,255,0.03);
- border-radius: var(--radius);
- }
- /* ─── Header ─── */
- .page-header {
- position: relative;
- z-index: 1;
- width: 100%;
- padding: 20px 32px;
- display: flex;
- align-items: center;
- gap: 12px;
- border-bottom: 1px solid rgba(0,212,255,0.1);
- }
- .page-header .logo {
- font-size: 20px;
- font-weight: 700;
- letter-spacing: 2px;
- color: var(--text-bright);
- }
- .page-header .logo span { color: var(--neon); }
- .page-header .subtitle {
- font-size: 14px;
- color: var(--text-dim);
- margin-left: 8px;
- }
- /* ─── Main Container ─── */
- .main-container {
- position: relative;
- z-index: 1;
- width: 100%;
- max-width: 720px;
- padding: 32px 24px;
- flex: 1;
- }
- /* ─── API Info Card ─── */
- .api-info-card {
- padding: 28px;
- margin-bottom: 24px;
- }
- .api-info-card .api-title {
- font-size: 22px;
- font-weight: 700;
- color: var(--text-bright);
- margin-bottom: 8px;
- }
- .api-info-card .api-title .badge {
- display: inline-block;
- font-size: 11px;
- font-weight: 500;
- padding: 2px 8px;
- border: 1px solid var(--neon);
- color: var(--neon);
- border-radius: 4px;
- margin-left: 10px;
- vertical-align: middle;
- }
- .api-info-card .api-desc {
- font-size: 14px;
- color: var(--text-dim);
- line-height: 1.6;
- }
- .api-info-card .api-stats {
- display: flex;
- gap: 24px;
- margin-top: 16px;
- padding-top: 16px;
- border-top: 1px solid rgba(255,255,255,0.06);
- }
- .api-info-card .stat-item {
- display: flex;
- flex-direction: column;
- }
- .api-info-card .stat-label {
- font-size: 12px;
- color: var(--text-dim);
- }
- .api-info-card .stat-value {
- font-size: 18px;
- font-weight: 600;
- color: var(--neon);
- }
- /* ─── Tier Selection ─── */
- .section-title {
- font-size: 14px;
- color: var(--text-dim);
- margin-bottom: 12px;
- letter-spacing: 1px;
- }
- .tier-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
- gap: 14px;
- margin-bottom: 28px;
- }
- .tier-card {
- padding: 18px;
- cursor: pointer;
- border: 1px solid transparent;
- position: relative;
- overflow: hidden;
- }
- .tier-card::after {
- content: '';
- position: absolute;
- top: 0; left: 0; right: 0;
- height: 2px;
- background: transparent;
- transition: background 0.3s ease;
- }
- .tier-card:hover {
- transform: translateY(-1px);
- }
- .tier-card.active {
- border-color: var(--neon);
- box-shadow:
- 4px 4px 8px var(--shadow-dark),
- -4px -4px 8px var(--shadow-light),
- 0 0 15px var(--neon-glow);
- }
- .tier-card.active::after {
- background: linear-gradient(90deg, var(--neon), var(--neon-dim));
- }
- .tier-price {
- font-size: 28px;
- font-weight: 700;
- color: var(--neon);
- }
- .tier-price .symbol { font-size: 16px; }
- .tier-count {
- font-size: 14px;
- color: var(--text);
- margin-top: 4px;
- }
- .tier-unit-price {
- display: inline-block;
- font-size: 11px;
- color: var(--text-dim);
- background: rgba(255,255,255,0.05);
- padding: 2px 6px;
- border-radius: 4px;
- margin-top: 8px;
- }
- /* ─── Summary ─── */
- .summary-bar {
- padding: 20px 24px;
- margin-bottom: 24px;
- display: flex;
- justify-content: space-between;
- align-items: center;
- }
- .summary-bar .label {
- font-size: 14px;
- color: var(--text-dim);
- }
- .summary-bar .total {
- font-size: 28px;
- font-weight: 700;
- color: var(--neon);
- }
- .summary-bar .validity {
- font-size: 12px;
- color: var(--text-dim);
- margin-top: 2px;
- }
- /* ─── Pay Button (Neumorphic) ─── */
- .pay-btn {
- display: block;
- width: 100%;
- padding: 16px;
- border: none;
- cursor: pointer;
- font-size: 16px;
- font-weight: 600;
- letter-spacing: 2px;
- color: var(--text-bright);
- background: var(--surface);
- background-image: linear-gradient(145deg, rgba(0,212,255,0.15), rgba(0,0,0,0.3));
- border-radius: var(--radius);
- box-shadow:
- 5px 5px 10px var(--shadow-dark),
- -5px -5px 10px var(--shadow-light),
- 0 0 20px var(--neon-glow);
- transition: all 0.25s ease;
- position: relative;
- overflow: hidden;
- }
- .pay-btn::before {
- content: '';
- position: absolute;
- top: 0; left: 0; right: 0;
- height: 1px;
- background: linear-gradient(90deg, transparent, var(--neon), transparent);
- }
- .pay-btn:hover {
- box-shadow:
- 3px 3px 6px var(--shadow-dark),
- -3px -3px 6px var(--shadow-light),
- 0 0 30px var(--neon-glow-s);
- transform: translateY(-1px);
- }
- .pay-btn:active {
- box-shadow:
- inset 3px 3px 6px var(--shadow-dark),
- inset -3px -3px 6px var(--shadow-light);
- background-image: linear-gradient(145deg, rgba(0,0,0,0.3), rgba(0,212,255,0.1));
- transform: translateY(0);
- }
- .pay-btn:disabled {
- opacity: 0.5;
- cursor: not-allowed;
- box-shadow:
- 2px 2px 4px var(--shadow-dark),
- -2px -2px 4px var(--shadow-light);
- }
- .pay-btn .btn-icon { margin-right: 8px; }
- /* ─── QR Modal ─── */
- .modal-overlay {
- display: none;
- position: fixed;
- top: 0; left: 0; right: 0; bottom: 0;
- background: rgba(0,0,0,0.85);
- z-index: 100;
- align-items: center;
- justify-content: center;
- }
- .modal-overlay.show { display: flex; }
- .modal-box {
- width: 380px;
- max-width: 90vw;
- padding: 32px;
- text-align: center;
- position: relative;
- border: 1px solid rgba(0,212,255,0.15);
- }
- .modal-box .modal-close {
- position: absolute;
- top: 12px;
- right: 16px;
- background: none;
- border: none;
- color: var(--text-dim);
- font-size: 20px;
- cursor: pointer;
- transition: color 0.2s;
- }
- .modal-box .modal-close:hover { color: var(--text-bright); }
- .modal-box .modal-title {
- font-size: 18px;
- font-weight: 600;
- color: var(--text-bright);
- margin-bottom: 6px;
- }
- .modal-box .modal-amount {
- font-size: 32px;
- font-weight: 700;
- color: var(--neon);
- margin: 8px 0;
- }
- .modal-box .modal-amount .symbol { font-size: 18px; }
- .qr-wrapper {
- display: inline-block;
- padding: 16px;
- background: #fff;
- border-radius: 8px;
- margin: 16px 0;
- box-shadow: 0 0 20px var(--neon-glow);
- }
- .qr-wrapper canvas { display: block; }
- .modal-box .scan-hint {
- font-size: 13px;
- color: var(--text-dim);
- margin-top: 8px;
- }
- .modal-box .scan-hint svg {
- vertical-align: middle;
- margin-right: 4px;
- }
- .polling-status {
- font-size: 12px;
- color: var(--text-dim);
- margin-top: 12px;
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
- }
- .polling-dot {
- display: inline-block;
- width: 6px; height: 6px;
- background: var(--neon);
- border-radius: 50%;
- animation: pulse 1.5s infinite;
- }
- @keyframes pulse {
- 0%, 100% { opacity: 0.3; }
- 50% { opacity: 1; }
- }
- /* ─── Success Screen ─── */
- .success-screen {
- display: none;
- text-align: center;
- padding: 48px 24px;
- }
- .success-screen.show { display: block; }
- .success-icon {
- width: 80px; height: 80px;
- margin: 0 auto 20px;
- border-radius: 50%;
- background: var(--surface);
- box-shadow:
- 5px 5px 10px var(--shadow-dark),
- -5px -5px 10px var(--shadow-light),
- 0 0 20px rgba(0,255,136,0.15);
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .success-icon svg {
- width: 40px; height: 40px;
- stroke: var(--success);
- }
- .success-screen .success-title {
- font-size: 24px;
- font-weight: 700;
- color: var(--text-bright);
- margin-bottom: 8px;
- }
- .success-screen .success-detail {
- font-size: 14px;
- color: var(--text-dim);
- line-height: 1.8;
- margin-bottom: 28px;
- }
- .success-screen .back-btn {
- display: inline-block;
- padding: 12px 40px;
- border: none;
- cursor: pointer;
- font-size: 14px;
- font-weight: 600;
- color: var(--text-bright);
- background: var(--surface);
- background-image: linear-gradient(145deg, rgba(0,255,136,0.12), rgba(0,0,0,0.3));
- border-radius: var(--radius);
- box-shadow:
- 4px 4px 8px var(--shadow-dark),
- -4px -4px 8px var(--shadow-light),
- 0 0 15px rgba(0,255,136,0.1);
- transition: all 0.25s ease;
- }
- .success-screen .back-btn:hover {
- transform: translateY(-1px);
- box-shadow:
- 3px 3px 6px var(--shadow-dark),
- -3px -3px 6px var(--shadow-light),
- 0 0 25px rgba(0,255,136,0.15);
- }
- .success-screen .back-btn:active {
- box-shadow:
- inset 3px 3px 6px var(--shadow-dark),
- inset -3px -3px 6px var(--shadow-light);
- transform: translateY(0);
- }
- /* ─── Loading Skeleton ─── */
- .skeleton {
- background: linear-gradient(90deg, var(--surface) 25%, var(--surface-alt) 50%, var(--surface) 75%);
- background-size: 200% 100%;
- animation: shimmer 1.5s infinite;
- border-radius: 6px;
- }
- @keyframes shimmer {
- 0% { background-position: 200% 0; }
- 100% { background-position: -200% 0; }
- }
- /* ─── Error State ─── */
- .error-bar {
- display: none;
- padding: 12px 16px;
- background: rgba(255,77,106,0.1);
- border: 1px solid rgba(255,77,106,0.3);
- border-radius: 8px;
- color: var(--danger);
- font-size: 13px;
- margin-bottom: 16px;
- }
- .error-bar.show { display: block; }
- /* ─── Responsive ─── */
- @media (max-width: 480px) {
- .main-container { padding: 20px 16px; }
- .api-info-card { padding: 20px; }
- .tier-grid { grid-template-columns: 1fr; }
- .modal-box { padding: 24px 20px; }
- }
- </style>
- </head>
- <body>
- <!-- Header -->
- <div class="page-header">
- <div class="logo">BRAIN<span>HACK</span></div>
- <div class="subtitle">API 服务充值</div>
- </div>
- <!-- Main -->
- <div class="main-container" id="mainContent">
- <!-- API Info Card -->
- <div class="api-info-card neu-raised" id="apiInfoCard">
- <div class="api-title" id="apiTitle">
- <span class="skeleton" style="display:inline-block;width:200px;height:24px;"> </span>
- </div>
- <div class="api-desc" id="apiDesc">
- <span class="skeleton" style="display:inline-block;width:100%;height:16px;margin-top:8px;"> </span>
- </div>
- <div class="api-stats" id="apiStats" style="display:none;">
- <div class="stat-item">
- <span class="stat-label">当前余额</span>
- <span class="stat-value" id="statCount">—</span>
- </div>
- <div class="stat-item">
- <span class="stat-label">服务状态</span>
- <span class="stat-value" id="statStatus">—</span>
- </div>
- </div>
- </div>
- <!-- Error -->
- <div class="error-bar" id="errorBar"></div>
- <!-- Tier Selection -->
- <div class="section-title">选择套餐</div>
- <div class="tier-grid" id="tierGrid">
- <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
- <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
- <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
- </div>
- <!-- Summary -->
- <div class="summary-bar neu-groove" id="summaryBar" style="display:none;">
- <div>
- <div class="label">套餐配额</div>
- <div id="summaryCount" style="font-size:16px;font-weight:600;color:var(--text-bright);margin-top:2px;">—</div>
- <div class="validity">有效期 730 天(自购买之日起)</div>
- </div>
- <div style="text-align:right;">
- <div class="label">应付金额</div>
- <div class="total"><span class="symbol">¥</span><span id="summaryPrice">0</span></div>
- </div>
- </div>
- <!-- Pay Button -->
- <button class="pay-btn" id="payBtn" disabled>
- <span class="btn-icon">💳</span> 微信支付
- </button>
- <!-- Success Screen -->
- <div class="success-screen" id="successScreen">
- <div class="success-icon">
- <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
- <polyline points="20 6 9 17 4 12"></polyline>
- </svg>
- </div>
- <div class="success-title">充值成功</div>
- <div class="success-detail" id="successDetail"></div>
- <button class="back-btn" onclick="handleDone()">完成</button>
- </div>
- </div>
- <!-- QR Modal -->
- <div class="modal-overlay" id="qrModal">
- <div class="modal-box neu-raised">
- <button class="modal-close" onclick="cancelPayment()">×</button>
- <div class="modal-title">微信扫码支付</div>
- <div class="modal-amount"><span class="symbol">¥</span><span id="modalPrice">0</span></div>
- <div class="qr-wrapper" id="qrWrapper">
- <canvas id="qrCanvas"></canvas>
- </div>
- <div class="scan-hint">
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>
- 打开微信扫一扫
- </div>
- <div class="polling-status" id="pollingStatus">
- <span class="polling-dot"></span> 等待支付中...
- </div>
- </div>
- </div>
- <script>
- // ═══════════════════════════════════════════════════
- // APIG Payment Logic
- // ═══════════════════════════════════════════════════
- const API_BASE = 'https://server.fmode.cn';
- const PARSE_BASE = API_BASE + '/parse/functions';
- const PAY_COMPANY = '1AiWpTEDH9';
- const APP_ID = 'ncloudmaster';
- // URL params
- const params = new URLSearchParams(window.location.search);
- const authId = params.get('authid') || '';
- const userId = params.get('user') || params.get('userid') || '';
- let apig = null;
- let selectedIndex = 0;
- let order = null;
- let tradeNo = '';
- let nonceStr = '';
- let pollTimer = null;
- // ─── Init ───
- document.addEventListener('DOMContentLoaded', () => {
- if (!authId) {
- showError('缺少 authid 参数,请通过正确链接访问本页面。');
- return;
- }
- // Show loading state
- const titleEl = document.getElementById('apiTitle');
- if (titleEl) titleEl.textContent = '加载中...';
- loadApig();
- });
- // ─── Load APIG Info ───
- async function loadApig() {
- try {
- // 1. Try getApig REST endpoint (works when authId is an APIGAuth objectId)
- const resp = await postJSON(API_BASE + '/api/apig/getApig', { authid: authId });
- if (resp.code === 200 && resp.data) {
- apig = resp.data;
- applyTestTier();
- renderApigInfo();
- renderTiers();
- return;
- }
- // 2. Fallback: use cloud function to query APIG by objectId
- // Cloud function IDs: getApigInfo=t012qy4XVe, getApigAuth=H7X7y9Wfc0
- // Note: FmodeParse SDK uses internal dispatch; direct REST call needs actual function name
- console.log('getApig returned no data, trying cloud function...');
- const cfFuncName = params.get('cfName') || 'getApigInfo';
- const cfResp = await parseCloudCall(cfFuncName, {
- apigId: authId
- }).catch(e => { console.warn('cloud function error:', e); return null; });
- console.log('Cloud function response:', cfResp);
- if (cfResp && cfResp.result) {
- const cfData = cfResp.result.data || cfResp.result;
- if (cfData && cfData.objectId) {
- apig = cfData;
- applyTestTier();
- renderApigInfo();
- renderTiers();
- return;
- }
- }
- // 3. Fallback: accept APIG data from URL params (OpenClaw can pass these)
- const urlTitle = params.get('title');
- const urlPrices = params.get('prices');
- const urlCounts = params.get('counts');
- if (urlTitle && urlPrices && urlCounts) {
- console.log('Using APIG data from URL params');
- const prices = urlPrices.split(',').map(Number);
- const counts = urlCounts.split(',').map(Number);
- apig = {
- objectId: authId,
- title: urlTitle,
- content: params.get('desc') || '',
- count: parseInt(params.get('balance') || '0'),
- priceStep: prices.map((p, i) => ({ price: p, count: counts[i] || 0 }))
- };
- applyTestTier();
- renderApigInfo();
- renderTiers();
- return;
- }
- showError('无法加载接口信息。请确认 authid 对应有效的 APIGAuth 记录,或通过 URL 参数传入套餐数据。');
- } catch (e) {
- showError('网络错误: ' + e.message);
- }
- }
- function applyTestTier() {
- if (params.get('test') === '1' && apig.priceStep) {
- apig.priceStep.unshift({ count: 1, price: 0.01 });
- }
- }
- function renderApigInfo() {
- const titleEl = document.getElementById('apiTitle');
- titleEl.innerHTML = apig.title + '<span class="badge">HTTPS</span>';
- const descEl = document.getElementById('apiDesc');
- descEl.textContent = apig.content || '专业API数据服务';
- const statsEl = document.getElementById('apiStats');
- statsEl.style.display = 'flex';
- document.getElementById('statCount').textContent =
- (apig.count != null ? apig.count + ' 次' : '—');
- document.getElementById('statStatus').textContent = '正常';
- document.getElementById('statStatus').style.color = 'var(--success)';
- }
- function renderTiers() {
- const grid = document.getElementById('tierGrid');
- if (!apig.priceStep || apig.priceStep.length === 0) {
- grid.innerHTML = '<div style="color:var(--text-dim);">暂无可用套餐</div>';
- return;
- }
- grid.innerHTML = '';
- apig.priceStep.forEach((tier, i) => {
- const card = document.createElement('div');
- card.className = 'tier-card neu-raised' + (i === 0 ? ' active' : '');
- const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
- const unitPrice = (tier.price / tier.count).toFixed(3);
- card.innerHTML = `
- <div class="tier-price"><span class="symbol">¥</span>${tier.price}</div>
- <div class="tier-count">含 ${tier.count} ${unitLabel}</div>
- <div class="tier-unit-price">≈ ${unitPrice} 元/${unitLabel}</div>
- `;
- card.addEventListener('click', () => selectTier(i));
- grid.appendChild(card);
- });
- selectTier(0);
- document.getElementById('payBtn').disabled = false;
- document.getElementById('payBtn').addEventListener('click', startPayment);
- }
- function selectTier(idx) {
- selectedIndex = idx;
- document.querySelectorAll('.tier-card').forEach((el, i) => {
- el.classList.toggle('active', i === idx);
- if (i === idx) {
- el.classList.remove('neu-raised');
- el.classList.add('neu-pressed');
- } else {
- el.classList.remove('neu-pressed');
- el.classList.add('neu-raised');
- }
- });
- const tier = apig.priceStep[idx];
- const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
- document.getElementById('summaryBar').style.display = 'flex';
- document.getElementById('summaryCount').textContent = tier.count + ' ' + unitLabel;
- document.getElementById('summaryPrice').textContent = tier.price;
- }
- // ─── Payment Flow ───
- async function startPayment() {
- const btn = document.getElementById('payBtn');
- btn.disabled = true;
- btn.textContent = '正在生成支付码...';
- hideError();
- try {
- // 1. Generate trade number
- const now = new Date();
- tradeNo = 'C' + (userId || 'U') +
- now.getFullYear() +
- String(now.getMonth() + 1).padStart(2, '0') +
- String(now.getDate()).padStart(2, '0') +
- String(now.getHours()).padStart(2, '0') +
- String(now.getMinutes()).padStart(2, '0') +
- String(now.getSeconds()).padStart(2, '0') +
- now.getMilliseconds();
- const tier = apig.priceStep[selectedIndex];
- // 2. Call pay_code2 to get QR URL
- const payResp = await postJSON(PARSE_BASE + '/pay_code2', {
- _ApplicationId: APP_ID,
- company: PAY_COMPANY,
- out_trade_no: tradeNo,
- total_fee: +tier.price,
- body: apig.title + ' 接口充值'
- });
- if (!payResp.result || !payResp.result.code_url) {
- throw new Error('获取支付码失败');
- }
- const codeUrl = payResp.result.code_url[0];
- nonceStr = payResp.result.nonce_str;
- // 3. Create order
- createOrder(tier);
- // 4. Show QR modal
- document.getElementById('modalPrice').textContent = tier.price;
- document.getElementById('qrModal').classList.add('show');
- document.getElementById('pollingStatus').innerHTML =
- '<span class="polling-dot"></span> 等待支付中...';
- // Generate QR code
- await renderQR(codeUrl);
- // 5. Start polling
- startPolling();
- } catch (e) {
- showError('支付发起失败: ' + e.message);
- } finally {
- btn.disabled = false;
- btn.innerHTML = '<span class="btn-icon">💳</span> 微信支付';
- }
- }
- async function createOrder(tier) {
- try {
- const body = {
- type: 'wxpay',
- authid: authId,
- params: {
- out_trade_no: tradeNo,
- total_fee: +tier.price,
- body: apig.title + ' 接口充值'
- },
- apigid: apig.objectId,
- oldCount: apig.count || 0,
- count: tier.count
- };
- // Server requires fcompany or user; fallback to authId if userId is empty
- body.user = userId || authId;
- body.fcompany = userId || authId;
- const resp = await postJSON(API_BASE + '/api/apig/created-apigorder', body);
- if (resp.code === 200 && resp.data) {
- order = resp.data;
- console.log('Order created:', order);
- }
- } catch (e) {
- console.warn('Order creation error (non-blocking):', e.message);
- }
- }
- function startPolling() {
- if (pollTimer) clearInterval(pollTimer);
- pollTimer = setInterval(async () => {
- try {
- const resp = await postJSON(PARSE_BASE + '/order_status2', {
- _ApplicationId: APP_ID,
- out_trade_no: tradeNo,
- nonce_str: nonceStr,
- company: PAY_COMPANY
- });
- if (resp.result && resp.result.status && resp.result.status[0] === 'SUCCESS') {
- clearInterval(pollTimer);
- pollTimer = null;
- document.getElementById('pollingStatus').innerHTML =
- '<span style="color:var(--success);">✓ 支付成功,正在充值...</span>';
- await doRecharge();
- }
- } catch (e) {
- console.warn('Poll error:', e.message);
- }
- }, 3000);
- }
- async function doRecharge() {
- // Show success first, then try recharge in background (saveRecharge may timeout)
- showSuccess();
- try {
- const tier = apig.priceStep[selectedIndex];
- // Build recharge body
- // authid = APIGAuth objectId (T0iOotHcDX)
- // apigid = APIG objectId from order or from getApig response
- const apigObjId = apig.objectId || authId;
- const body = {
- authid: authId,
- apigid: apigObjId,
- oldCount: apig.count || 0,
- count: tier.count,
- orderid: order ? order.objectId : ''
- };
- // Server requires fcompany or user; fallback to authId if userId is empty
- body.user = userId || authId;
- body.authComp = userId || authId;
- body.fcompany = userId || authId;
- console.log('saveRecharge body:', JSON.stringify(body));
- // Use AbortController for 15s timeout
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), 15000);
- const resp = await fetch(API_BASE + '/api/apig/saveRecharge', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- signal: controller.signal
- });
- clearTimeout(timer);
- const result = await resp.json().catch(() => null);
- console.log('saveRecharge response:', result);
- // Refresh balance display
- await refreshBalance();
- } catch (e) {
- console.warn('Recharge call failed (non-critical):', e.message);
- }
- }
- async function refreshBalance() {
- try {
- const resp = await postJSON(API_BASE + '/api/apig/getApig', { authid: authId });
- if (resp.code === 200 && resp.data && resp.data.count != null) {
- apig.count = resp.data.count;
- const detail = document.getElementById('successDetail');
- if (detail) {
- const tier = apig.priceStep[selectedIndex];
- const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
- detail.innerHTML =
- '已充值 <strong style="color:var(--neon);">' + apig.title + '</strong> 接口<br>' +
- '获得 <strong style="color:var(--success);">' + tier.count + ' ' + unitLabel + '</strong>,有效期 730 天<br>' +
- '<span style="color:var(--text-dim);margin-top:8px;display:inline-block;">当前余额: <strong style="color:var(--neon);">' + apig.count + ' ' + unitLabel + '</strong></span>';
- }
- console.log('Balance refreshed:', apig.count);
- }
- } catch(e) {
- console.warn('Balance refresh failed:', e.message);
- }
- }
- function showSuccess() {
- document.getElementById('qrModal').classList.remove('show');
- document.getElementById('mainContent').querySelector('.api-info-card').style.display = 'none';
- document.querySelector('.section-title').style.display = 'none';
- document.getElementById('tierGrid').style.display = 'none';
- document.getElementById('summaryBar').style.display = 'none';
- document.getElementById('payBtn').style.display = 'none';
- const tier = apig.priceStep[selectedIndex];
- const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
- document.getElementById('successDetail').innerHTML =
- '已充值 <strong style="color:var(--neon);">' + apig.title + '</strong> 接口<br>' +
- '获得 <strong style="color:var(--success);">' + tier.count + ' ' + unitLabel + '</strong>,有效期 730 天';
- document.getElementById('successScreen').classList.add('show');
- }
- async function renderQR(url) {
- const wrapper = document.getElementById('qrWrapper');
- const canvas = document.getElementById('qrCanvas');
- // Clear previous QR (img fallback)
- wrapper.querySelectorAll('img').forEach(i => i.remove());
- canvas.style.display = '';
- canvas.width = 200;
- canvas.height = 200;
- // Try canvas-based QRCode lib first
- if (typeof QRCode !== 'undefined' && QRCode && QRCode.toCanvas) {
- try {
- await QRCode.toCanvas(canvas, url, {
- width: 200,
- margin: 0,
- color: { dark: '#000000', light: '#ffffff' }
- });
- console.log('QR rendered via canvas');
- return;
- } catch (e) {
- console.warn('QRCode.toCanvas failed:', e);
- }
- }
- // Fallback: use img with QR server API
- console.log('Using img fallback for QR');
- canvas.style.display = 'none';
- const img = document.createElement('img');
- img.src = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(url);
- img.width = 200;
- img.height = 200;
- img.alt = 'Payment QR Code';
- img.style.display = 'block';
- wrapper.appendChild(img);
- }
- function handleDone() {
- // Notify parent window (OpenClaw integration)
- try {
- const msg = { type: 'apig-payment-done', authid: authId, user: userId };
- if (window.opener) window.opener.postMessage(msg, '*');
- if (window.parent !== window) window.parent.postMessage(msg, '*');
- } catch(e) { console.warn('postMessage failed:', e); }
- // Try to close window (works if opened via window.open)
- try { window.close(); } catch(e) {}
- setTimeout(() => {
- // If still here, window.close didn't work — reload page
- window.location.reload();
- }, 500);
- }
- function cancelPayment() {
- if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
- document.getElementById('qrModal').classList.remove('show');
- }
- // ─── Helpers ───
- function showError(msg) {
- const el = document.getElementById('errorBar');
- if (!el) { console.error('errorBar not found:', msg); return; }
- el.textContent = msg;
- el.classList.add('show');
- }
- function hideError() {
- const el = document.getElementById('errorBar');
- if (el) el.classList.remove('show');
- }
- async function postJSON(url, data) {
- const resp = await fetch(url, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(data)
- });
- return resp.json();
- }
- async function parseCloudCall(funcId, params) {
- const url = PARSE_BASE + '/' + funcId;
- const body = Object.assign({ _ApplicationId: APP_ID }, params);
- const resp = await fetch(url, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-Parse-Application-Id': APP_ID
- },
- body: JSON.stringify(body)
- });
- if (!resp.ok) {
- console.warn('Cloud function ' + funcId + ' returned ' + resp.status);
- return null;
- }
- return resp.json();
- }
- </script>
- </body>
- </html>
|