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
相关产品推荐
相关产品推荐

