我正在尝试测试 Sendgrid 的工作事务模板。当值被硬编码时,我能够发送邮件,但当我为它们提供变量时却不能。让我们来看看:
我的标题:
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer my_actual_api_key',
);
我的 $data 数组:
$resetLink = 'na';
$reset = 'Please, click here to activate your account';
$user = 'MyName';
$data = ['reset'=>$reset, 'user'=>$user, 'resetLink'=>$resetLink];
$subs 是通过执行以下操作创建的:
if($data){
foreach($data as $k=>$v){
$subs.= '"{{'.$k.'}}":"'.$v.'"';
if($last_element != $v){
$subs .=",";
}
}
}
输出:
"{{reset}}": "Please, click here to activate your account.",
"{{user}}": "MyName",
"{{resetLink}}": "na"
正是我想要的!
但是,如果我这样做:
$json = '{
"personalizations": [{
"to": [{
"email": "'.$to.'",
"name": "Example 01"
}],
"subject": "'.$subject.'",
"substitutions": {
'.$subs.'
}
}],
"from": {
"email": "'.$from.'",
"name": "'.$from.'"
},
"reply_to": {
"email": "'.$from.'",
"name": "'.$from.'"
},
"template_id": "My_actual_temnplate_id"
}';
我回来了:
{"errors":[{"message":"Bad Request","field":null,"help":null}]}
但是,如果我这样做:
$json = '{
"personalizations": [{
"to": [{
"email": "'.$to.'",
"name": "Example 01"
}],
"subject": "'.$subject.'",
"substitutions": {
"{{reset}}": "Please, click here to activate your account.",
"{{user}}": "MyName",
"{{resetLink}}": "na"
}
}],
"from": {
"email": "'.$from.'",
"name": "'.$from.'"
},
"reply_to": {
"email": "'.$from.'",
"name": "'.$from.'"
},
"template_id": "1959ba19-3bc7-455b-a577-7a340f4c5fd9"
}';
我可以很好地卷曲并发送我的邮件,使用以下内容没有错误。
这是 cURL,标准的东西:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sendgrid.com/v3/mail/send");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
我也尝试将这个 json 作为一个数组,然后使用 json_encode(),也没有运气,与上面相同的错误非消息。这是在 Sendgrid 网站的某个地方提供的 json,仅供参考。
如您所见,我将所有内容都作为字符串,这占了我找到的大部分答案。有人可以解释为什么会这样吗?提前致谢!