> 本文记录在ThinkPHP6.0中使用阿里云短信验证码,该封装类不仅仅局限于TP,拿来即用 **使用该类之前必须引入 `flc/dysms` 扩展,该封装类就是基于这个扩展写的** ``` composer require flc/dysms ``` ```php <?php // 本文件放入TP6.0的extend目录下 extend/Dysms.php use Flc\Dysms\Client; use Flc\Dysms\Request\SendSms; // 获取类的实例 // function dysms() // { // return Dysms::getInstance(); // } // 使用示例 返回一个数组 // $arr['result'] true 发送成功 // $arr['result'] false 发送失败 msg 错误信息 // $arr = dysms()->sendSms(1503xxxxx);//参数是接收验证码的手机号 /** * 阿里大于短信验证码封装 * composer require flc/dysms * * 阿里云短信服务默认流控 * 同一个签名同一个手机号短信验证码 1条/分钟 */ class Dysms { private static $obj; private $config; private $signName; private $templateCode; /** * 私有化构造方法 * 禁止类在外部被实例化 */ private function __construct() { // accessKey、accesssecret $this->config = [ 'accessKeyId' => 'LTAI4GJ6iaE7xxxxxxxxxxxx', 'accessKeySecret' => 'uljdxDoi8ocXNxxxxxxxxxx', ]; //短信签名 $this->signName = 'xxxxxxxx'; //短信模板ID $this->templateCode = 'SMS_179xxxxxx'; } /** * 获取类的实例 */ public static function getInstance() { if (self::$obj instanceof self) { return self::$obj; } else { self::$obj = new self; return self::$obj; } } /** * 传入手机号发送短信 * @param $phoneNumbers 手机号 */ public function sendSms($phoneNumbers) { $client = new Client($this->config); $sendSms = new SendSms; $sendSms->setPhoneNumbers($phoneNumbers); $sendSms->setSignName($this->signName); $sendSms->setTemplateCode($this->templateCode); $sendSms->setTemplateParam(['code' => rand(100000, 999999)]); $sendSms->setOutId('demo'); // 返回标准类对象 发送失败 // object(stdClass)#59 (3) { // ["Message"]=> // string(30) "触发小时级流控Permits:5" // ["RequestId"]=> // string(36) "B76061EE-2D9A-4E46-89B9-2418E8A5555E" // ["Code"]=> // string(26) "isv.BUSINESS_LIMIT_CONTROL" // } $result = $client->execute($sendSms); // 返回结果 // array(2) { // ["result"]=> // bool(true) // ["msg"]=> // string(12) "发送成功" // } // array(3) { // ["result"]=> // bool(false) // ["code"]=> // string(26) "isv.BUSINESS_LIMIT_CONTROL" // ["msg"]=> // string(30) "触发小时级流控Permits:5" // } if ($result->Code === 'OK') { return ['result' => true, 'msg' => '发送成功']; } else { return ['result' => false, 'code' => $result->Code,'msg' => $result->Message]; } } /** * 私有化克隆方法 * 禁止类的实例在外部被克隆 */ private function __clone(){} } ``` #### 在 TP6.0 中的使用 --- **(1)在框架根目录执行以下命令,引入扩展包** ``` composer require flc/dysms ``` **(2)将该类放入TP6.0的`extend`目录下,也就是 `extend/Dysms.php`**  **(3)将以下函数放入TP6.0的全局公共函数文件 `app/common.php`** ```php // 获取类的实例 function dysms() { return Dysms::getInstance(); } ``` **(4)此时在控制器或模型中则可以使用以下方式直接使用** ```php // 使用示例 返回一个数组 // $arr['result'] true 发送成功 // $arr['result'] false 发送失败 msg 错误信息 $arr = dysms()->sendSms(150xxxx);//参数是接收验证码的手机号 ```