微信公众号 API 代理配置

解决本地 IP 变动及 VPN 导致的微信白名单验证失败问题。

本方案使用 Cloudflare Worker 作为中转。请妥善保管你的 Worker 地址,防止被他人滥用。

1

创建 Cloudflare Worker

  • 登录 Cloudflare Dashboard
  • 在左侧菜单选择 Workers & Pages
  • 点击 Create ApplicationCreate Worker
  • 为服务命名(例如:wechat-proxy),然后点击 Deploy
2

部署代理代码

点击 Edit code,清空原有内容,粘贴以下代码并点击 Deploy

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 });
    }
  }
};
3

配置微信白名单

登录微信公众号后台,在 基本配置 -> IP白名单 中添加 Cloudflare 的出口 IP 段。
以下是整理好的 IP 列表(每行一个,可直接复制粘贴):

提示: Cloudflare IP 偶尔会有更新。若报错建议对照 Cloudflare 官方列表 检查。

官方页面包含 IPv4 和 IPv6,请仅复制 IPv4 列表

* 数据来源:Cloudflare Official IPs

4

插件配置

回到 Obsidian 插件设置页面:

  1. 进入 高级设置
  2. 找到 API 代理地址 选项
  3. 填入你的 Worker URL,例如:
    https://wechat-proxy.your-account.workers.dev

Generated for Obsidian WeChat Plugin