mock-balance-server.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Mock API 服务器 — 模拟"余额不足"响应
  3. * 用于测试 OpenClaw 是否能正确识别 errorHandling 条件并弹出充值网址
  4. *
  5. * 启动: node scripts/mock-balance-server.js
  6. * 端点: POST http://localhost:3899/api/mock/skill
  7. * - 默认返回 { code: -2, msg: "余额不足,请充值后重试" }
  8. * - 加 ?mode=ok 返回 { code: 200, data: { workId: "mock123" } }
  9. * - 加 ?mode=unauth 返回 { code: 401, msg: "unauthorized token" }
  10. */
  11. const http = require('http');
  12. const PORT = 3899;
  13. const RESPONSES = {
  14. insufficient: {
  15. code: -2,
  16. msg: '余额不足,请充值后重试',
  17. message: '余额不足,请充值后重试'
  18. },
  19. ok: {
  20. code: 200,
  21. data: { workId: 'mock_' + Date.now() }
  22. },
  23. unauth: {
  24. code: 401,
  25. msg: 'unauthorized token invalid'
  26. }
  27. };
  28. const server = http.createServer((req, res) => {
  29. // CORS headers
  30. res.setHeader('Access-Control-Allow-Origin', '*');
  31. res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  32. res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Parse-Application-Id');
  33. if (req.method === 'OPTIONS') {
  34. res.writeHead(204);
  35. res.end();
  36. return;
  37. }
  38. const url = new URL(req.url, `http://localhost:${PORT}`);
  39. const mode = url.searchParams.get('mode') || 'insufficient';
  40. const body = RESPONSES[mode] || RESPONSES.insufficient;
  41. console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} => mode=${mode}`);
  42. console.log(` Response: ${JSON.stringify(body)}`);
  43. res.writeHead(200, { 'Content-Type': 'application/json' });
  44. res.end(JSON.stringify(body));
  45. });
  46. server.listen(PORT, () => {
  47. console.log(`\n╔══════════════════════════════════════════════════════╗`);
  48. console.log(`║ Mock Balance Server 已启动 ║`);
  49. console.log(`╚══════════════════════════════════════════════════════╝`);
  50. console.log(`\n 余额不足: POST http://localhost:${PORT}/api/mock/skill`);
  51. console.log(` 正常响应: POST http://localhost:${PORT}/api/mock/skill?mode=ok`);
  52. console.log(` 未授权: POST http://localhost:${PORT}/api/mock/skill?mode=unauth`);
  53. console.log(`\n等待请求...\n`);
  54. });