优化空间很大,先用着,能用
<?php
namespace app\common\lib\sms\tencent;
//缓存
use think\facade\Cache;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Sms\V20210111\SmsClient;
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
class Sms{
public $SecretID = "......................";
public $SecretKey = ".......................";
public $SmsSdkAppId = "...........";
public $TemplateId = ".........";
public $SignName = "............";
public $code;
public $phone;
public function __construct($phone = '', $code = '', $tempID = '')
{
$this->phone = $phone;
$this->code = $code;
if(!empty($tempID)){
$this->TemplateId = $tempID;
}
}
public function send(){
try {
//控制台 >API密钥管理页面获取 SecretID 和 SecretKey
$cred = new Credential($this->SecretID, $this->SecretKey);
//实例化一个http选项 [可选]
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("sms.tencentcloudapi.com");
//实例化一个client选项 [可选]
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
/**
* 实例化以sms为例的client对象, [第三个参数 可选]
*
* 第二个参数是地域信息,可以直接填 ap-guangzhou
*/
$client = new SmsClient($cred, "ap-beijing", $clientProfile);
// 实例化一个sms发送短信请求对象,每个接口都会对应一个request对象。
$req = new SendSmsRequest();
//生成随机验证码
// $code = rand(11111, 99999);
// $params = array(
// //接收方手机号,带上+86 示例:+8613711112222
// "PhoneNumberSet" => array((string)$this->phone),
// //短信应用ID:在 [短信控制台] 添加应用后生成的实际SdkAppId
// "SmsSdkAppId" => (string)$this->SmsSdkAppId,
// //短信签名内容:[不理解可以看文章里的截图]
// "SignName" => (string)$this->SignName,
// //模板ID:必须填写已审核通过的模板
// "TemplateId" => (string)$this->TemplateId,
// //我的模板中有两个参数 第一个是验证码参数 第二个是有效时间 若无模板参数,则设置为空
// "TemplateParamSet" => array((string)$this->code, '10'),
// //SecretID
// // "SenderId" => (string)$this->SecretID
// );
$params = array(
"PhoneNumberSet" => array( (string)$this->phone ),
"SmsSdkAppId" => (string)$this->SmsSdkAppId,
"SignName" => (string)$this->SignName,
"TemplateId" => (string)$this->TemplateId,
"TemplateParamSet" => array( (string)$this->code),
// "SenderId" => (string)$this->SecretID
);
$req->fromJsonString(json_encode($params));
//发出请求,返回一个实例
$resp = $client->SendSms($req);
// print_r($resp);die;
//如果成功,把验证码存入缓存
//成功实例中的Code值为 Ok
if ($resp->SendStatusSet[0]->Code === "Ok") {
return true;
// Cache::set('name', $code, 600);
// return json(['msg' => "发送成功", 'code' => 200]);
}
} catch (TencentCloudSDKException $e) {
echo $e;
}
}
}
评论