Back to Chats

微信公众号 API 代理设置指南

Summary

🔧 微信公众号 API 代理设置指南

由于微信公众号 API 强制要求 IP 白名单验证,而本地电脑通常使用动态 IP 或 VPN,这会导致请求被微信拦截。我们可以通过部署一个 Cloudflare Worker 来解决此问题,利用 Cloudflare 相对固定的出口 IP 段进行白名单配置。

第一步:创建 Cloudflare Worker

  1. 登录 Cloudflare Dashboard
  2. 在左侧菜单选择 Workers & PagesCreate ApplicationCreate Worker
  3. 为服务命名(建议命名为 wechat-proxy),点击 Deploy 部署初始版本。

第二步:编辑 Worker 代码

点击 Edit code 进入代码编辑器,删除所有原有代码,粘贴以下增强版代码。

注意:此代码已包含 CORS 处理逻辑,支持跨域调用。

export default {
  async fetch(request, env) {
    const corsHeaders = {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    };

    // 处理 CORS 预检请求
    if (request.method === 'OPTIONS') {
      return new Response(null, { headers: corsHeaders });
    }

    if (request.method !== 'POST') {
      return new Response('Method Not Allowed', { status: 405, headers: corsHeaders });
    }

    try {
      const body = await request.json();
      const { url, method = 'GET', data, fileData, fileName, mimeType, fieldName } = body;
      
      // === Debug Logging ===
      console.log('Received URL:', url);
      
      // 安全校验:只允许访问微信 API
      if (!url || !url.startsWith('https://api.weixin.qq.com/')) {
        const errorMsg = `Invalid URL. Expected: starts with https://api.weixin.qq.com/. FLASH: Received [${typeof url}]: ${url}`;
        return new Response(JSON.stringify({ error: errorMsg, receivedBody: body }), { status: 400, headers: corsHeaders });
      }

      let response;
      if (method === 'UPLOAD' && fileData) {
        // 文件上传处理:Base64 -> Binary -> FormData
        const binary = atob(fileData);
        const bytes = new Uint8Array(binary.length);
        for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
        
        const formData = new FormData();
        formData.append(fieldName || 'media', new Blob([bytes], { type: mimeType }), fileName);
        response = await fetch(url, { method: 'POST', body: formData });
      } else {
        // 普通 JSON 请求
        const opts = { method, headers: { 'Content-Type': 'application/json' } };
        if (method !== 'GET' && data) opts.body = JSON.stringify(data);
        response = await fetch(url, opts);
      }

      const result = await response.json();
      return new Response(JSON.stringify(result), {
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      return new Response(JSON.stringify({ error: `Server Error: ${error.message}`, stack: error.stack }), { status: 500, headers: corsHeaders });
    }
  }
};

点击 Deploy 保存并发布。

第三步:配置微信 IP 白名单

你需要将 Cloudflare 的出口 IP 添加到微信公众号后台。

  1. 登录 微信公众号平台
  2. 进入 基本配置IP白名单修改
  3. 复制以下 IP 列表,粘贴到输入框中并保存:
173.245.48.0/20
103.21.244.0/22
103.22.200.0/22
103.31.4.0/22
141.101.64.0/18
108.162.192.0/18
190.93.240.0/20
188.114.96.0/20
197.234.240.0/22
198.41.128.0/17
162.158.0.0/15
104.16.0.0/13
104.24.0.0/14
172.64.0.0/13
131.0.72.0/22

⚠️ 提示:Cloudflare 的 IP 列表可能会偶发变动,若出现连接问题,请查阅 Cloudflare 官方 IP 列表。 官方页面同时包含 IPv4 和 IPv6 列表,请仅复制 IPv4 列表

第四步:插件设置

  1. 打开 Obsidian,进入本插件设置页。
  2. 找到 高级设置 (Advanced Settings)。
  3. API 代理地址 中填入你的 Worker 完整 URL: https://wechat-proxy.your-name.workers.dev

Conversation Log

Open in New Tab