使用WhatsApp Business API创建消息模板失败问题求助
解决WhatsApp Business API创建消息模板的问题
你的核心问题是POST请求的参数传递方式错误,Facebook Graph API创建模板要求用JSON格式的请求体传递参数,而非把所有参数拼在URL查询字符串里;同时手动拼接的JSON参数存在编码问题,导致请求格式无效,引发HTTP错误。
需要修改的关键部分:
- 将所有请求参数从URL转移到POST请求体,以JSON格式发送
- 添加
Content-Type: application/json请求头,告知API请求体格式 - 使用
json_encode自动处理JSON转义,避免手动拼接的编码错误 - 修正URL,只保留API基础路径,移除查询字符串中的参数
修改后的完整代码:
public static function CreateTemplate($templateName, $templateCat, $language, $components){ $businessaccountid = .....; $token = ....; $ch = curl_init(); // 仅保留API基础路径,参数移至请求体 $url = 'https://graph.facebook.com/v16.0/' . $businessaccountid . '/message_templates'; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); // 构造JSON格式的请求体参数 $postData = json_encode([ 'allow_category_change' => true, 'name' => $templateName, 'category' => $templateCat, 'language' => $language, 'components' => $components // 直接传入数组,由json_encode处理转义 ]); $headers = array(); $headers[] = 'Authorization: Bearer ' . $token; // 必须添加Content-Type头,标识请求体格式 $headers[] = 'Content-Type: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 设置POST请求体内容 curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); $result = curl_exec($ch); if ($result === false) { $result = curl_error($ch) . " - ".curl_errno($ch); } else { $resultDecode = json_decode($result); if($resultDecode!=null){ $result = $resultDecode; } } curl_close($ch); return $result; }
调用说明:
调用方法时,$components直接传入PHP数组即可,无需手动转成JSON字符串:
$components = [ ['type' => 'BODY', 'text' => 'Obrigado por comprar na nossa loja. Assim que o objecto for expedido, irá receber no seu email o numero de rastreamento da encomenda.'], ['type' => 'FOOTER', 'text' => 'A minha empresa'] ]; CreateTemplate('compra_terminada', 'MARKETING', 'pt_PT', $components);
错误原因解析:
- 原代码将POST参数放在URL查询字符串中,不符合Graph API的请求规范,API无法正确解析参数
- 手动拼接的JSON字符串存在转义不规范问题,导致请求体格式无效
- 缺少
Content-Type: application/json请求头,API无法识别请求体的格式
内容的提问来源于stack exchange,提问作者RSilva
相关产品推荐
相关产品推荐

