Alibaba Cloud SMS redis
1. Install Alibaba Cloud SMS SDK
Alibaba Cloud SMS debugging
Alibaba Cloud SMS SDK PHP document
Refer to the official Alibaba Cloud documentation to install Alibaba Cloud SMS SDK:
composer require alibabacloud/sdk
After the installation is complete, Alibaba Cloud's common functions will be generated in the vendor folder, not just the SMS module.
Two, package into the project lib
Because the SMS module may also be used in other applications, encapsulate it in the lib
middle, common\lib
create a folder under the sms\AliSms
folder, and encapsulate the functions of Alibaba Cloud SMS in AliSms
it:
first test whether the SMS can be sent in the visual debugging page, and fill in PhoneNumbers to receive the SMS Mobile phone number, SignName is the name of the signature (SMS service-domestic message-signature management), TemplateCode fills in the name of the short message template (SMS service-domestic message-template management):
Click 发起调用
to check if you have received a short message:
after successful sending, it will be on the right The code is pasted into the lib
library, AliSms.php
and some of the parameters inside are written in the configuration file:
<?php
declare(strict_types=1);
namespace app\common\lib\sms\AliSms;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class AliSms
{
/**
* 阿里云发送短信
* @param string $phone
* @param int $code
* @return bool
* @throws ClientException
*/
public static function sendCode(string $phone, int $code) : bool {
if(empty($phone) || empty($code)){
return false;
}
AlibabaCloud::accessKeyClient(config("aliyun.access_key_id"), config("aliyun.access_secret"))
->regionId(config("aliyun.region_id"))
->asDefaultClient();
$templateParam = [
"code" => $code
];
try {
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
// ->scheme('https') // https | http
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host(config("aliyun.host"))
->options([
'query' => [
'RegionId' => config("aliyun.region_id"),
'PhoneNumbers' => $phone,
'SignName' => config("aliyun.sign_name"),
'TemplateCode' => config("aliyun.template_code"),
'TemplateParam' => json_encode($templateParam),
],
])
->request();
print_r($result->toArray());
} catch (ClientException $e) {
return false;
// echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
return false;
// echo $e->getErrorMessage() . PHP_EOL;
}
return true;
}
}
Business
Floor:
<?php
declare(strict_types=1);
namespace app\common\business;
use app\common\lib\sms\AliSms\AliSms;
class Sms
{
public static function sendCode(string $phoneNumber) : bool {
$code = rand(100000, 999999);
$sms = AliSms::sendCode($phoneNumber, $code);
if($sms){
// 需要记录redis及失效时间1分钟
}
return true;
}
}
Controller
Floor:
<?php
namespace app\api\controller;
use app\api\validate\User;
use app\BaseController;
use think\exception\ValidateException;
use app\common\business\Sms as SmsBus;
class Sms extends BaseController
{
public function code(){
$phoneNumber = input("param.phone_number","","trim");
$data = [
'phone_number' => $phoneNumber
];
// 已采用自定义异常方法拦截,如果没有采用自定义拦截,需要try...catch
validate(User::class)->scene("send_code")->check($data);
/*try {
validate(User::class)->scene("send_code")->check($data);
}catch (ValidateException $e){
return show(config("status.error"), $e->getError());
}*/
if(SmsBus::sendCode($phoneNumber)){
return show(config("status.success"),"发送验证码成功");
}
return show(config("status.error"),"发送验证码失败");
}
}
Define the routing file:
api.php
<?php
use think\facade\Route;
Route::rule('smscode', 'sms/code','POST');
Define exception method interception reference: ThinkPHP6 project basic operation (13. Custom exception handling summary in actual combat projects, error page & API error)
Three, radis record verification code
1. Install redis service
Download from the official website: https://redis.io/download
Install the redis
service according to your own system , and then turn on the service.
Double-click on the windows and the redis-server.exe
following interface appears to start the service:
Tips: 这个窗口不要关闭哦,否则服务就关掉了!
2. Visual redis management software
Beginners can view the data managed by redis through visualization tools, just like navcat
viewing the database.
RDM official website: https://rdm.dev/
(The official website is chargeable, but we Chinese students should know what to do, so I won’t say more...)
3. PHP install redis extension
Enter in the console to php -m
view the php
installed extensions. If you find the redis extension, you don't need to install it.
Enter the php -i
view PHP Extension Build
information in the console , and then download the corresponding redis
extended version.
redis download official website
Zend Extension Build => API320190902,NTS,VC15
PHP Extension Build => API20190902,NTS,VC15
Then put it in the php extension directory: the D:\phpstudy_pro\Extensions\php\php7.4.3nts\ext
general integrated environment will have this file, and then check the php.ini
configuration in the file redis
:
extension=php_redis.dll
Open the php extension redis
:
4. Configure cache redis
ThinkPHP
The default is to use the file cache. The interface for sending the verification code is written in the api
application, so I copied a cache
configuration file to the api
application config
directory and modified the configuration:
<?php
// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------
return [
// 默认缓存驱动
'default' => env('cache.driver', 'redis'),
// 缓存连接方式配置
'stores' => [
'file' => [
// 驱动方式
'type' => 'File',
// 缓存保存目录
'path' => '',
// 缓存前缀
'prefix' => '',
// 缓存有效期 0表示永久缓存
'expire' => 0,
// 缓存标签前缀
'tag_prefix' => 'tag:',
// 序列化机制 例如 ['serialize', 'unserialize']
'serialize' => [],
],
// 更多的缓存连接
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
'type' => 'redis',
]
],
];
5. Redis saves the SMS verification code and sets the expiration time
- Configure redis prefix and expiration time
<?php return [ "code_pre" => "sms_code_pre_", // key 前缀 "code_expire" => 60, // 失效时间 60 秒 ];
- Modify
Business
layer codepublic static function sendCode(string $phoneNumber) : bool { $code = rand(100000, 999999); $sms = AliSms::sendCode($phoneNumber, $code); if($sms){ // 需要记录redis及失效时间1分钟 cache(config("redis.code_pre").$phoneNumber, $code, config("redis.code_expire")); } return $sms; }
- Re-test the SMS sending interface to see
redis
if the record is successful.
Send a POST request with Postmanhttp://tp6.com/api/smscode
, and it shows that the sending is successful: the
mobile phone receives the SMS verification code403777
, refresh the RDM, there is already a record, and the verification code and expiration time are displayed, the time60
decreases from the beginning If it is reduced,0
it will no longer be accessible. Refresh this key and it will disappear.
6. Verify SMS verification code
Here you only need to use cache("key")
it to get radis
the value of the record. If it is not found, it is expired. If it is not expired, then judge whether it is equal.