You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过WhatsApp API发送多张图片?能否使用S3链接?

WhatsApp 发送多张图片失败问题及解决方案

问题根源

WhatsApp Business API 不支持在单条消息中发送多张图片,你的代码试图在image类型的消息 payload 中传入links数组,这不符合API的请求格式规范——image类型仅接受单个媒体资源的链接或ID。

S3链接的可行性

完全可以使用S3链接发送图片,但需满足两个条件:

  • 链接对应的S3对象必须是公开可访问的,或者使用带签名的临时URL(确保在发送请求时链接有效);
  • 每张图片必须作为独立的消息发送,不能批量打包在一条请求里。

修正后的代码示例

将多张图片的发送逻辑改为循环发送单个图片请求:

type TextPayload = { body: string };
type ImagePayload = { link: string }; // 注意这里是单个link,不是数组

// 默认文本消息
let messageType = "text";
let messagePayload: TextPayload | ImagePayload = { body: message };

async function sendWhatsAppMessage(toPhoneNumber: string, accessToken: string, reqUrl: string, timeout_ms: number) {
  if (type === "image") {
    const imageLinks = [
      "https://images.s3.amazonaws.com/0743.jpg",
      "https://images.s3.amazonaws.com/0743.jpg",
      // 其他图片链接...
    ];
    
    // 循环发送每张图片
    const results = [];
    for (const link of imageLinks) {
      const controller = new AbortController();
      const signal = controller.signal;
      setTimeout(() => controller.abort(), timeout_ms);
      
      try {
        const res = await fetch(reqUrl, {
          signal,
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + accessToken,
          },
          body: JSON.stringify({
            messaging_product: "whatsapp",
            to: toPhoneNumber,
            recipient_type: "individual",
            type: "image",
            image: { link } // 单个图片链接
          })
        });
        results.push(await res.json());
      } catch (err) {
        results.push({ error: err });
      }
      
      // 可选:添加短延时避免触发API频率限制
      await new Promise(resolve => setTimeout(resolve, 500));
    }
    return results;
  } else {
    // 文本消息发送逻辑
    const controller = new AbortController();
    const signal = controller.signal;
    setTimeout(() => controller.abort(), timeout_ms);
    return fetch(reqUrl, {
      signal,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + accessToken,
      },
      body: JSON.stringify({
        messaging_product: "whatsapp",
        to: toPhoneNumber,
        recipient_type: "individual",
        type: messageType,
        text: messagePayload
      })
    });
  }
}

注意事项

  • 需关注WhatsApp API的频率限制,避免短时间内发送过多请求导致被限流;
  • 确保S3链接的有效性:公开链接需正确设置桶的权限,签名链接需保证有效期覆盖发送时间;
  • 超时时间可根据实际网络情况调整,2秒可能过短,建议适当延长(如5秒)。

内容的提问来源于stack exchange,提问作者Arsene Wenger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 14:10:35