thinkphp之集成腾讯云短信
在开发过程中,做个过好多个短信接入的项目,都很简单,最近集成腾讯云短信,竟然弄了好长的时间,腾讯云的接口感觉也是个坑啊!现在我展示一下集成好的短信发送,避免更多的人踩坑。
一.控制器代码如下:
<?php
namespace App\Controller;
use Common\Controller\HomebaseController;
class SendController extends HomebaseController{
function _initialize()
{
parent::_initialize();
}
public function send(){
/*发送短信操作*/
$template=new \Common\Service\SendMessage\SendtencentMessage();
$template->_sendSMS("18233123653","123456");
exit("1111");
}
}
二:业务逻辑层:
<?php
namespace Common\Service\SendMessage;
class SendtencentMessage //extends Model
{
function _sendSMS($phone,$code){
Vendor("tencentcloud/examples/SendSms");
$send=new \SendSms("secretId","secretKey");
$send->sendSms("签名","短信模板","手机号",Array($code,"3"));//最后一个参数为验证码和分钟数,添加模板时动态参数
return true;
}
}
三.腾讯云端SDK
<?php
ini_set("display_errors", "on");
require_once dirname(__DIR__) . '/TCloudAutoLoader.php';
// 导入对应产品模块的client
use TencentCloud\Sms\V20190711\SmsClient;
// 导入要请求接口对应的Request类
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
class SendSms
{
public function __construct($accessKeyId="", $accessKeySecret="",$SmsSdkAppid="")
{
$this->accessKeyId=$accessKeyId;
$this->accessKeySecret=$accessKeySecret;
$this->SmsSdkAppid=$SmsSdkAppid;
}
public function sendSms($signName,$TemplateID,$phone,$templateParam){
try
{
$cred = new Credential($this->accessKeyId, $this->accessKeySecret);
$httpProfile = new HttpProfile();
$httpProfile->setReqMethod("GET"); // post请求(默认为post请求)
$httpProfile->setReqTimeout(30); // 请求超时时间,单位为秒(默认60秒)
$httpProfile->setEndpoint("sms.tencentcloudapi.com"); // 指定接入地域域名(默认就近接入)
$clientProfile = new ClientProfile();
$clientProfile->setSignMethod("TC3-HMAC-SHA256"); // 指定签名算法(默认为HmacSHA256)
$clientProfile->setHttpProfile($httpProfile);
$client = new SmsClient($cred, "ap-shanghai", $clientProfile);
$req = new SendSmsRequest();
$req->SmsSdkAppid = $this->SmsSdkAppid;
$req->Sign = $signName;
$req->ExtendCode = "0";
$req->PhoneNumberSet = array("+86".$phone);
$req->SenderId = "";
$req->SessionContext = "";
$req->TemplateID = $TemplateID;
$req->TemplateParamSet = $templateParam;
$resp = $client->SendSms($req);
print_r($resp->toJsonString());
print_r($resp->TotalCount);
}
catch
(TencentCloudSDKException $e) {
echo $e;
}
}
}
四.值得一提的时腾讯云短信需要GuzzleHttp支持,官方提供的SDK里面已经没有这些文件了,所以需要自己自行下载并集成到自己的目录里面,位置如下图所示:
网友评论