apig-pay.html 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>API 服务充值 — BrainHack</title>
  7. <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.4/build/qrcode.min.js"></script>
  8. <script>
  9. // Fallback: if QRCode lib not loaded, provide a shim using img
  10. if (typeof QRCode === 'undefined') {
  11. console.warn('QRCode lib not loaded, will use img fallback');
  12. window.QRCode = null;
  13. }
  14. </script>
  15. <style>
  16. /* ═══════════════════════════════════════════════════
  17. BrainHack Dark Neumorphic Payment Page
  18. Color Palette: #0A0A0A bg, #00D4FF neon, #00B6C0 tech
  19. ═══════════════════════════════════════════════════ */
  20. :root {
  21. --bg: #0A0A0A;
  22. --surface: #141414;
  23. --surface-alt: #1A1A1A;
  24. --neon: #00D4FF;
  25. --neon-dim: #00B6C0;
  26. --neon-glow: rgba(0, 212, 255, 0.15);
  27. --neon-glow-s: rgba(0, 212, 255, 0.25);
  28. --text: #E0E0E0;
  29. --text-dim: #888;
  30. --text-bright: #FFFFFF;
  31. --success: #00FF88;
  32. --success-dim: #059660;
  33. --danger: #FF4D6A;
  34. --shadow-dark: rgba(0, 0, 0, 0.7);
  35. --shadow-light: rgba(255, 255, 255, 0.04);
  36. --radius: 12px;
  37. }
  38. * { margin: 0; padding: 0; box-sizing: border-box; }
  39. body {
  40. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  41. background: var(--bg);
  42. color: var(--text);
  43. min-height: 100vh;
  44. display: flex;
  45. flex-direction: column;
  46. align-items: center;
  47. overflow-x: hidden;
  48. }
  49. /* ─── Background Grid Effect ─── */
  50. body::before {
  51. content: '';
  52. position: fixed;
  53. top: 0; left: 0; right: 0; bottom: 0;
  54. background-image:
  55. radial-gradient(ellipse 600px 400px at 50% 0%, rgba(0,212,255,0.06) 0%, transparent 70%),
  56. linear-gradient(rgba(0,212,255,0.03) 1px, transparent 1px),
  57. linear-gradient(90deg, rgba(0,212,255,0.03) 1px, transparent 1px);
  58. background-size: 100% 100%, 40px 40px, 40px 40px;
  59. pointer-events: none;
  60. z-index: 0;
  61. }
  62. /* ─── Neumorphic Mixins (Dark Mode) ─── */
  63. .neu-raised {
  64. background: var(--surface);
  65. background-image: linear-gradient(145deg, rgba(255,255,255,0.03), rgba(0,0,0,0.2));
  66. border-radius: var(--radius);
  67. box-shadow:
  68. 4px 4px 8px var(--shadow-dark),
  69. -4px -4px 8px var(--shadow-light);
  70. transition: box-shadow 0.25s ease, background 0.25s ease, transform 0.15s ease;
  71. }
  72. .neu-raised:hover {
  73. box-shadow:
  74. 2px 2px 5px var(--shadow-dark),
  75. -2px -2px 5px var(--shadow-light);
  76. }
  77. .neu-pressed {
  78. box-shadow:
  79. inset 3px 3px 6px var(--shadow-dark),
  80. inset -3px -3px 6px var(--shadow-light);
  81. background-image: linear-gradient(145deg, rgba(0,0,0,0.25), rgba(255,255,255,0.02));
  82. }
  83. .neu-groove {
  84. background: rgba(10,10,10,0.6);
  85. box-shadow:
  86. inset 2px 2px 4px rgba(0,0,0,0.5),
  87. inset -2px -2px 4px rgba(255,255,255,0.03);
  88. border-radius: var(--radius);
  89. }
  90. /* ─── Header ─── */
  91. .page-header {
  92. position: relative;
  93. z-index: 1;
  94. width: 100%;
  95. padding: 20px 32px;
  96. display: flex;
  97. align-items: center;
  98. gap: 12px;
  99. border-bottom: 1px solid rgba(0,212,255,0.1);
  100. }
  101. .page-header .logo {
  102. font-size: 20px;
  103. font-weight: 700;
  104. letter-spacing: 2px;
  105. color: var(--text-bright);
  106. }
  107. .page-header .logo span { color: var(--neon); }
  108. .page-header .subtitle {
  109. font-size: 14px;
  110. color: var(--text-dim);
  111. margin-left: 8px;
  112. }
  113. /* ─── Main Container ─── */
  114. .main-container {
  115. position: relative;
  116. z-index: 1;
  117. width: 100%;
  118. max-width: 720px;
  119. padding: 32px 24px;
  120. flex: 1;
  121. }
  122. /* ─── API Info Card ─── */
  123. .api-info-card {
  124. padding: 28px;
  125. margin-bottom: 24px;
  126. }
  127. .api-info-card .api-title {
  128. font-size: 22px;
  129. font-weight: 700;
  130. color: var(--text-bright);
  131. margin-bottom: 8px;
  132. }
  133. .api-info-card .api-title .badge {
  134. display: inline-block;
  135. font-size: 11px;
  136. font-weight: 500;
  137. padding: 2px 8px;
  138. border: 1px solid var(--neon);
  139. color: var(--neon);
  140. border-radius: 4px;
  141. margin-left: 10px;
  142. vertical-align: middle;
  143. }
  144. .api-info-card .api-desc {
  145. font-size: 14px;
  146. color: var(--text-dim);
  147. line-height: 1.6;
  148. }
  149. .api-info-card .api-stats {
  150. display: flex;
  151. gap: 24px;
  152. margin-top: 16px;
  153. padding-top: 16px;
  154. border-top: 1px solid rgba(255,255,255,0.06);
  155. }
  156. .api-info-card .stat-item {
  157. display: flex;
  158. flex-direction: column;
  159. }
  160. .api-info-card .stat-label {
  161. font-size: 12px;
  162. color: var(--text-dim);
  163. }
  164. .api-info-card .stat-value {
  165. font-size: 18px;
  166. font-weight: 600;
  167. color: var(--neon);
  168. }
  169. /* ─── Tier Selection ─── */
  170. .section-title {
  171. font-size: 14px;
  172. color: var(--text-dim);
  173. margin-bottom: 12px;
  174. letter-spacing: 1px;
  175. }
  176. .tier-grid {
  177. display: grid;
  178. grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  179. gap: 14px;
  180. margin-bottom: 28px;
  181. }
  182. .tier-card {
  183. padding: 18px;
  184. cursor: pointer;
  185. border: 1px solid transparent;
  186. position: relative;
  187. overflow: hidden;
  188. }
  189. .tier-card::after {
  190. content: '';
  191. position: absolute;
  192. top: 0; left: 0; right: 0;
  193. height: 2px;
  194. background: transparent;
  195. transition: background 0.3s ease;
  196. }
  197. .tier-card:hover {
  198. transform: translateY(-1px);
  199. }
  200. .tier-card.active {
  201. border-color: var(--neon);
  202. box-shadow:
  203. 4px 4px 8px var(--shadow-dark),
  204. -4px -4px 8px var(--shadow-light),
  205. 0 0 15px var(--neon-glow);
  206. }
  207. .tier-card.active::after {
  208. background: linear-gradient(90deg, var(--neon), var(--neon-dim));
  209. }
  210. .tier-price {
  211. font-size: 28px;
  212. font-weight: 700;
  213. color: var(--neon);
  214. }
  215. .tier-price .symbol { font-size: 16px; }
  216. .tier-count {
  217. font-size: 14px;
  218. color: var(--text);
  219. margin-top: 4px;
  220. }
  221. .tier-unit-price {
  222. display: inline-block;
  223. font-size: 11px;
  224. color: var(--text-dim);
  225. background: rgba(255,255,255,0.05);
  226. padding: 2px 6px;
  227. border-radius: 4px;
  228. margin-top: 8px;
  229. }
  230. /* ─── Summary ─── */
  231. .summary-bar {
  232. padding: 20px 24px;
  233. margin-bottom: 24px;
  234. display: flex;
  235. justify-content: space-between;
  236. align-items: center;
  237. }
  238. .summary-bar .label {
  239. font-size: 14px;
  240. color: var(--text-dim);
  241. }
  242. .summary-bar .total {
  243. font-size: 28px;
  244. font-weight: 700;
  245. color: var(--neon);
  246. }
  247. .summary-bar .validity {
  248. font-size: 12px;
  249. color: var(--text-dim);
  250. margin-top: 2px;
  251. }
  252. /* ─── Pay Button (Neumorphic) ─── */
  253. .pay-btn {
  254. display: block;
  255. width: 100%;
  256. padding: 16px;
  257. border: none;
  258. cursor: pointer;
  259. font-size: 16px;
  260. font-weight: 600;
  261. letter-spacing: 2px;
  262. color: var(--text-bright);
  263. background: var(--surface);
  264. background-image: linear-gradient(145deg, rgba(0,212,255,0.15), rgba(0,0,0,0.3));
  265. border-radius: var(--radius);
  266. box-shadow:
  267. 5px 5px 10px var(--shadow-dark),
  268. -5px -5px 10px var(--shadow-light),
  269. 0 0 20px var(--neon-glow);
  270. transition: all 0.25s ease;
  271. position: relative;
  272. overflow: hidden;
  273. }
  274. .pay-btn::before {
  275. content: '';
  276. position: absolute;
  277. top: 0; left: 0; right: 0;
  278. height: 1px;
  279. background: linear-gradient(90deg, transparent, var(--neon), transparent);
  280. }
  281. .pay-btn:hover {
  282. box-shadow:
  283. 3px 3px 6px var(--shadow-dark),
  284. -3px -3px 6px var(--shadow-light),
  285. 0 0 30px var(--neon-glow-s);
  286. transform: translateY(-1px);
  287. }
  288. .pay-btn:active {
  289. box-shadow:
  290. inset 3px 3px 6px var(--shadow-dark),
  291. inset -3px -3px 6px var(--shadow-light);
  292. background-image: linear-gradient(145deg, rgba(0,0,0,0.3), rgba(0,212,255,0.1));
  293. transform: translateY(0);
  294. }
  295. .pay-btn:disabled {
  296. opacity: 0.5;
  297. cursor: not-allowed;
  298. box-shadow:
  299. 2px 2px 4px var(--shadow-dark),
  300. -2px -2px 4px var(--shadow-light);
  301. }
  302. .pay-btn .btn-icon { margin-right: 8px; }
  303. /* ─── QR Modal ─── */
  304. .modal-overlay {
  305. display: none;
  306. position: fixed;
  307. top: 0; left: 0; right: 0; bottom: 0;
  308. background: rgba(0,0,0,0.85);
  309. z-index: 100;
  310. align-items: center;
  311. justify-content: center;
  312. }
  313. .modal-overlay.show { display: flex; }
  314. .modal-box {
  315. width: 380px;
  316. max-width: 90vw;
  317. padding: 32px;
  318. text-align: center;
  319. position: relative;
  320. border: 1px solid rgba(0,212,255,0.15);
  321. }
  322. .modal-box .modal-close {
  323. position: absolute;
  324. top: 12px;
  325. right: 16px;
  326. background: none;
  327. border: none;
  328. color: var(--text-dim);
  329. font-size: 20px;
  330. cursor: pointer;
  331. transition: color 0.2s;
  332. }
  333. .modal-box .modal-close:hover { color: var(--text-bright); }
  334. .modal-box .modal-title {
  335. font-size: 18px;
  336. font-weight: 600;
  337. color: var(--text-bright);
  338. margin-bottom: 6px;
  339. }
  340. .modal-box .modal-amount {
  341. font-size: 32px;
  342. font-weight: 700;
  343. color: var(--neon);
  344. margin: 8px 0;
  345. }
  346. .modal-box .modal-amount .symbol { font-size: 18px; }
  347. .qr-wrapper {
  348. display: inline-block;
  349. padding: 16px;
  350. background: #fff;
  351. border-radius: 8px;
  352. margin: 16px 0;
  353. box-shadow: 0 0 20px var(--neon-glow);
  354. }
  355. .qr-wrapper canvas { display: block; }
  356. .modal-box .scan-hint {
  357. font-size: 13px;
  358. color: var(--text-dim);
  359. margin-top: 8px;
  360. }
  361. .modal-box .scan-hint svg {
  362. vertical-align: middle;
  363. margin-right: 4px;
  364. }
  365. .polling-status {
  366. font-size: 12px;
  367. color: var(--text-dim);
  368. margin-top: 12px;
  369. display: flex;
  370. align-items: center;
  371. justify-content: center;
  372. gap: 6px;
  373. }
  374. .polling-dot {
  375. display: inline-block;
  376. width: 6px; height: 6px;
  377. background: var(--neon);
  378. border-radius: 50%;
  379. animation: pulse 1.5s infinite;
  380. }
  381. @keyframes pulse {
  382. 0%, 100% { opacity: 0.3; }
  383. 50% { opacity: 1; }
  384. }
  385. /* ─── Success Screen ─── */
  386. .success-screen {
  387. display: none;
  388. text-align: center;
  389. padding: 48px 24px;
  390. }
  391. .success-screen.show { display: block; }
  392. .success-icon {
  393. width: 80px; height: 80px;
  394. margin: 0 auto 20px;
  395. border-radius: 50%;
  396. background: var(--surface);
  397. box-shadow:
  398. 5px 5px 10px var(--shadow-dark),
  399. -5px -5px 10px var(--shadow-light),
  400. 0 0 20px rgba(0,255,136,0.15);
  401. display: flex;
  402. align-items: center;
  403. justify-content: center;
  404. }
  405. .success-icon svg {
  406. width: 40px; height: 40px;
  407. stroke: var(--success);
  408. }
  409. .success-screen .success-title {
  410. font-size: 24px;
  411. font-weight: 700;
  412. color: var(--text-bright);
  413. margin-bottom: 8px;
  414. }
  415. .success-screen .success-detail {
  416. font-size: 14px;
  417. color: var(--text-dim);
  418. line-height: 1.8;
  419. margin-bottom: 28px;
  420. }
  421. .success-screen .back-btn {
  422. display: inline-block;
  423. padding: 12px 40px;
  424. border: none;
  425. cursor: pointer;
  426. font-size: 14px;
  427. font-weight: 600;
  428. color: var(--text-bright);
  429. background: var(--surface);
  430. background-image: linear-gradient(145deg, rgba(0,255,136,0.12), rgba(0,0,0,0.3));
  431. border-radius: var(--radius);
  432. box-shadow:
  433. 4px 4px 8px var(--shadow-dark),
  434. -4px -4px 8px var(--shadow-light),
  435. 0 0 15px rgba(0,255,136,0.1);
  436. transition: all 0.25s ease;
  437. }
  438. .success-screen .back-btn:hover {
  439. transform: translateY(-1px);
  440. box-shadow:
  441. 3px 3px 6px var(--shadow-dark),
  442. -3px -3px 6px var(--shadow-light),
  443. 0 0 25px rgba(0,255,136,0.15);
  444. }
  445. .success-screen .back-btn:active {
  446. box-shadow:
  447. inset 3px 3px 6px var(--shadow-dark),
  448. inset -3px -3px 6px var(--shadow-light);
  449. transform: translateY(0);
  450. }
  451. /* ─── Loading Skeleton ─── */
  452. .skeleton {
  453. background: linear-gradient(90deg, var(--surface) 25%, var(--surface-alt) 50%, var(--surface) 75%);
  454. background-size: 200% 100%;
  455. animation: shimmer 1.5s infinite;
  456. border-radius: 6px;
  457. }
  458. @keyframes shimmer {
  459. 0% { background-position: 200% 0; }
  460. 100% { background-position: -200% 0; }
  461. }
  462. /* ─── Error State ─── */
  463. .error-bar {
  464. display: none;
  465. padding: 12px 16px;
  466. background: rgba(255,77,106,0.1);
  467. border: 1px solid rgba(255,77,106,0.3);
  468. border-radius: 8px;
  469. color: var(--danger);
  470. font-size: 13px;
  471. margin-bottom: 16px;
  472. }
  473. .error-bar.show { display: block; }
  474. /* ─── Responsive ─── */
  475. @media (max-width: 480px) {
  476. .main-container { padding: 20px 16px; }
  477. .api-info-card { padding: 20px; }
  478. .tier-grid { grid-template-columns: 1fr; }
  479. .modal-box { padding: 24px 20px; }
  480. }
  481. </style>
  482. </head>
  483. <body>
  484. <!-- Header -->
  485. <div class="page-header">
  486. <div class="logo">BRAIN<span>HACK</span></div>
  487. <div class="subtitle">API 服务充值</div>
  488. </div>
  489. <!-- Main -->
  490. <div class="main-container" id="mainContent">
  491. <!-- API Info Card -->
  492. <div class="api-info-card neu-raised" id="apiInfoCard">
  493. <div class="api-title" id="apiTitle">
  494. <span class="skeleton" style="display:inline-block;width:200px;height:24px;">&nbsp;</span>
  495. </div>
  496. <div class="api-desc" id="apiDesc">
  497. <span class="skeleton" style="display:inline-block;width:100%;height:16px;margin-top:8px;">&nbsp;</span>
  498. </div>
  499. <div class="api-stats" id="apiStats" style="display:none;">
  500. <div class="stat-item">
  501. <span class="stat-label">当前余额</span>
  502. <span class="stat-value" id="statCount">—</span>
  503. </div>
  504. <div class="stat-item">
  505. <span class="stat-label">服务状态</span>
  506. <span class="stat-value" id="statStatus">—</span>
  507. </div>
  508. </div>
  509. </div>
  510. <!-- Error -->
  511. <div class="error-bar" id="errorBar"></div>
  512. <!-- Tier Selection -->
  513. <div class="section-title">选择套餐</div>
  514. <div class="tier-grid" id="tierGrid">
  515. <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
  516. <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
  517. <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
  518. </div>
  519. <!-- Summary -->
  520. <div class="summary-bar neu-groove" id="summaryBar" style="display:none;">
  521. <div>
  522. <div class="label">套餐配额</div>
  523. <div id="summaryCount" style="font-size:16px;font-weight:600;color:var(--text-bright);margin-top:2px;">—</div>
  524. <div class="validity">有效期 730 天(自购买之日起)</div>
  525. </div>
  526. <div style="text-align:right;">
  527. <div class="label">应付金额</div>
  528. <div class="total"><span class="symbol">¥</span><span id="summaryPrice">0</span></div>
  529. </div>
  530. </div>
  531. <!-- Pay Button -->
  532. <button class="pay-btn" id="payBtn" disabled>
  533. <span class="btn-icon">💳</span> 微信支付
  534. </button>
  535. <!-- Success Screen -->
  536. <div class="success-screen" id="successScreen">
  537. <div class="success-icon">
  538. <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
  539. <polyline points="20 6 9 17 4 12"></polyline>
  540. </svg>
  541. </div>
  542. <div class="success-title">充值成功</div>
  543. <div class="success-detail" id="successDetail"></div>
  544. <button class="back-btn" onclick="handleDone()">完成</button>
  545. </div>
  546. </div>
  547. <!-- QR Modal -->
  548. <div class="modal-overlay" id="qrModal">
  549. <div class="modal-box neu-raised">
  550. <button class="modal-close" onclick="cancelPayment()">&times;</button>
  551. <div class="modal-title">微信扫码支付</div>
  552. <div class="modal-amount"><span class="symbol">¥</span><span id="modalPrice">0</span></div>
  553. <div class="qr-wrapper" id="qrWrapper">
  554. <canvas id="qrCanvas"></canvas>
  555. </div>
  556. <div class="scan-hint">
  557. <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>
  558. 打开微信扫一扫
  559. </div>
  560. <div class="polling-status" id="pollingStatus">
  561. <span class="polling-dot"></span> 等待支付中...
  562. </div>
  563. </div>
  564. </div>
  565. <script>
  566. // ═══════════════════════════════════════════════════
  567. // APIG Payment Logic
  568. // ═══════════════════════════════════════════════════
  569. const API_BASE = 'https://server.fmode.cn';
  570. const PARSE_BASE = API_BASE + '/parse/functions';
  571. const PAY_COMPANY = '1AiWpTEDH9';
  572. const APP_ID = 'ncloudmaster';
  573. // URL params
  574. const params = new URLSearchParams(window.location.search);
  575. const authId = params.get('authid') || '';
  576. const userId = params.get('user') || params.get('userid') || '';
  577. let apig = null;
  578. let selectedIndex = 0;
  579. let order = null;
  580. let tradeNo = '';
  581. let nonceStr = '';
  582. let pollTimer = null;
  583. // ─── Init ───
  584. document.addEventListener('DOMContentLoaded', () => {
  585. if (!authId) {
  586. showError('缺少 authid 参数,请通过正确链接访问本页面。');
  587. return;
  588. }
  589. // Show loading state
  590. const titleEl = document.getElementById('apiTitle');
  591. if (titleEl) titleEl.textContent = '加载中...';
  592. loadApig();
  593. });
  594. // ─── Load APIG Info ───
  595. async function loadApig() {
  596. try {
  597. // 1. Try getApig REST endpoint (works when authId is an APIGAuth objectId)
  598. const resp = await postJSON(API_BASE + '/api/apig/getApig', { authid: authId });
  599. if (resp.code === 200 && resp.data) {
  600. apig = resp.data;
  601. applyTestTier();
  602. renderApigInfo();
  603. renderTiers();
  604. return;
  605. }
  606. // 2. Fallback: use cloud function to query APIG by objectId
  607. // Cloud function IDs: getApigInfo=t012qy4XVe, getApigAuth=H7X7y9Wfc0
  608. // Note: FmodeParse SDK uses internal dispatch; direct REST call needs actual function name
  609. console.log('getApig returned no data, trying cloud function...');
  610. const cfFuncName = params.get('cfName') || 'getApigInfo';
  611. const cfResp = await parseCloudCall(cfFuncName, {
  612. apigId: authId
  613. }).catch(e => { console.warn('cloud function error:', e); return null; });
  614. console.log('Cloud function response:', cfResp);
  615. if (cfResp && cfResp.result) {
  616. const cfData = cfResp.result.data || cfResp.result;
  617. if (cfData && cfData.objectId) {
  618. apig = cfData;
  619. applyTestTier();
  620. renderApigInfo();
  621. renderTiers();
  622. return;
  623. }
  624. }
  625. // 3. Fallback: accept APIG data from URL params (OpenClaw can pass these)
  626. const urlTitle = params.get('title');
  627. const urlPrices = params.get('prices');
  628. const urlCounts = params.get('counts');
  629. if (urlTitle && urlPrices && urlCounts) {
  630. console.log('Using APIG data from URL params');
  631. const prices = urlPrices.split(',').map(Number);
  632. const counts = urlCounts.split(',').map(Number);
  633. apig = {
  634. objectId: authId,
  635. title: urlTitle,
  636. content: params.get('desc') || '',
  637. count: parseInt(params.get('balance') || '0'),
  638. priceStep: prices.map((p, i) => ({ price: p, count: counts[i] || 0 }))
  639. };
  640. applyTestTier();
  641. renderApigInfo();
  642. renderTiers();
  643. return;
  644. }
  645. showError('无法加载接口信息。请确认 authid 对应有效的 APIGAuth 记录,或通过 URL 参数传入套餐数据。');
  646. } catch (e) {
  647. showError('网络错误: ' + e.message);
  648. }
  649. }
  650. function applyTestTier() {
  651. if (params.get('test') === '1' && apig.priceStep) {
  652. apig.priceStep.unshift({ count: 1, price: 0.01 });
  653. }
  654. }
  655. function renderApigInfo() {
  656. const titleEl = document.getElementById('apiTitle');
  657. titleEl.innerHTML = apig.title + '<span class="badge">HTTPS</span>';
  658. const descEl = document.getElementById('apiDesc');
  659. descEl.textContent = apig.content || '专业API数据服务';
  660. const statsEl = document.getElementById('apiStats');
  661. statsEl.style.display = 'flex';
  662. document.getElementById('statCount').textContent =
  663. (apig.count != null ? apig.count + ' 次' : '—');
  664. document.getElementById('statStatus').textContent = '正常';
  665. document.getElementById('statStatus').style.color = 'var(--success)';
  666. }
  667. function renderTiers() {
  668. const grid = document.getElementById('tierGrid');
  669. if (!apig.priceStep || apig.priceStep.length === 0) {
  670. grid.innerHTML = '<div style="color:var(--text-dim);">暂无可用套餐</div>';
  671. return;
  672. }
  673. grid.innerHTML = '';
  674. apig.priceStep.forEach((tier, i) => {
  675. const card = document.createElement('div');
  676. card.className = 'tier-card neu-raised' + (i === 0 ? ' active' : '');
  677. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  678. const unitPrice = (tier.price / tier.count).toFixed(3);
  679. card.innerHTML = `
  680. <div class="tier-price"><span class="symbol">¥</span>${tier.price}</div>
  681. <div class="tier-count">含 ${tier.count} ${unitLabel}</div>
  682. <div class="tier-unit-price">≈ ${unitPrice} 元/${unitLabel}</div>
  683. `;
  684. card.addEventListener('click', () => selectTier(i));
  685. grid.appendChild(card);
  686. });
  687. selectTier(0);
  688. document.getElementById('payBtn').disabled = false;
  689. document.getElementById('payBtn').addEventListener('click', startPayment);
  690. }
  691. function selectTier(idx) {
  692. selectedIndex = idx;
  693. document.querySelectorAll('.tier-card').forEach((el, i) => {
  694. el.classList.toggle('active', i === idx);
  695. if (i === idx) {
  696. el.classList.remove('neu-raised');
  697. el.classList.add('neu-pressed');
  698. } else {
  699. el.classList.remove('neu-pressed');
  700. el.classList.add('neu-raised');
  701. }
  702. });
  703. const tier = apig.priceStep[idx];
  704. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  705. document.getElementById('summaryBar').style.display = 'flex';
  706. document.getElementById('summaryCount').textContent = tier.count + ' ' + unitLabel;
  707. document.getElementById('summaryPrice').textContent = tier.price;
  708. }
  709. // ─── Payment Flow ───
  710. async function startPayment() {
  711. const btn = document.getElementById('payBtn');
  712. btn.disabled = true;
  713. btn.textContent = '正在生成支付码...';
  714. hideError();
  715. try {
  716. // 1. Generate trade number
  717. const now = new Date();
  718. tradeNo = 'C' + (userId || 'U') +
  719. now.getFullYear() +
  720. String(now.getMonth() + 1).padStart(2, '0') +
  721. String(now.getDate()).padStart(2, '0') +
  722. String(now.getHours()).padStart(2, '0') +
  723. String(now.getMinutes()).padStart(2, '0') +
  724. String(now.getSeconds()).padStart(2, '0') +
  725. now.getMilliseconds();
  726. const tier = apig.priceStep[selectedIndex];
  727. // 2. Call pay_code2 to get QR URL
  728. const payResp = await postJSON(PARSE_BASE + '/pay_code2', {
  729. _ApplicationId: APP_ID,
  730. company: PAY_COMPANY,
  731. out_trade_no: tradeNo,
  732. total_fee: +tier.price,
  733. body: apig.title + ' 接口充值'
  734. });
  735. if (!payResp.result || !payResp.result.code_url) {
  736. throw new Error('获取支付码失败');
  737. }
  738. const codeUrl = payResp.result.code_url[0];
  739. nonceStr = payResp.result.nonce_str;
  740. // 3. Create order
  741. createOrder(tier);
  742. // 4. Show QR modal
  743. document.getElementById('modalPrice').textContent = tier.price;
  744. document.getElementById('qrModal').classList.add('show');
  745. document.getElementById('pollingStatus').innerHTML =
  746. '<span class="polling-dot"></span> 等待支付中...';
  747. // Generate QR code
  748. await renderQR(codeUrl);
  749. // 5. Start polling
  750. startPolling();
  751. } catch (e) {
  752. showError('支付发起失败: ' + e.message);
  753. } finally {
  754. btn.disabled = false;
  755. btn.innerHTML = '<span class="btn-icon">💳</span> 微信支付';
  756. }
  757. }
  758. async function createOrder(tier) {
  759. try {
  760. const body = {
  761. type: 'wxpay',
  762. authid: authId,
  763. params: {
  764. out_trade_no: tradeNo,
  765. total_fee: +tier.price,
  766. body: apig.title + ' 接口充值'
  767. },
  768. apigid: apig.objectId,
  769. oldCount: apig.count || 0,
  770. count: tier.count
  771. };
  772. // Server requires fcompany or user; fallback to authId if userId is empty
  773. body.user = userId || authId;
  774. body.fcompany = userId || authId;
  775. const resp = await postJSON(API_BASE + '/api/apig/created-apigorder', body);
  776. if (resp.code === 200 && resp.data) {
  777. order = resp.data;
  778. console.log('Order created:', order);
  779. }
  780. } catch (e) {
  781. console.warn('Order creation error (non-blocking):', e.message);
  782. }
  783. }
  784. function startPolling() {
  785. if (pollTimer) clearInterval(pollTimer);
  786. pollTimer = setInterval(async () => {
  787. try {
  788. const resp = await postJSON(PARSE_BASE + '/order_status2', {
  789. _ApplicationId: APP_ID,
  790. out_trade_no: tradeNo,
  791. nonce_str: nonceStr,
  792. company: PAY_COMPANY
  793. });
  794. if (resp.result && resp.result.status && resp.result.status[0] === 'SUCCESS') {
  795. clearInterval(pollTimer);
  796. pollTimer = null;
  797. document.getElementById('pollingStatus').innerHTML =
  798. '<span style="color:var(--success);">✓ 支付成功,正在充值...</span>';
  799. await doRecharge();
  800. }
  801. } catch (e) {
  802. console.warn('Poll error:', e.message);
  803. }
  804. }, 3000);
  805. }
  806. async function doRecharge() {
  807. // Show success first, then try recharge in background (saveRecharge may timeout)
  808. showSuccess();
  809. try {
  810. const tier = apig.priceStep[selectedIndex];
  811. // Build recharge body
  812. // authid = APIGAuth objectId (T0iOotHcDX)
  813. // apigid = APIG objectId from order or from getApig response
  814. const apigObjId = apig.objectId || authId;
  815. const body = {
  816. authid: authId,
  817. apigid: apigObjId,
  818. oldCount: apig.count || 0,
  819. count: tier.count,
  820. orderid: order ? order.objectId : ''
  821. };
  822. // Server requires fcompany or user; fallback to authId if userId is empty
  823. body.user = userId || authId;
  824. body.authComp = userId || authId;
  825. body.fcompany = userId || authId;
  826. console.log('saveRecharge body:', JSON.stringify(body));
  827. // Use AbortController for 15s timeout
  828. const controller = new AbortController();
  829. const timer = setTimeout(() => controller.abort(), 15000);
  830. const resp = await fetch(API_BASE + '/api/apig/saveRecharge', {
  831. method: 'POST',
  832. headers: { 'Content-Type': 'application/json' },
  833. body: JSON.stringify(body),
  834. signal: controller.signal
  835. });
  836. clearTimeout(timer);
  837. const result = await resp.json().catch(() => null);
  838. console.log('saveRecharge response:', result);
  839. // Refresh balance display
  840. await refreshBalance();
  841. } catch (e) {
  842. console.warn('Recharge call failed (non-critical):', e.message);
  843. }
  844. }
  845. async function refreshBalance() {
  846. try {
  847. const resp = await postJSON(API_BASE + '/api/apig/getApig', { authid: authId });
  848. if (resp.code === 200 && resp.data && resp.data.count != null) {
  849. apig.count = resp.data.count;
  850. const detail = document.getElementById('successDetail');
  851. if (detail) {
  852. const tier = apig.priceStep[selectedIndex];
  853. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  854. detail.innerHTML =
  855. '已充值 <strong style="color:var(--neon);">' + apig.title + '</strong> 接口<br>' +
  856. '获得 <strong style="color:var(--success);">' + tier.count + ' ' + unitLabel + '</strong>,有效期 730 天<br>' +
  857. '<span style="color:var(--text-dim);margin-top:8px;display:inline-block;">当前余额: <strong style="color:var(--neon);">' + apig.count + ' ' + unitLabel + '</strong></span>';
  858. }
  859. console.log('Balance refreshed:', apig.count);
  860. }
  861. } catch(e) {
  862. console.warn('Balance refresh failed:', e.message);
  863. }
  864. }
  865. function showSuccess() {
  866. document.getElementById('qrModal').classList.remove('show');
  867. document.getElementById('mainContent').querySelector('.api-info-card').style.display = 'none';
  868. document.querySelector('.section-title').style.display = 'none';
  869. document.getElementById('tierGrid').style.display = 'none';
  870. document.getElementById('summaryBar').style.display = 'none';
  871. document.getElementById('payBtn').style.display = 'none';
  872. const tier = apig.priceStep[selectedIndex];
  873. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  874. document.getElementById('successDetail').innerHTML =
  875. '已充值 <strong style="color:var(--neon);">' + apig.title + '</strong> 接口<br>' +
  876. '获得 <strong style="color:var(--success);">' + tier.count + ' ' + unitLabel + '</strong>,有效期 730 天';
  877. document.getElementById('successScreen').classList.add('show');
  878. }
  879. async function renderQR(url) {
  880. const wrapper = document.getElementById('qrWrapper');
  881. const canvas = document.getElementById('qrCanvas');
  882. // Clear previous QR (img fallback)
  883. wrapper.querySelectorAll('img').forEach(i => i.remove());
  884. canvas.style.display = '';
  885. canvas.width = 200;
  886. canvas.height = 200;
  887. // Try canvas-based QRCode lib first
  888. if (typeof QRCode !== 'undefined' && QRCode && QRCode.toCanvas) {
  889. try {
  890. await QRCode.toCanvas(canvas, url, {
  891. width: 200,
  892. margin: 0,
  893. color: { dark: '#000000', light: '#ffffff' }
  894. });
  895. console.log('QR rendered via canvas');
  896. return;
  897. } catch (e) {
  898. console.warn('QRCode.toCanvas failed:', e);
  899. }
  900. }
  901. // Fallback: use img with QR server API
  902. console.log('Using img fallback for QR');
  903. canvas.style.display = 'none';
  904. const img = document.createElement('img');
  905. img.src = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(url);
  906. img.width = 200;
  907. img.height = 200;
  908. img.alt = 'Payment QR Code';
  909. img.style.display = 'block';
  910. wrapper.appendChild(img);
  911. }
  912. function handleDone() {
  913. // Notify parent window (OpenClaw integration)
  914. try {
  915. const msg = { type: 'apig-payment-done', authid: authId, user: userId };
  916. if (window.opener) window.opener.postMessage(msg, '*');
  917. if (window.parent !== window) window.parent.postMessage(msg, '*');
  918. } catch(e) { console.warn('postMessage failed:', e); }
  919. // Try to close window (works if opened via window.open)
  920. try { window.close(); } catch(e) {}
  921. setTimeout(() => {
  922. // If still here, window.close didn't work — reload page
  923. window.location.reload();
  924. }, 500);
  925. }
  926. function cancelPayment() {
  927. if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  928. document.getElementById('qrModal').classList.remove('show');
  929. }
  930. // ─── Helpers ───
  931. function showError(msg) {
  932. const el = document.getElementById('errorBar');
  933. if (!el) { console.error('errorBar not found:', msg); return; }
  934. el.textContent = msg;
  935. el.classList.add('show');
  936. }
  937. function hideError() {
  938. const el = document.getElementById('errorBar');
  939. if (el) el.classList.remove('show');
  940. }
  941. async function postJSON(url, data) {
  942. const resp = await fetch(url, {
  943. method: 'POST',
  944. headers: { 'Content-Type': 'application/json' },
  945. body: JSON.stringify(data)
  946. });
  947. return resp.json();
  948. }
  949. async function parseCloudCall(funcId, params) {
  950. const url = PARSE_BASE + '/' + funcId;
  951. const body = Object.assign({ _ApplicationId: APP_ID }, params);
  952. const resp = await fetch(url, {
  953. method: 'POST',
  954. headers: {
  955. 'Content-Type': 'application/json',
  956. 'X-Parse-Application-Id': APP_ID
  957. },
  958. body: JSON.stringify(body)
  959. });
  960. if (!resp.ok) {
  961. console.warn('Cloud function ' + funcId + ' returned ' + resp.status);
  962. return null;
  963. }
  964. return resp.json();
  965. }
  966. </script>
  967. </body>
  968. </html>