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

React Web应用集成WhatsApp Cloud API:如何传递模板变量?

解决WhatsApp Cloud API模板变量传递问题

要给模板中的{{1}}传入用户名称,你需要在请求体的template对象中添加components字段,用来指定模板变量的具体值。

修改后的发送代码:

const sendMessage = () => {
    const userName = "Archit"; // 替换为实际的用户名称
    const body = {
      messaging_product: "whatsapp",
      to: "91" + 8872649119,
      type: "template",
      template: {
        name: "hello_world",
        language: { code: "en_US" },
        components: [
          {
            type: "body",
            parameters: [
              {
                type: "text",
                text: userName
              }
            ]
          }
        ]
      },
    };

    axios
      .post(
        "https://graph.facebook.com/v17.0/100320906470290/messages",
        body,
        header
      )
      .then((res) => console.log("sent successfully", res))
      .catch((err) => console.log("error while sending", err));
  };

关键说明:

  • components数组用于定义模板各部分的变量值,这里变量在模板正文里,所以type设为body。
  • parameters数组的元素顺序要和模板占位符完全对应:{{1}}对应数组第一个元素,{{2}}对应第二个,以此类推。
  • 每个参数的type设为text,text字段填入你要传递的实际内容(比如用户名称)。

额外注意:

确保你在Meta平台创建的模板已包含对应文本占位符(如你提供的截图所示),且模板已通过审核并处于可用状态。

内容的提问来源于stack exchange,提问作者Archit Dadwal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 01:20:04