Using factory mode to implement Thinkphp6.0 access to Alibaba Cloud SMS
如今,短信验证码已成为网站、APP的基础必备应用,应用场景十分丰富,随着移动互联网的发展会越来越多。作为一名码农,对第三方短信接口也是必须掌握的。本文php中文网将介绍使用工厂模式怎么实现ThinkPHP6.0
接入阿里云短信。
一、环境要求
PHP版本 >= 7.1.0
开发环境必须安装有Composer
已开通阿里云短信服务,并且已获取AccessKey,创建模板和签名
最重要的,阿里云账户余额一定要有钱。
这里我就不演示开通短信服务和创建签名模板了,小伙伴们可以查看官方文档:https://help.aliyun.com/document_detail/108072.html?spm=a2c4g.11186623.6.565.1b4825903BoqGV
二、使用Composer
安装Thinkphp6.0
如果您是第一次安装,请在命令行中切换到您的web目录执行下面的命令
composer create-project topthink/think sms
本教程将安装在C盘www目录下 三、使用
Composer
安装 Alibaba Cloud SDK for PHP
进到刚刚创建的sms项目下执行下面的命令
composer require alibabacloud/sdk
四、使用编辑器打开项目 ,并在
config文件夹
下创建sms.php
配置文件来管理阿里短信配置信息
<?php return [ //阿里云短信API接口地址 'host' => 'dysmsapi.aliyuncs.com', //AccessKey ID 'access_key_id' => '您的AccessKey ID', //Access Key Secret 'access_key_secret' => '您的Access Key Secret', //地区ID 'region_id' => 'cn-hangzhou', //模板CODE 'template_code' => '您的模板CODE', //签名名称 'sign_name' => '您的短信签名名称', ];
五、顺便在config文件夹
下打开cache.php
添加Redis
缓存配置,后面发送短信验证码会用到
<?php // +---------------------------------------------------------------------- // | 缓存设置 // +---------------------------------------------------------------------- return [ // 默认缓存驱动 'default' => env('cache.driver', 'redis'), // 缓存连接方式配置 'stores' => [ 'file' => [ // 驱动方式 'type' => 'File', // 缓存保存目录 'path' => '', // 缓存前缀 'prefix' => '', // 缓存有效期 0表示永久缓存 'expire' => 0, // 缓存标签前缀 'tag_prefix' => 'tag:', // 序列化机制 例如 ['serialize', 'unserialize'] 'serialize' => [], ], // Redis缓存 'redis' => [ //服务器地址 'host' => '127.0.0.1', //redis端口 'port' => 6379, //驱动方式 'type' => 'redis', //缓存前缀 'prefix' => 'sms_code_', ] ], ];
六、在app
目录下创建common/lib/sms/Sms.php
接口类,用来约束发送短信验证码的方法
<?php namespace app\common\lib\sms; //定义实现发送短信验证码的接口类,用来约束发送验证码的方法 interface Sms { /** * @desc 发送短信验证码的方法 * @param string $phone 手机号 * @param int $code 验证码 * @return mixed */ public static function sendCode(string $phone, int $code); }
七、在common/lib/sms
目录下创建AliSms类来实现Sms接口的smsSend()
<?php namespace app\common\lib\sms; use AlibabaCloud\Client\AlibabaCloud; use AlibabaCloud\Client\Exception\ClientException; use AlibabaCloud\Client\Exception\ServerException; class AliSms implements Sms { /** * @desc 阿里云发送短信验证码 * @param string $phone 手机号 * @param int $code 验证码 * @return mixed|void * @throws ClientException */ public static function sendCode(string $phone, int $code) { //判断手机号和验证码是否为空 if (empty($phone) || empty($code)){ return false; } AlibabaCloud::accessKeyClient(config('sms.access_key_id'), config('sms.access_key_secret'))->regionId(config('sms.region_id'))->asDefaultClient(); try { $result = AlibabaCloud::rpc() ->product('Dysmsapi') // ->scheme('https') // https | http ->version('2017-05-25') ->action('SendSms') ->method('POST') ->host(config('sms.host')) ->options([ 'query' => [ 'RegionId' =>config('sms.region_id'), 'SignName' => config('sms.sign_name'), 'PhoneNumbers' => $phone, 'TemplateCode' => config('sms.template_code'), 'TemplateParam' => json_encode(['code' => $code]), ], ])->request(); } catch (ClientException $e) { return false; } catch (ServerException $e) { return false; } return true; } }
八、在common\lib
目录下创建生成短信验证码的类 Code.php
<?php namespace app\common\lib; class Code { /** * @desc 生成4位或6位短信验证码,默认为4位 * @param int $length 验证码长度 * @return int */ public static function getCode(int $length = 4) { $code = rand(1000,9999); if ($length == 6){ $code = rand(100000,999999); } return $code; } }
九、在common目录下创建service/Sms.php
<?php namespace app\common\Service; use app\common\lib\Code; class Sms { /** * @param string $phone 手机号 * @param int $lengthCode 验证码长度 * @param string $type 短信厂家,默认选用AliSms * @return mixed */ public static function sendCode(string $phone,int $lengthCode,string $type='AliSms') { //生成短信验证码 $code = Code::getCode(4); //使用工厂模式 调用Lib层发送短信 $class = "app\common\lib\sms\\".$type; $sms = $class::sendCode($phone,$code); if ($sms){ //发送成功,把短信验证码存储Redis缓存中,并给失效时间 cache($phone,$code,300); } return $sms; } }
十、在common目录下创建validate/SmsValidate
验证器
<?php namespace app\common\validate; use think\Validate; class SmsValidate extends Validate { //验证规则 protected $rule = [ 'phone' => 'require|mobile', 'code' => 'require|number' ]; //错误信息 protected $message = [ 'phone.require' => '请输入手机号', 'phone.mobile' => '手机号格式错误', 'code.require' => '短信验证码不能为空', 'code.number' => '短信验证码必须为纯数字' ]; //验证场景 protected $scene = [ 'sendCode' => ['phone'] ]; }
十一、在controller目录下创建Sms.php
<?php namespace app\controller; use app\common\validate\SmsValidate; class Sms { /** * @desc 发送短信验证码 * @return \think\response\Json */ public function code() { if (request()->isPost()){ //获取手机号 $data = [ 'phone' => request()->param('phone','','trim'), ]; //参数校验 $validate = new SmsValidate(); if (!$validate->scene('sendCode')->check($data)){ return json(['code'=>0,'msg'=>$validate->getError()]); } //发送短信验证码 if (\app\common\Service\Sms::sendCode($data['phone'],6,'AliSms')){ return json(['code'=>1,'msg'=>'发送成功,请注意查收。']); }else{ return json(['code'=>0,'msg'=>'发送失败,请稍后重试!']); } } } }
十二、使用PostMan
测试发送短信验证码
不输入手机号或输入错误手机号会给相应的提示。
输入正确的手机号,提示发送短信验证成功这时我们来看看收到的验证码和缓存中的验证码是否一致
到这里我们的发送验证码已经完成
十三、这时我们需要校验验证码是否正确,在app\controller
目录下创建Login.php
<?php namespace app\controller; use app\common\validate\SmsValidate; class Login { public function index() { //接收参数 $data = [ 'phone' => request()->param('phone','','trim'), 'code' => request()->param('code','','trim'), ]; //参数校验 $validate = new SmsValidate(); if (!$validate->check($data)){ return json(['code'=>0,'msg'=>$validate->getError()]); } //从Redis中获取验证码 $redisCode = cache($data['phone']); //判断验证码是否正确 if (empty($redisCode)){ return json(['code'=>0,'msg'=>'验证码已过期,请重新发送!']); } if ($redisCode != $data['code']){ return json(['code'=>0,'msg'=>'验证码输入错误,请重新输入!']); } return '验证成功'; } }
十四、使用PostMan
校验验证码是否正确
输入错误的验证码,会给出响应的提示
输入正确的验证码,提示验证成功
看到这里我相信很多小伙伴的验证码都已发送成功了。
不知道小伙伴们有没有发现文中有两处参数校验的代码相识度很高,在后续的thinkphp技术文章中我会对这个问题进行优化,感兴趣的小伙伴请关注。
The above is the detailed content of Using factory mode to implement Thinkphp6.0 access to Alibaba Cloud SMS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



With the popularity of smart phones, we receive a large number of text messages every day, some of which are advertising and promotional messages, and some of which are spam text messages. These text messages not only waste our time, but also occupy the space of our mobile phones. Fortunately, however, iPhones offer some features to block these annoying text messages. This article will introduce how to block text messages using iPhone. To block text messages, first open the Settings app, then scroll and tap Messages. In the information settings interface, you can see some options, including "Blocked

How to adjust the font size in text messages: 1. On the iOS device, open the "Settings" application, then select the "Display & Brightness" option, find the "Text Size" slider, and slide the slider to adjust the size of the text on the entire device. The text size, including the text in the text message; 2. On the Android device, open the "Settings" application and select the "Display" option, find the "Font Size" option, and select different font sizes to preview and adjust the text in the text message. font size.

How to block text messages from someone on iPhone? If you receive a text message from someone you want to block, you need to open the message on your iPhone. Once you've opened the message, click on the icon at the top with the mobile number or sender's name below it. Now click on Messages on the right side of the screen; now you will see another screen with the option to block this caller. Click this button and select Block Contact. The phone number will no longer be able to send you text messages; it will also be blocked from calling your iPhone. How to unblock blocked contacts on iPhone? If you decide to allow a blocked person to send you messages, you can unblock them on your iPhone at any time. To unblock contacts on iPhone, you need to

Some important text messages have been deleted from Apple mobile phone text messages, and many users don’t know how to recover them. In fact, the recovery method is also very simple. Today I will share with you the detailed recovery method. How to recover deleted text messages on Apple mobile phone? Answer: There are four methods, namely iCloud recovery, iTunes recovery, third-party software recovery and operator recovery 1. If the user uses icloud to back up the text message data of his mobile phone, he can directly use icloud Data recovery. 2. Just go to [Settings]>[General]>[Restore], then restore from iCloud backup, and select the most recent text message backup. 3. If the user uses iTunes to back up his mobile phone, then the player only needs to

PHP implements the automatic anti-swiping function of SMS verification code, which requires specific code examples. In modern Internet applications, SMS verification code is one of the common identity verification methods. However, due to the existence of malicious users, SMS verification codes are often vulnerable to automated attacks, which is the so-called SMS verification code anti-swiping problem. In order to protect the user's account security and system stability, we need to implement the automatic anti-swipe function of SMS verification codes in PHP. This article will introduce a simple method based on IP address and time interval, and provide specific PHP code examples. one

Many friends accidentally delete some important text messages when using their mobile phones. They want to restore them but don't know how to do it. This article uses "Cloud Space" as an example to teach you how to reply to deleted text messages. First, open your phone and find the “cloud space” that comes with your phone. As shown below: Most branded mobile phones now have a "cloud service" function. This function is usually turned on by default. Once it is turned on, it will regularly back up some important data in the phone, including text messages. After turning on the cloud service, pull down the menu and check the SMS backup time. As shown below: If the backup time is earlier than the time you deleted the text messages, it means that the deleted text messages have been uploaded to the cloud space and saved. At this time, click the "Backup and Restore" option

According to news on July 16, according to the official public account of the China Meteorological Administration, entering the main flood season, many places in my country have encountered continuous heavy precipitation and strong convective weather, making the flood prevention and relief situation complex and severe. Since the beginning of this year, the China Meteorological Administration has held multiple meetings to deploy disaster prevention and reduction work, calling for strengthening the linkage between early warning and emergency response, vigorously promoting the application of new information mandatory reminders such as "flash messages", and continuously improving the public coverage and reception rate of early warning information, so that The prevention reminders are more targeted, forming a closed loop of early warning, response, and feedback to gain opportunities for flood prevention and disaster relief. 1. The China Meteorological Administration Public Meteorological Service Center (National Early Warning Information Release Center) strengthens the directionality of early warnings and establishes high-level early warning release technology based on "flash message" mandatory reminders.

1. It may be that SMS filtering contacts is turned on, or iMessages on the phone is not turned on. 2. It may be that airplane mode and do not disturb mode are turned on. 3. The operator in your area may have service interruption or mobile phone payment arrears. It is recommended to contact the operator to solve the problem. 4. The mobile phone system may be faulty. It is recommended to update the operator settings and mobile phone system and restart the mobile phone. 5. It may be a hardware failure. It is recommended to go to the Apple service center for testing.
