| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046 |
- <!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
- };
- // Use user field if available, fallback to fcompany
- if (userId) {
- body.user = userId;
- body.fcompany = userId;
- }
- 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 : ''
- };
- if (userId) {
- body.user = userId;
- body.authComp = userId;
- }
- // Also pass fcompany for compatibility
- body.fcompany = userId || '';
- 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>
|