composer require tencentcloud/tencentcloud-sdk-php安装composer包
public function tencent_send(){$mobile = $this->request->post("mobile");
// if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
// $this->error(__('手机号不正确'));
// }$sms = new SmsTencent();$auth_code = rand(1000,9999);$result = $sms->send(Config::get('site.tencent_template_id'), '', $mobile, $auth_code);if ($result['code'] == 0) {Cache::set($mobile,$auth_code,300);$this->success(__('发送成功'));} else {$this->error('发送失败:'.$result['msg']);}}<?phpnamespace app\api\controller;use app\common\controller\Api;
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;
use think\Config;class SmsTencent extends Api
{protected $noNeedLogin = ['*'];protected $noNeedRight = ['*'];public function _initialize(){parent::_initialize();// 这里的配置信息可以写入基本配置里面,这里只是为了练手$this->config = ['appid' => Config::get('site.tencent_appid'),'secret_id' => Config::get('site.tencent_secret_id'),'secret_key' => Config::get('site.tencent_secret_key')];}public function send($template_id, $sign, $phone, $auth_code){$return = ['code' => 0,'msg' => 'success','data' => []];try {$cred = new Credential($this->config['secret_id'], $this->config['secret_key']);$httpProfile = new HttpProfile();$httpProfile->setEndpoint("sms.tencentcloudapi.com");$clientProfile = new ClientProfile();$clientProfile->setHttpProfile($httpProfile);$client = new SmsClient($cred, "ap-guangzhou", $clientProfile);$req = new SendSmsRequest();/* 是否国际/港澳台短信:0表示国内短信1表示国际/港澳台短信 */$req->International = 1;$params = array("PhoneNumberSet" => array($phone),"TemplateID" => $template_id,"Sign" => $sign,"TemplateParamSet" => array((string)$auth_code),"SmsSdkAppid" => $this->config['appid']);$req->fromJsonString(json_encode($params));$resp = $client->SendSms($req);$result = $resp->toJsonString();$result = json_decode($result, true);} catch (TencentCloudSDKException $e) {$return['code'] = 500;$return['msg'] = $e->getMessage();return $return;}if (isset($result['SendStatusSet'][0]['Code'])&&$result['SendStatusSet'][0]['Code']=='Ok') {$return['code'] = 0;$return['msg'] = 'success';} else {$return['code'] = 500;$return['msg'] = $result['SendStatusSet'][0]['Message'] ?? '发送失败';}return $return;}
}