ga4-proxy.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * FeHelper GA4代理服务器
  3. * 用于转发统计数据到GA4服务器,解决国内访问GA服务器被拦截问题
  4. */
  5. const express = require('express');
  6. const fetch = require('node-fetch');
  7. const bodyParser = require('body-parser');
  8. const app = express();
  9. const PORT = process.env.PORT || 3001;
  10. // 中间件
  11. app.use(bodyParser.json());
  12. app.use((req, res, next) => {
  13. res.header('Access-Control-Allow-Origin', '*');
  14. res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  15. if (req.method === 'OPTIONS') {
  16. res.header('Access-Control-Allow-Methods', 'GET, POST');
  17. return res.status(200).json({});
  18. }
  19. next();
  20. });
  21. // 代理GA4的收集端点
  22. app.post('/mp/collect', async (req, res) => {
  23. try {
  24. const measurementId = req.query.measurement_id;
  25. const apiSecret = req.query.api_secret;
  26. if (!measurementId || !apiSecret) {
  27. return res.status(400).json({ error: '缺少必要参数' });
  28. }
  29. const gaUrl = `https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`;
  30. // 记录请求数据但不保存敏感信息
  31. console.log(`[${new Date().toISOString()}] 代理请求到GA4: ${measurementId}`);
  32. // 转发请求到GA4
  33. const gaResponse = await fetch(gaUrl, {
  34. method: 'POST',
  35. headers: {
  36. 'Content-Type': 'application/json'
  37. },
  38. body: JSON.stringify(req.body)
  39. });
  40. // 如果GA4返回成功,返回成功响应
  41. if (gaResponse.ok) {
  42. return res.status(200).json({ success: true });
  43. } else {
  44. // 如果GA4返回错误,返回错误响应
  45. const errorData = await gaResponse.text();
  46. return res.status(gaResponse.status).json({
  47. error: '转发到GA4失败',
  48. status: gaResponse.status,
  49. details: errorData
  50. });
  51. }
  52. } catch (error) {
  53. console.error('代理请求失败:', error);
  54. res.status(500).json({ error: '代理服务器内部错误' });
  55. }
  56. });
  57. // 健康检查端点
  58. app.get('/health', (req, res) => {
  59. res.status(200).json({ status: 'ok' });
  60. });
  61. // 启动服务器
  62. app.listen(PORT, () => {
  63. console.log(`FeHelper GA4代理服务器运行在 http://localhost:${PORT}`);
  64. });