apig-pay.html 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  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. /* ─── Order History ─── */
  475. .order-history {
  476. margin-top: 36px;
  477. padding-top: 28px;
  478. border-top: 1px solid rgba(0,212,255,0.08);
  479. }
  480. .order-history .section-header {
  481. display: flex;
  482. align-items: center;
  483. justify-content: space-between;
  484. margin-bottom: 16px;
  485. }
  486. .order-history .section-header .section-title {
  487. margin-bottom: 0;
  488. }
  489. .order-history .refresh-btn {
  490. background: none;
  491. border: 1px solid rgba(0,212,255,0.2);
  492. color: var(--neon-dim);
  493. font-size: 12px;
  494. padding: 4px 12px;
  495. border-radius: 6px;
  496. cursor: pointer;
  497. transition: all 0.2s;
  498. }
  499. .order-history .refresh-btn:hover {
  500. border-color: var(--neon);
  501. color: var(--neon);
  502. background: var(--neon-glow);
  503. }
  504. .order-history .refresh-btn:disabled {
  505. opacity: 0.4;
  506. cursor: not-allowed;
  507. }
  508. .order-table {
  509. width: 100%;
  510. border-collapse: separate;
  511. border-spacing: 0;
  512. font-size: 13px;
  513. }
  514. .order-table thead th {
  515. text-align: left;
  516. padding: 10px 12px;
  517. color: var(--text-dim);
  518. font-weight: 500;
  519. font-size: 12px;
  520. letter-spacing: 0.5px;
  521. border-bottom: 1px solid rgba(255,255,255,0.06);
  522. white-space: nowrap;
  523. }
  524. .order-table tbody tr {
  525. transition: background 0.15s;
  526. }
  527. .order-table tbody tr:hover {
  528. background: rgba(0,212,255,0.03);
  529. }
  530. .order-table tbody td {
  531. padding: 12px 12px;
  532. border-bottom: 1px solid rgba(255,255,255,0.03);
  533. color: var(--text);
  534. vertical-align: middle;
  535. }
  536. .order-table tbody tr:last-child td {
  537. border-bottom: none;
  538. }
  539. .order-table .col-time {
  540. color: var(--text-dim);
  541. font-size: 12px;
  542. white-space: nowrap;
  543. }
  544. .order-table .col-amount {
  545. font-weight: 600;
  546. color: var(--neon);
  547. white-space: nowrap;
  548. }
  549. .order-table .col-count {
  550. white-space: nowrap;
  551. }
  552. .order-status {
  553. display: inline-block;
  554. font-size: 11px;
  555. font-weight: 500;
  556. padding: 2px 8px;
  557. border-radius: 4px;
  558. white-space: nowrap;
  559. }
  560. .order-status.status-paid {
  561. color: var(--success);
  562. background: rgba(0,255,136,0.08);
  563. border: 1px solid rgba(0,255,136,0.2);
  564. }
  565. .order-status.status-pending {
  566. color: #FFB800;
  567. background: rgba(255,184,0,0.08);
  568. border: 1px solid rgba(255,184,0,0.2);
  569. }
  570. .order-status.status-failed {
  571. color: var(--danger);
  572. background: rgba(255,77,106,0.08);
  573. border: 1px solid rgba(255,77,106,0.2);
  574. }
  575. .order-status.status-recharged {
  576. color: var(--neon);
  577. background: var(--neon-glow);
  578. border: 1px solid rgba(0,212,255,0.2);
  579. }
  580. .order-empty {
  581. text-align: center;
  582. padding: 32px 16px;
  583. color: var(--text-dim);
  584. font-size: 13px;
  585. }
  586. .order-empty svg {
  587. display: block;
  588. margin: 0 auto 12px;
  589. opacity: 0.3;
  590. }
  591. .order-loading {
  592. text-align: center;
  593. padding: 24px;
  594. color: var(--text-dim);
  595. font-size: 13px;
  596. }
  597. .order-loading .polling-dot {
  598. margin-right: 6px;
  599. }
  600. .order-error {
  601. text-align: center;
  602. padding: 16px;
  603. color: var(--text-dim);
  604. font-size: 12px;
  605. }
  606. .order-more-btn {
  607. display: block;
  608. width: 100%;
  609. padding: 10px;
  610. margin-top: 8px;
  611. background: none;
  612. border: 1px solid rgba(255,255,255,0.06);
  613. border-radius: 8px;
  614. color: var(--text-dim);
  615. font-size: 12px;
  616. cursor: pointer;
  617. transition: all 0.2s;
  618. }
  619. .order-more-btn:hover {
  620. border-color: rgba(0,212,255,0.2);
  621. color: var(--neon-dim);
  622. background: rgba(0,212,255,0.03);
  623. }
  624. /* ─── Responsive ─── */
  625. @media (max-width: 480px) {
  626. .main-container { padding: 20px 16px; }
  627. .api-info-card { padding: 20px; }
  628. .tier-grid { grid-template-columns: 1fr; }
  629. .modal-box { padding: 24px 20px; }
  630. .order-table { font-size: 12px; }
  631. .order-table thead th,
  632. .order-table tbody td { padding: 8px 6px; }
  633. }
  634. </style>
  635. </head>
  636. <body>
  637. <!-- Header -->
  638. <div class="page-header">
  639. <div class="logo">BRAIN<span>HACK</span></div>
  640. <div class="subtitle">API 服务充值</div>
  641. </div>
  642. <!-- Main -->
  643. <div class="main-container" id="mainContent">
  644. <!-- API Info Card -->
  645. <div class="api-info-card neu-raised" id="apiInfoCard">
  646. <div class="api-title" id="apiTitle">
  647. <span class="skeleton" style="display:inline-block;width:200px;height:24px;">&nbsp;</span>
  648. </div>
  649. <div class="api-desc" id="apiDesc">
  650. <span class="skeleton" style="display:inline-block;width:100%;height:16px;margin-top:8px;">&nbsp;</span>
  651. </div>
  652. <div class="api-stats" id="apiStats" style="display:none;">
  653. <div class="stat-item">
  654. <span class="stat-label">当前余额</span>
  655. <span class="stat-value" id="statCount">—</span>
  656. </div>
  657. <div class="stat-item">
  658. <span class="stat-label">服务状态</span>
  659. <span class="stat-value" id="statStatus">—</span>
  660. </div>
  661. </div>
  662. </div>
  663. <!-- Error -->
  664. <div class="error-bar" id="errorBar"></div>
  665. <!-- Tier Selection -->
  666. <div class="section-title">选择套餐</div>
  667. <div class="tier-grid" id="tierGrid">
  668. <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
  669. <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
  670. <div class="tier-card neu-raised skeleton" style="height:100px;"></div>
  671. </div>
  672. <!-- Summary -->
  673. <div class="summary-bar neu-groove" id="summaryBar" style="display:none;">
  674. <div>
  675. <div class="label">套餐配额</div>
  676. <div id="summaryCount" style="font-size:16px;font-weight:600;color:var(--text-bright);margin-top:2px;">—</div>
  677. <div class="validity">有效期 730 天(自购买之日起)</div>
  678. </div>
  679. <div style="text-align:right;">
  680. <div class="label">应付金额</div>
  681. <div class="total"><span class="symbol">¥</span><span id="summaryPrice">0</span></div>
  682. </div>
  683. </div>
  684. <!-- Pay Button -->
  685. <button class="pay-btn" id="payBtn" disabled>
  686. <span class="btn-icon">💳</span> 微信支付
  687. </button>
  688. <!-- Order History -->
  689. <div class="order-history" id="orderHistory" style="display:none;">
  690. <div class="section-header">
  691. <div class="section-title">历史订单</div>
  692. <button class="refresh-btn" id="refreshOrdersBtn" onclick="loadOrderHistory()">刷新</button>
  693. </div>
  694. <div class="neu-groove" style="padding:2px 16px;overflow-x:auto;">
  695. <div id="orderListBody">
  696. <div class="order-loading"><span class="polling-dot"></span> 加载中...</div>
  697. </div>
  698. </div>
  699. </div>
  700. <!-- Success Screen -->
  701. <div class="success-screen" id="successScreen">
  702. <div class="success-icon">
  703. <svg viewBox="0 0 24 24" fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
  704. <polyline points="20 6 9 17 4 12"></polyline>
  705. </svg>
  706. </div>
  707. <div class="success-title">充值成功</div>
  708. <div class="success-detail" id="successDetail"></div>
  709. <button class="back-btn" onclick="handleDone()">完成</button>
  710. </div>
  711. </div>
  712. <!-- QR Modal -->
  713. <div class="modal-overlay" id="qrModal">
  714. <div class="modal-box neu-raised">
  715. <button class="modal-close" onclick="cancelPayment()">&times;</button>
  716. <div class="modal-title">微信扫码支付</div>
  717. <div class="modal-amount"><span class="symbol">¥</span><span id="modalPrice">0</span></div>
  718. <div class="qr-wrapper" id="qrWrapper">
  719. <canvas id="qrCanvas"></canvas>
  720. </div>
  721. <div class="scan-hint">
  722. <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>
  723. 打开微信扫一扫
  724. </div>
  725. <div class="polling-status" id="pollingStatus">
  726. <span class="polling-dot"></span> 等待支付中...
  727. </div>
  728. </div>
  729. </div>
  730. <script>
  731. // ═══════════════════════════════════════════════════
  732. // APIG Payment Logic
  733. // ═══════════════════════════════════════════════════
  734. const API_BASE = 'https://server.fmode.cn';
  735. const PARSE_BASE = API_BASE + '/parse/functions';
  736. const PAY_COMPANY = '1AiWpTEDH9';
  737. const APP_ID = 'ncloudmaster';
  738. // 充值云函数ID — 微信支付回调自动执行 apigRechargeOnPay
  739. // 部署云函数后将 objectId 填入此处,或通过 URL 参数 fun_id 传入
  740. const DEFAULT_FUN_ID = 'HOkkX72PMF';
  741. // URL params
  742. const params = new URLSearchParams(window.location.search);
  743. let authId = params.get('authid') || '';
  744. const userId = params.get('user') || params.get('userid') || '';
  745. const apigId = params.get('apigid') || '';
  746. const funId = params.get('fun_id') || DEFAULT_FUN_ID;
  747. let apig = null;
  748. let selectedIndex = 0;
  749. let order = null;
  750. let tradeNo = '';
  751. let nonceStr = '';
  752. let pollTimer = null;
  753. // ─── Init ───
  754. document.addEventListener('DOMContentLoaded', () => {
  755. if (!authId && !(userId && apigId)) {
  756. showError('缺少参数。请传入 authid,或同时传入 user 和 apigid。');
  757. return;
  758. }
  759. // Show loading state
  760. const titleEl = document.getElementById('apiTitle');
  761. if (titleEl) titleEl.textContent = '加载中...';
  762. loadApig();
  763. });
  764. // ─── Load APIG Info ───
  765. async function loadApig() {
  766. try {
  767. // 如果没有 authId 但有 user+apigid,先查询/创建 APIGAuth
  768. if (!authId && userId && apigId) {
  769. console.log('[INIT] 无 authId,通过 user+apigid 查询 APIGAuth...');
  770. authId = await resolveAuthId(userId, apigId);
  771. if (!authId) {
  772. showError('无法获取或创建计费账套,请联系管理员。');
  773. return;
  774. }
  775. console.log('[INIT] 获取到 authId:', authId);
  776. }
  777. // 1. Try getApig REST endpoint (works when authId is an APIGAuth objectId)
  778. const resp = await postJSON(API_BASE + '/api/apig/getApig', { authid: authId });
  779. if (resp.code === 200 && resp.data) {
  780. apig = resp.data;
  781. applyTestTier();
  782. renderApigInfo();
  783. renderTiers();
  784. loadOrderHistory();
  785. return;
  786. }
  787. // 2. Fallback: use cloud function to query APIG by objectId
  788. console.log('getApig returned no data, trying cloud function...');
  789. const cfFuncName = params.get('cfName') || 'getApigInfo';
  790. const cfResp = await parseCloudCall(cfFuncName, {
  791. apigId: authId
  792. }).catch(e => { console.warn('cloud function error:', e); return null; });
  793. console.log('Cloud function response:', cfResp);
  794. if (cfResp && cfResp.result) {
  795. const cfData = cfResp.result.data || cfResp.result;
  796. if (cfData && cfData.objectId) {
  797. apig = cfData;
  798. applyTestTier();
  799. renderApigInfo();
  800. renderTiers();
  801. loadOrderHistory();
  802. return;
  803. }
  804. }
  805. showError('无法加载接口信息。请确认参数正确。');
  806. } catch (e) {
  807. showError('网络错误: ' + e.message);
  808. }
  809. }
  810. // ─── 通过 user+apigid 查询或创建 APIGAuth ───
  811. async function resolveAuthId(user, apig) {
  812. // 1. 查询是否已有 APIGAuth(user 对应 company,api 对应 APIG)
  813. try {
  814. const query = {
  815. _method: 'GET',
  816. where: JSON.stringify({
  817. api: { __type: 'Pointer', className: 'APIG', objectId: apig },
  818. company: { __type: 'Pointer', className: 'Company', objectId: user }
  819. }),
  820. limit: 1
  821. };
  822. const resp = await fetch(API_BASE + '/parse/classes/APIGAuth?' + new URLSearchParams(query), {
  823. headers: { 'X-Parse-Application-Id': APP_ID }
  824. });
  825. const data = await resp.json();
  826. if (data.results && data.results.length > 0) {
  827. console.log('[resolveAuthId] 找到已有 APIGAuth:', data.results[0].objectId);
  828. return data.results[0].objectId;
  829. }
  830. } catch (e) {
  831. console.warn('[resolveAuthId] 查询失败:', e.message);
  832. }
  833. // 2. 不存在则创建新的 APIGAuth
  834. try {
  835. console.log('[resolveAuthId] 未找到 APIGAuth,创建新记录...');
  836. const createResp = await fetch(API_BASE + '/parse/classes/APIGAuth', {
  837. method: 'POST',
  838. headers: {
  839. 'X-Parse-Application-Id': APP_ID,
  840. 'Content-Type': 'application/json'
  841. },
  842. body: JSON.stringify({
  843. api: { __type: 'Pointer', className: 'APIG', objectId: apig },
  844. company: { __type: 'Pointer', className: 'Company', objectId: user },
  845. count: 0,
  846. used: 0
  847. })
  848. });
  849. const created = await createResp.json();
  850. if (created.objectId) {
  851. console.log('[resolveAuthId] 创建成功:', created.objectId);
  852. return created.objectId;
  853. }
  854. console.error('[resolveAuthId] 创建失败:', JSON.stringify(created));
  855. } catch (e) {
  856. console.error('[resolveAuthId] 创建异常:', e.message);
  857. }
  858. return null;
  859. }
  860. function applyTestTier() {
  861. if (params.get('test') === '1' && apig.priceStep) {
  862. apig.priceStep.unshift({ count: 1, price: 0.01 });
  863. }
  864. }
  865. function renderApigInfo() {
  866. const titleEl = document.getElementById('apiTitle');
  867. titleEl.innerHTML = apig.title + '<span class="badge">HTTPS</span>';
  868. const descEl = document.getElementById('apiDesc');
  869. descEl.textContent = apig.content || '专业API数据服务';
  870. const statsEl = document.getElementById('apiStats');
  871. statsEl.style.display = 'flex';
  872. document.getElementById('statCount').textContent =
  873. (apig.count != null ? apig.count + ' 次' : '—');
  874. document.getElementById('statStatus').textContent = '正常';
  875. document.getElementById('statStatus').style.color = 'var(--success)';
  876. }
  877. function renderTiers() {
  878. const grid = document.getElementById('tierGrid');
  879. if (!apig.priceStep || apig.priceStep.length === 0) {
  880. grid.innerHTML = '<div style="color:var(--text-dim);">暂无可用套餐</div>';
  881. return;
  882. }
  883. grid.innerHTML = '';
  884. apig.priceStep.forEach((tier, i) => {
  885. const card = document.createElement('div');
  886. card.className = 'tier-card neu-raised' + (i === 0 ? ' active' : '');
  887. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  888. const unitPrice = (tier.price / tier.count).toFixed(3);
  889. card.innerHTML = `
  890. <div class="tier-price"><span class="symbol">¥</span>${tier.price}</div>
  891. <div class="tier-count">含 ${tier.count} ${unitLabel}</div>
  892. <div class="tier-unit-price">≈ ${unitPrice} 元/${unitLabel}</div>
  893. `;
  894. card.addEventListener('click', () => selectTier(i));
  895. grid.appendChild(card);
  896. });
  897. selectTier(0);
  898. document.getElementById('payBtn').disabled = false;
  899. document.getElementById('payBtn').addEventListener('click', startPayment);
  900. }
  901. function selectTier(idx) {
  902. selectedIndex = idx;
  903. document.querySelectorAll('.tier-card').forEach((el, i) => {
  904. el.classList.toggle('active', i === idx);
  905. if (i === idx) {
  906. el.classList.remove('neu-raised');
  907. el.classList.add('neu-pressed');
  908. } else {
  909. el.classList.remove('neu-pressed');
  910. el.classList.add('neu-raised');
  911. }
  912. });
  913. const tier = apig.priceStep[idx];
  914. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  915. document.getElementById('summaryBar').style.display = 'flex';
  916. document.getElementById('summaryCount').textContent = tier.count + ' ' + unitLabel;
  917. document.getElementById('summaryPrice').textContent = tier.price;
  918. }
  919. // ─── Payment Flow ───
  920. async function startPayment() {
  921. const btn = document.getElementById('payBtn');
  922. btn.disabled = true;
  923. btn.textContent = '正在生成支付码...';
  924. hideError();
  925. try {
  926. // 1. Generate trade number
  927. const now = new Date();
  928. tradeNo = 'C' + (userId || 'U') +
  929. now.getFullYear() +
  930. String(now.getMonth() + 1).padStart(2, '0') +
  931. String(now.getDate()).padStart(2, '0') +
  932. String(now.getHours()).padStart(2, '0') +
  933. String(now.getMinutes()).padStart(2, '0') +
  934. String(now.getSeconds()).padStart(2, '0') +
  935. now.getMilliseconds();
  936. const tier = apig.priceStep[selectedIndex];
  937. // 2. Create order FIRST (so backend callback can find it)
  938. console.log('[PAY] Creating order...', { tradeNo, tier: tier.price, funId });
  939. await createOrder(tier);
  940. console.log('[PAY] Order created, order=', order);
  941. // 3. Call pay_code2 to get QR URL (with fun_id for auto-recharge)
  942. const payParams = {
  943. _ApplicationId: APP_ID,
  944. company: PAY_COMPANY,
  945. out_trade_no: tradeNo,
  946. total_fee: +tier.price,
  947. body: apig.title + ' 接口充值'
  948. };
  949. // 传入 fun_id: 微信支付成功后回调自动执行充值云函数
  950. if (funId) {
  951. payParams.fun_id = funId;
  952. }
  953. console.log('[PAY] Calling pay_code2 with params:', JSON.stringify(payParams));
  954. let payResp = null;
  955. try {
  956. const payController = new AbortController();
  957. const payTimeout = setTimeout(() => payController.abort(), 15000);
  958. const rawResp = await fetch(PARSE_BASE + '/pay_code2', {
  959. method: 'POST',
  960. headers: { 'Content-Type': 'application/json' },
  961. body: JSON.stringify(payParams),
  962. signal: payController.signal
  963. });
  964. clearTimeout(payTimeout);
  965. payResp = await rawResp.json();
  966. console.log('[PAY] pay_code2 response:', JSON.stringify(payResp));
  967. } catch (fetchErr) {
  968. console.error('[PAY] pay_code2 fetch error:', fetchErr.message);
  969. // 如果带 fun_id 请求失败,尝试不带 fun_id 重试
  970. if (payParams.fun_id) {
  971. console.log('[PAY] Retrying pay_code2 WITHOUT fun_id...');
  972. delete payParams.fun_id;
  973. payResp = await postJSON(PARSE_BASE + '/pay_code2', payParams);
  974. console.log('[PAY] pay_code2 retry response:', JSON.stringify(payResp));
  975. } else {
  976. throw fetchErr;
  977. }
  978. }
  979. if (!payResp || !payResp.result || !payResp.result.code_url) {
  980. throw new Error('获取支付码失败: ' + JSON.stringify(payResp));
  981. }
  982. const codeUrl = payResp.result.code_url[0];
  983. nonceStr = payResp.result.nonce_str;
  984. console.log('[PAY] QR code URL:', codeUrl);
  985. // 4. Show QR modal
  986. document.getElementById('modalPrice').textContent = tier.price;
  987. document.getElementById('qrModal').classList.add('show');
  988. document.getElementById('pollingStatus').innerHTML =
  989. '<span class="polling-dot"></span> 等待支付中...';
  990. // Generate QR code
  991. await renderQR(codeUrl);
  992. // 5. Start polling
  993. startPolling();
  994. } catch (e) {
  995. showError('支付发起失败: ' + e.message);
  996. } finally {
  997. btn.disabled = false;
  998. btn.innerHTML = '<span class="btn-icon">💳</span> 微信支付';
  999. }
  1000. }
  1001. async function createOrder(tier) {
  1002. try {
  1003. const body = {
  1004. type: 'wxpay',
  1005. authid: authId,
  1006. params: {
  1007. out_trade_no: tradeNo,
  1008. total_fee: +tier.price,
  1009. body: apig.title + ' 接口充值'
  1010. },
  1011. apigid: apig.objectId,
  1012. oldCount: apig.count || 0,
  1013. count: tier.count
  1014. };
  1015. // Server requires fcompany or user; fallback to authId if userId is empty
  1016. body.user = userId || authId;
  1017. body.fcompany = userId || authId;
  1018. const resp = await postJSON(API_BASE + '/api/apig/created-apigorder', body);
  1019. if (resp.code === 200 && resp.data) {
  1020. order = resp.data;
  1021. console.log('Order created:', order);
  1022. }
  1023. } catch (e) {
  1024. console.warn('Order creation error (non-blocking):', e.message);
  1025. }
  1026. }
  1027. function startPolling() {
  1028. if (pollTimer) clearInterval(pollTimer);
  1029. pollTimer = setInterval(async () => {
  1030. try {
  1031. const resp = await postJSON(PARSE_BASE + '/order_status2', {
  1032. _ApplicationId: APP_ID,
  1033. out_trade_no: tradeNo,
  1034. nonce_str: nonceStr,
  1035. company: PAY_COMPANY
  1036. });
  1037. if (resp.result && resp.result.status && resp.result.status[0] === 'SUCCESS') {
  1038. clearInterval(pollTimer);
  1039. pollTimer = null;
  1040. document.getElementById('pollingStatus').innerHTML =
  1041. '<span style="color:var(--success);">✓ 支付成功,正在充值...</span>';
  1042. await doRecharge();
  1043. }
  1044. } catch (e) {
  1045. console.warn('Poll error:', e.message);
  1046. }
  1047. }, 3000);
  1048. }
  1049. async function doRecharge() {
  1050. showSuccess();
  1051. const oldCount = apig.count || 0;
  1052. const tier = apig.priceStep[selectedIndex];
  1053. console.log('═══ [RECHARGE] 开始 ═══ oldCount:', oldCount, 'addCount:', tier.count, 'fun_id:', funId);
  1054. // 步骤1: 等待后端微信回调自动执行云函数(fun_id 机制)
  1055. // 轮询 8 次(间隔 3 秒,共 24 秒)— 微信回调通常 5~15 秒到达
  1056. for (let i = 1; i <= 8; i++) {
  1057. console.log('[RECHARGE] 步骤1: 等待后端回调... 第' + i + '/8次 (3秒后)');
  1058. await new Promise(r => setTimeout(r, 3000));
  1059. await refreshBalance();
  1060. if (apig.count > oldCount) {
  1061. console.log('[RECHARGE] ✅ 后端回调充值成功! 余额:', oldCount, '→', apig.count);
  1062. console.log('═══ [RECHARGE] 结束 ═══ 最终余额:', apig.count);
  1063. loadOrderHistory();
  1064. return;
  1065. }
  1066. }
  1067. // 步骤2: 后端回调未生效,调用 saveRecharge 保底
  1068. console.log('[RECHARGE] 步骤2: 后端回调未生效,调用 saveRecharge 保底...');
  1069. try {
  1070. const rechargeBody = {
  1071. user: userId || authId,
  1072. authComp: userId || authId,
  1073. authid: authId,
  1074. apigid: apig.objectId,
  1075. oldCount: oldCount,
  1076. count: tier.count,
  1077. orderid: order ? order.objectId : ''
  1078. };
  1079. console.log('[RECHARGE] saveRecharge 参数:', JSON.stringify(rechargeBody));
  1080. const rechargeResp = await postJSON(API_BASE + '/api/apig/saveRecharge', rechargeBody);
  1081. console.log('[RECHARGE] saveRecharge 响应:', JSON.stringify(rechargeResp));
  1082. } catch (e) {
  1083. console.warn('[RECHARGE] saveRecharge 失败:', e.message);
  1084. }
  1085. // 步骤3: 再轮询 3 次确认余额(saveRecharge 或延迟回调)
  1086. for (let i = 1; i <= 3; i++) {
  1087. await new Promise(r => setTimeout(r, 2000));
  1088. await refreshBalance();
  1089. if (apig.count > oldCount) {
  1090. console.log('[RECHARGE] ✅ saveRecharge 充值成功! 余额:', oldCount, '→', apig.count);
  1091. break;
  1092. }
  1093. console.log('[RECHARGE] 步骤3: 第' + i + '次余额未变 (' + apig.count + ')');
  1094. }
  1095. if (apig.count <= oldCount) {
  1096. console.warn('[RECHARGE] ⚠️ 充值可能延迟,请稍后刷新页面查看');
  1097. }
  1098. console.log('═══ [RECHARGE] 结束 ═══ 最终余额:', apig.count);
  1099. loadOrderHistory();
  1100. }
  1101. async function refreshBalance() {
  1102. try {
  1103. const resp = await postJSON(API_BASE + '/api/apig/getApig', { authid: authId });
  1104. if (resp.code === 200 && resp.data && resp.data.count != null) {
  1105. apig.count = resp.data.count;
  1106. const detail = document.getElementById('successDetail');
  1107. if (detail) {
  1108. const tier = apig.priceStep[selectedIndex];
  1109. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  1110. detail.innerHTML =
  1111. '已充值 <strong style="color:var(--neon);">' + apig.title + '</strong> 接口<br>' +
  1112. '获得 <strong style="color:var(--success);">' + tier.count + ' ' + unitLabel + '</strong>,有效期 730 天<br>' +
  1113. '<span style="color:var(--text-dim);margin-top:8px;display:inline-block;">当前余额: <strong style="color:var(--neon);">' + apig.count + ' ' + unitLabel + '</strong></span>';
  1114. }
  1115. console.log('Balance refreshed:', apig.count);
  1116. }
  1117. } catch(e) {
  1118. console.warn('Balance refresh failed:', e.message);
  1119. }
  1120. }
  1121. function showSuccess() {
  1122. document.getElementById('qrModal').classList.remove('show');
  1123. document.getElementById('mainContent').querySelector('.api-info-card').style.display = 'none';
  1124. document.querySelector('.section-title').style.display = 'none';
  1125. document.getElementById('tierGrid').style.display = 'none';
  1126. document.getElementById('summaryBar').style.display = 'none';
  1127. document.getElementById('payBtn').style.display = 'none';
  1128. const tier = apig.priceStep[selectedIndex];
  1129. const unitLabel = (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ') ? 'token' : '次';
  1130. document.getElementById('successDetail').innerHTML =
  1131. '已充值 <strong style="color:var(--neon);">' + apig.title + '</strong> 接口<br>' +
  1132. '获得 <strong style="color:var(--success);">' + tier.count + ' ' + unitLabel + '</strong>,有效期 730 天';
  1133. document.getElementById('successScreen').classList.add('show');
  1134. }
  1135. async function renderQR(url) {
  1136. const wrapper = document.getElementById('qrWrapper');
  1137. const canvas = document.getElementById('qrCanvas');
  1138. // Clear previous QR (img fallback)
  1139. wrapper.querySelectorAll('img').forEach(i => i.remove());
  1140. canvas.style.display = '';
  1141. canvas.width = 200;
  1142. canvas.height = 200;
  1143. // Try canvas-based QRCode lib first
  1144. if (typeof QRCode !== 'undefined' && QRCode && QRCode.toCanvas) {
  1145. try {
  1146. await QRCode.toCanvas(canvas, url, {
  1147. width: 200,
  1148. margin: 0,
  1149. color: { dark: '#000000', light: '#ffffff' }
  1150. });
  1151. console.log('QR rendered via canvas');
  1152. return;
  1153. } catch (e) {
  1154. console.warn('QRCode.toCanvas failed:', e);
  1155. }
  1156. }
  1157. // Fallback: use img with QR server API
  1158. console.log('Using img fallback for QR');
  1159. canvas.style.display = 'none';
  1160. const img = document.createElement('img');
  1161. img.src = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' + encodeURIComponent(url);
  1162. img.width = 200;
  1163. img.height = 200;
  1164. img.alt = 'Payment QR Code';
  1165. img.style.display = 'block';
  1166. wrapper.appendChild(img);
  1167. }
  1168. function handleDone() {
  1169. // Notify parent window (OpenClaw integration)
  1170. try {
  1171. const msg = { type: 'apig-payment-done', authid: authId, user: userId };
  1172. if (window.opener) window.opener.postMessage(msg, '*');
  1173. if (window.parent !== window) window.parent.postMessage(msg, '*');
  1174. } catch(e) { console.warn('postMessage failed:', e); }
  1175. // Try to close window (works if opened via window.open)
  1176. try { window.close(); } catch(e) {}
  1177. setTimeout(() => {
  1178. // If still here, window.close didn't work — reload page
  1179. window.location.reload();
  1180. }, 500);
  1181. }
  1182. function cancelPayment() {
  1183. if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
  1184. document.getElementById('qrModal').classList.remove('show');
  1185. }
  1186. // ─── Order History ───
  1187. let orderSkip = 0;
  1188. const ORDER_PAGE_SIZE = 10;
  1189. async function loadOrderHistory(append) {
  1190. const container = document.getElementById('orderListBody');
  1191. const section = document.getElementById('orderHistory');
  1192. const refreshBtn = document.getElementById('refreshOrdersBtn');
  1193. section.style.display = '';
  1194. if (refreshBtn) refreshBtn.disabled = true;
  1195. if (!append) {
  1196. orderSkip = 0;
  1197. container.innerHTML = '<div class="order-loading"><span class="polling-dot"></span> 加载中...</div>';
  1198. }
  1199. try {
  1200. // Query APIGOrder class via Parse REST API
  1201. // Orders link to user via fromCompany/fromUser Pointer whose objectId = userId or authId
  1202. const userVal = userId || authId;
  1203. const where = JSON.stringify({
  1204. '$or': [
  1205. { fromCompany: { __type: 'Pointer', className: 'Company', objectId: userVal } },
  1206. { fromUser: { __type: 'Pointer', className: '_User', objectId: userVal } }
  1207. ]
  1208. });
  1209. const qs = new URLSearchParams({
  1210. where: where,
  1211. order: '-createdAt',
  1212. limit: String(ORDER_PAGE_SIZE),
  1213. skip: String(orderSkip)
  1214. });
  1215. const resp = await fetch(API_BASE + '/parse/classes/APIGOrder?' + qs.toString(), {
  1216. headers: {
  1217. 'X-Parse-Application-Id': APP_ID
  1218. }
  1219. });
  1220. if (!resp.ok) throw new Error('HTTP ' + resp.status);
  1221. const data = await resp.json();
  1222. const orders = data.results || [];
  1223. console.log('Order history loaded:', orders.length, 'skip:', orderSkip);
  1224. if (!append) {
  1225. if (orders.length === 0) {
  1226. container.innerHTML =
  1227. '<div class="order-empty">' +
  1228. '<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M9 5H7a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/></svg>' +
  1229. '暂无订单记录</div>';
  1230. if (refreshBtn) refreshBtn.disabled = false;
  1231. return;
  1232. }
  1233. container.innerHTML = '';
  1234. // Build table
  1235. const table = document.createElement('table');
  1236. table.className = 'order-table';
  1237. table.innerHTML =
  1238. '<thead><tr>' +
  1239. '<th>时间</th>' +
  1240. '<th>套餐</th>' +
  1241. '<th>金额</th>' +
  1242. '<th>状态</th>' +
  1243. '</tr></thead>';
  1244. const tbody = document.createElement('tbody');
  1245. tbody.id = 'orderTbody';
  1246. table.appendChild(tbody);
  1247. container.appendChild(table);
  1248. }
  1249. const tbody = document.getElementById('orderTbody');
  1250. orders.forEach(o => {
  1251. const tr = document.createElement('tr');
  1252. tr.innerHTML = formatOrderRow(o);
  1253. tbody.appendChild(tr);
  1254. });
  1255. // Remove old "load more" button
  1256. const oldMore = container.querySelector('.order-more-btn');
  1257. if (oldMore) oldMore.remove();
  1258. // Show "load more" if there might be more records
  1259. if (orders.length >= ORDER_PAGE_SIZE) {
  1260. orderSkip += ORDER_PAGE_SIZE;
  1261. const moreBtn = document.createElement('button');
  1262. moreBtn.className = 'order-more-btn';
  1263. moreBtn.textContent = '加载更多...';
  1264. moreBtn.onclick = () => loadOrderHistory(true);
  1265. container.appendChild(moreBtn);
  1266. }
  1267. } catch (e) {
  1268. console.warn('Order history error:', e);
  1269. if (!append) {
  1270. container.innerHTML =
  1271. '<div class="order-error">订单加载失败: ' + e.message + '</div>';
  1272. }
  1273. }
  1274. if (refreshBtn) refreshBtn.disabled = false;
  1275. }
  1276. function formatOrderRow(o) {
  1277. // Time
  1278. const dt = o.createdAt ? new Date(o.createdAt) : null;
  1279. const timeStr = dt
  1280. ? dt.getFullYear() + '-' +
  1281. String(dt.getMonth() + 1).padStart(2, '0') + '-' +
  1282. String(dt.getDate()).padStart(2, '0') + ' ' +
  1283. String(dt.getHours()).padStart(2, '0') + ':' +
  1284. String(dt.getMinutes()).padStart(2, '0')
  1285. : '—';
  1286. // Count — from detail.addCount or count field
  1287. const count = (o.detail && o.detail.addCount) || o.count || '—';
  1288. const unitLabel = (apig && (apig.objectId === 'MYM5zJBKgw' || apig.objectId === 'FQtTgjcqIZ')) ? 'token' : '次';
  1289. const countStr = count !== '—' ? count + ' ' + unitLabel : '—';
  1290. // Amount — from price field
  1291. const fee = o.price != null ? o.price : null;
  1292. const amountStr = fee != null ? '¥' + fee : '—';
  1293. // Status
  1294. const status = resolveOrderStatus(o);
  1295. return '<td class="col-time">' + timeStr + '</td>' +
  1296. '<td class="col-count">' + countStr + '</td>' +
  1297. '<td class="col-amount">' + amountStr + '</td>' +
  1298. '<td>' + status + '</td>';
  1299. }
  1300. function resolveOrderStatus(o) {
  1301. // isPay is the primary payment status flag in APIGOrder
  1302. if (o.isPay === true) {
  1303. // Check if recharge was applied (detail.oldCount exists and addCount exists)
  1304. if (o.detail && o.detail.addCount && o.detail.oldCount != null) {
  1305. return '<span class="order-status status-recharged">已充值</span>';
  1306. }
  1307. return '<span class="order-status status-paid">已支付</span>';
  1308. }
  1309. if (o.isPay === false) {
  1310. // Unpaid — check if expired (>30 min old)
  1311. const age = Date.now() - new Date(o.createdAt).getTime();
  1312. if (age > 30 * 60 * 1000) {
  1313. return '<span class="order-status status-failed">已过期</span>';
  1314. }
  1315. return '<span class="order-status status-pending">待支付</span>';
  1316. }
  1317. return '<span class="order-status status-pending">未知</span>';
  1318. }
  1319. // ─── Helpers ───
  1320. function showError(msg) {
  1321. const el = document.getElementById('errorBar');
  1322. if (!el) { console.error('errorBar not found:', msg); return; }
  1323. el.textContent = msg;
  1324. el.classList.add('show');
  1325. }
  1326. function hideError() {
  1327. const el = document.getElementById('errorBar');
  1328. if (el) el.classList.remove('show');
  1329. }
  1330. async function postJSON(url, data) {
  1331. const resp = await fetch(url, {
  1332. method: 'POST',
  1333. headers: { 'Content-Type': 'application/json' },
  1334. body: JSON.stringify(data)
  1335. });
  1336. return resp.json();
  1337. }
  1338. async function parseCloudCall(funcId, params) {
  1339. const url = PARSE_BASE + '/' + funcId;
  1340. const body = Object.assign({ _ApplicationId: APP_ID }, params);
  1341. const resp = await fetch(url, {
  1342. method: 'POST',
  1343. headers: {
  1344. 'Content-Type': 'application/json',
  1345. 'X-Parse-Application-Id': APP_ID
  1346. },
  1347. body: JSON.stringify(body)
  1348. });
  1349. if (!resp.ok) {
  1350. console.warn('Cloud function ' + funcId + ' returned ' + resp.status);
  1351. return null;
  1352. }
  1353. return resp.json();
  1354. }
  1355. </script>
  1356. </body>
  1357. </html>