ThinkPHP6项目基本操作(阿里云短信SDK+redis)
1.安装阿里云短信SDK
阿里云短信SDK PHP文档(百度就够了)
查看阿里云官方文档安装阿里云短信SDK:
composer require alibabacloud/sdk
安装完成后,会在vendor文件夹中创建阿里云的常用功能,而不仅仅是短信模块。
2。封装到lib项目
因为短信模块也可以在其他应用中使用,所以封装在lib
中,并在common\lib❀❀文件夹sms\AliSms
中创建封装阿里巴巴AliSms
中的云短信功能:
首先在可视化调试页面测试能否发送短信。 PhoneNumbers填写接收短信的手机。号码,SignName 为签名的名称(短信服务-国内消息-签名管理),TemplateCode 填写短信模板的名称(短信服务-国内消息-模板管理):
点击开始签名拨打
,查看是否有回执 短信:
发送成功后,将右侧代码粘贴至库 定义路由文件: 下载官网:https://redis.io/download 温馨提示:请勿关闭此窗口,否则服务将被关闭! 初学者可以通过可视化工具查看redis管理的数据,如 在控制台中输入 然后放到php扩展目录下: 打开php扩展 a.配置redis前缀和过期时间 b.修改 代码 c. 再次测试短信发送接口,查看 手机收到短信验证代码lib
AliSms.php♸。我在配置文件里写了一些参数:
<?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;
}
}
业务
层:<?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;
}
}
控制器
层:<?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"),"发送验证码失败");
}
}
3.radis记下验证码 1、安装redis服务
安装redis
服务,然后启动自己的service服务。
在 Windows 中双击 redis-server.exe
。当出现以下界面时,服务已开启: 2。可视化redis管理软件
navcat
查看数据库。 ? php -m
即可查看php
安装的扩展。如果找到redis扩展,则无需安装。
在控制台输入php -i
即可看到PHP Extension Build
信息,然后下载合适版本的♺”redis redis下载官网Zend Extension Build => API320190902,NTS,VC15
PHP Extension Build => API20190902,NTS,VC15
D:\phpstudy_pro\Extensions\php\php7.4.3nts\ext
一般集成环境都会有这个文件,然后查看文件php.ini
有一个配置redis
:extension=php_redis.dll
redis
:4。 Redis缓存配置
ThinkPHP
默认使用文件缓存,这里贴出验证代码 我在api
应用中编写了接口,所以我将配置文件复制到
api
application config
下一个内容列表,并修改配置:<?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存储短信验证码并设置过期时间
<?php
return [
"code_pre" => "sms_code_pre_", // key 前缀
"code_expire" => 60, // 失效时间 60 秒
];
public 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;
}
redis
是否成功记录
使用Postman发送POST请求http://tp6.com/smscode 如果发送成功:
403777
。 RDM刷新中已有记录,并显示验证码和过期时间。时间开始从60
减少到不再可访问的0
。刷新按钮,它就会消失。 ?只要确保它们在过期之前就可以了。
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。