apig-pay.html 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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. // Use user field if available, fallback to fcompany
  773. if (userId) {
  774. body.user = userId;
  775. body.fcompany = userId;
  776. }
  777. const resp = await postJSON(API_BASE + '/api/apig/created-apigorder', body);
  778. if (resp.code === 200 && resp.data) {
  779. order = resp.data;
  780. console.log('Order created:', order);
  781. }
  782. } catch (e) {
  783. console.warn('Order creation error (non-blocking):', e.message);
  784. }
  785. }
  786. function startPolling() {
  787. if (pollTimer) clearInterval(pollTimer);
  788. pollTimer = setInterval(async () => {
  789. try {
  790. const resp = await postJSON(PARSE_BASE + '/order_status2', {
  791. _ApplicationId: APP_ID,
  792. out_trade_no: tradeNo,
  793. nonce_str: nonceStr,
  794. company: PAY_COMPANY
  795. });
  796. if (resp.result && resp.result.status && resp.result.status[0] === 'SUCCESS') {
  797. clearInterval(pollTimer);
  798. pollTimer = null;
  799. document.getElementById('pollingStatus').innerHTML =
  800. '<span style="color:var(--success);">✓ 支付成功,正在充值...</span>';
  801. await doRecharge();
  802. }
  803. } catch (e) {
  804. console.warn('Poll error:', e.message);
  805. }
  806. }, 3000);
  807. }
  808. async function doRecharge() {
  809. // Show success first, then try recharge in background (saveRecharge may timeout)
  810. showSuccess();
  811. try {
  812. const tier = apig.priceStep[selectedIndex];
  813. // Build recharge body
  814. // authid = APIGAuth objectId (T0iOotHcDX)
  815. // apigid = APIG objectId from order or from getApig response
  816. const apigObjId = apig.objectId || authId;
  817. const body = {
  818. authid: authId,
  819. apigid: apigObjId,
  820. oldCount: apig.count || 0,
  821. count: tier.count,
  822. orderid: order ? order.objectId : ''
  823. };
  824. if (userId) {
  825. body.user = userId;
  826. body.authComp = userId;
  827. }
  828. // Also pass fcompany for compatibility
  829. body.fcompany = userId || '';
  830. console.log('saveRecharge body:', JSON.stringify(body));
  831. // Use AbortController for 15s timeout
  832. const controller = new AbortController();
  833. const timer = setTimeout(() => controller.abort(), 15000);
  834. const resp = await fetch(API_BASE + '/api/apig/saveRecharge', {
  835. method: 'POST',
  836. headers: { 'Content-Type': 'application/json' },
  837. body: JSON.stringify(body),
  838. signal: controller.signal
  839. });
  840. clearTimeout(timer);
  841. const result = await resp.json().catch(() => null);
  842. console.log('saveRecharge response:', result);
  843. // Refresh balance display
  844. await refreshBalance();
  845. } catch (e) {
  846. console.warn('Recharge call failed (non-critical):', e.message);
  847. }
  848. }
  849. async function refreshBalance() {
  850. try {
  851. const resp = await postJSON(API_BASE + '/api/apig/getApig', { authid: authId });
  852. if (resp.code === 200 && resp.data && resp.data.count != null) {
  853. apig.count = resp.data.count;
  854. const detail = document.getElementById('successDetail');
  855. if (detail) {
  856. const tier = apig.priceStep[selectedIndex];
  857. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  858. detail.innerHTML =
  859. '已充值 <strong style="color:var(--neon);">' + apig.title + '</strong> 接口<br>' +
  860. '获得 <strong style="color:var(--success);">' + tier.count + ' ' + unitLabel + '</strong>,有效期 730 天<br>' +
  861. '<span style="color:var(--text-dim);margin-top:8px;display:inline-block;">当前余额: <strong style="color:var(--neon);">' + apig.count + ' ' + unitLabel + '</strong></span>';
  862. }
  863. console.log('Balance refreshed:', apig.count);
  864. }
  865. } catch(e) {
  866. console.warn('Balance refresh failed:', e.message);
  867. }
  868. }
  869. function showSuccess() {
  870. document.getElementById('qrModal').classList.remove('show');
  871. document.getElementById('mainContent').querySelector('.api-info-card').style.display = 'none';
  872. document.querySelector('.section-title').style.display = 'none';
  873. document.getElementById('tierGrid').style.display = 'none';
  874. document.getElementById('summaryBar').style.display = 'none';
  875. document.getElementById('payBtn').style.display = 'none';
  876. const tier = apig.priceStep[selectedIndex];
  877. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  878. document.getElementById('successDetail').innerHTML =
  879. '已充值 <strong style="color:var(--neon);">' + apig.title + '</strong> 接口<br>' +
  880. '获得 <strong style="color:var(--success);">' + tier.count + ' ' + unitLabel + '</strong>,有效期 730 天';
  881. document.getElementById('successScreen').classList.add('show');
  882. }
  883. async function renderQR(url) {
  884. const wrapper = document.getElementById('qrWrapper');
  885. const canvas = document.getElementById('qrCanvas');
  886. // Clear previous QR (img fallback)
  887. wrapper.querySelectorAll('img').forEach(i => i.remove());
  888. canvas.style.display = '';
  889. canvas.width = 200;
  890. canvas.height = 200;
  891. // Try canvas-based QRCode lib first
  892. if (typeof QRCode !== 'undefined' && QRCode && QRCode.toCanvas) {
  893. try {
  894. await QRCode.toCanvas(canvas, url, {
  895. width: 200,
  896. margin: 0,
  897. color: { dark: '#000000', light: '#ffffff' }
  898. });
  899. console.log('QR rendered via canvas');
  900. return;
  901. } catch (e) {
  902. console.warn('QRCode.toCanvas failed:', e);
  903. }
  904. }
  905. // Fallback: use img with QR server API
  906. console.log('Using img fallback for QR');
  907. canvas.style.display = 'none';
  908. const img = document.createElement('img');
  909. img.src = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(url);
  910. img.width = 200;
  911. img.height = 200;
  912. img.alt = 'Payment QR Code';
  913. img.style.display = 'block';
  914. wrapper.appendChild(img);
  915. }
  916. function handleDone() {
  917. // Notify parent window (OpenClaw integration)
  918. try {
  919. const msg = { type: 'apig-payment-done', authid: authId, user: userId };
  920. if (window.opener) window.opener.postMessage(msg, '*');
  921. if (window.parent !== window) window.parent.postMessage(msg, '*');
  922. } catch(e) { console.warn('postMessage failed:', e); }
  923. // Try to close window (works if opened via window.open)
  924. try { window.close(); } catch(e) {}
  925. setTimeout(() => {
  926. // If still here, window.close didn't work — reload page
  927. window.location.reload();
  928. }, 500);
  929. }
  930. function cancelPayment() {
  931. if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  932. document.getElementById('qrModal').classList.remove('show');
  933. }
  934. // ─── Helpers ───
  935. function showError(msg) {
  936. const el = document.getElementById('errorBar');
  937. if (!el) { console.error('errorBar not found:', msg); return; }
  938. el.textContent = msg;
  939. el.classList.add('show');
  940. }
  941. function hideError() {
  942. const el = document.getElementById('errorBar');
  943. if (el) el.classList.remove('show');
  944. }
  945. async function postJSON(url, data) {
  946. const resp = await fetch(url, {
  947. method: 'POST',
  948. headers: { 'Content-Type': 'application/json' },
  949. body: JSON.stringify(data)
  950. });
  951. return resp.json();
  952. }
  953. async function parseCloudCall(funcId, params) {
  954. const url = PARSE_BASE + '/' + funcId;
  955. const body = Object.assign({ _ApplicationId: APP_ID }, params);
  956. const resp = await fetch(url, {
  957. method: 'POST',
  958. headers: {
  959. 'Content-Type': 'application/json',
  960. 'X-Parse-Application-Id': APP_ID
  961. },
  962. body: JSON.stringify(body)
  963. });
  964. if (!resp.ok) {
  965. console.warn('Cloud function ' + funcId + ' returned ' + resp.status);
  966. return null;
  967. }
  968. return resp.json();
  969. }
  970. </script>
  971. </body>
  972. </html>