文章最后更新时间:2021年10月29日已超过201天没有更新。
分享一个在开发过程中用到的腾讯云短信发送功能,用thinkphp框架写的,封装了一个service类,直接看代码吧
需要引入腾讯短信sdk:引入用composer 前提是服务器或本地需要安装composer哦
//在thinkphp框架根目录 composer.json里添加如下代码,找到你文件里的require: { "require": { "tencentcloud/tencentcloud-sdk-php": "^3.0", } } //然后 在项目根目录执行 composer update //加载成功就OK了
<?php namespace app\api\service; use think\Db; use TencentCloud\Cds\V20180420\Models\DbauditTypesInfo; use TencentCloud\Common\Credential; use TencentCloud\Common\Profile\ClientProfile; use TencentCloud\Common\Profile\HttpProfile; use TencentCloud\Common\Exception\TencentCloudSDKException; use TencentCloud\Sms\V20190711\SmsClient; use TencentCloud\Sms\V20190711\Models\SendSmsRequest; class SmsService{ public $phone='';//接收短信的手机号 public $templateParamSet=[];//是模板变量参数的数组 public $return_msg=''; public $secretId='AKDDDwOVP6KhiXAsENE0EosiIEvRhtypK1FE';//腾讯云secretId public $secretKey='A63hAVaV9YinD5gzHI1TebS3RyADEsNf';//腾讯云secretKey public $smsSdkAppid='1400456431';//短信appid public $templateID='552412';//短信模板id public $sign='先生博客';//短信签名 public function __construct() { } /** * 手机号判断 * @access public * @param string $mb 手机号 * @return bool */ public function is_mobile($mb) { return preg_match("/^1[3|4|5|6|7|8|9]{1}[0-9]{9}$/", $mb); } //发送短信 public function sendSms(){ try { if(empty($this->phone)){ $this->return_msg='手机号不能为空'; return false; } if(!$this->is_mobile($this->phone)){ $this->return_msg='手机号格式错误'; return false; } $cred = new Credential($this->secretId,$this->secretKey); $httpProfile = new HttpProfile(); $httpProfile->setEndpoint("sms.tencentcloudapi.com"); $clientProfile = new ClientProfile(); $clientProfile->setHttpProfile($httpProfile); $clientProfile->setSignMethod("TC3-HMAC-SHA256"); // 指定签名算法(默认为HmacSHA256) $client = new SmsClient($cred,"",$clientProfile); //保存验证码逻辑,此处省略1万代码。。 $req = new SendSmsRequest(); $req->SmsSdkAppid =$this->smsSdkAppid; $req->Sign=$this->sign; $req->PhoneNumberSet =['+86'.$this->phone]; $req->TemplateID =$this->templateID; $req->TemplateParamSet = $this->templateParamSet;//是模板变量参数的数组 $resp = $client->SendSms($req); if($resp->SendStatusSet[0]->Code=='Ok'){ $this->return_msg='发送成功'; return true; }else{ $this->return_msg='发送失败'; return false; } } catch(TencentCloudSDKException $e) { $this->return_msg=$e->getMessage(); return false; } } }
<?php namespace app\api\controller; use think\Controller; use app\api\service\SmsService; use think\App; //测试控制器 调取短信服务类进行发送短信 class Test extend Controller{ $this->sms_service->phone=18888888888;//手机号 // 我申请的模板大致内容是 您好,您的验证码是8888,5分钟后会失效。 8888是第一个参数 5是第二个参数 // 注意:数组内的参数必须是字符串性,不能是整型 比如 5 这个参数数字必须是"" 引号包含 //templateParamSet ["验证码","5分钟内有效"]需要和你申请的模板对应,你申请的模板有几个参数,数组就有几个值 $code=rand(1000,9999); $this->sms_service->templateParamSet=["{$code}","5"]; $is_true=$this->sms_service->sendSms(); if(!$is_true){ echo "$this->sms_service->return_msg";exit;//发送失败信息 }else{ echo "$this->sms_service->return_msg";exit;//发送成功信息 } }
文章版权声明:除非注明,否则均为先生博客原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...