腾讯云提供了众多的API接口,方便开发者在自己的应用中使用。本文是作者在调用腾讯云邮件发送接口时所踩过的坑,特发此文章以作记录。
腾讯云API密钥
在使用腾讯云API接口之前,首先需要获取API密钥。API密钥由SecretId和SecretKey组成,可在腾讯云控制台上进行申请和管理。申请完成后,开发者需要将SecretId和SecretKey保存到本地,用于后续的API接口调用。
API调用
根据腾讯云v1签名文档中的PHP案例,最终生成如下代码:
public function test(){
$secretId = 'your secretId';
$secretKey = 'your secretKey';
$param = [
//公共参数
'Action' => 'SendEmail',
'Version' => '2020-10-02',
'Region' => 'ap-hongkong',
'Timestamp' => time(),
'Nonce' => rand(),
'SecretId' => $secretId,
//接口参数
'FromEmailAddress' => '发送方邮箱',
'Destination.0' => "接收方邮箱",
'Subject' => '主题',
'Template.TemplateID' => 85147, //模板id
'Template.TemplateData' => json_encode([
'name' => '张三'
]),//模板变量
];
//对参数排序
ksort($param);
//拼接字符串
$signStr = "GETses.tencentcloudapi.com/?";
foreach ( $param as $key => $value ) {
$signStr = $signStr . $key . "=" . $value . "&";
}
$signStr = substr($signStr, 0, -1);
// echo $signStr."</br>";
//生成签名串
$signature = base64_encode(hash_hmac("sha1", $signStr, $secretKey, true));
// echo $signature."</br>";
$param["Signature"] = $signature;
$url = "https://ses.tencentcloudapi.com/?".http_build_query($param);
// echo $url."</br>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$output = curl_exec($ch);
curl_close($ch);
echo json_decode($output);
}
上述代码中需替换你的SecretId和SecretKey,输入发送方邮件、接收方邮件、主题、模板id、模板变量既可正常调用。如需调用其他接口,需要根据接口要求,替换参数即可。
常见问题
1.Destination.N:这样的参数需要把N替换成数字,如:
'Destination.0' => "邮箱1",
'Destination.1' => "邮箱2",
2.Template:这类参数在php中不能写成数组形式,具体写法如下:
'Template.TemplateID' => 85147,
'Template.TemplateData' => json_encode([
'name' => '张三'
]),
3.如果你成功发送请求,却没有任何反应,也不会报错,则有可能是ssl的问题 ,需要在上述代码中的43~45行之间添加如下代码:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
注意:开启curl扩展