ThinkPHP6项目基操(15.实战部分 阿里云短信redis)
日期: 2020-12-12 分类: 跨站数据测试 586次阅读
阿里云短信redis
一、安装阿里云短信SDK
阿里云短信调试
阿里云短信SDK PHP文档
参考阿里云官方文档安装阿里云短信SDK:
composer require alibabacloud/sdk
安装完成后会在vendor文件夹生成阿里云的常用功能,不仅仅是短信模块。
二、封装到项目lib中
因为短信模块可能在其他应用中也有使用,所以封装在lib
中,在common\lib
文件夹下创建sms\AliSms
文件夹,将阿里云短信的功能封装在AliSms
中:
先在可视化调试中页面测试是否可以发送短信,PhoneNumbers填写接收短信的手机号码,SignName是签名名称(短信服务–国内消息–签名管理),TemplateCode填写短信模板名称(短信服务–国内消息–模板管理):
点击发起调用
,查看是否有收到短信:
发送成功后将右侧代码粘贴到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;
}
}
Business
层:
<?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
层:
<?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"),"发送验证码失败");
}
}
定义路由文件:
api.php
<?php
use think\facade\Route;
Route::rule('smscode', 'sms/code','POST');
定义异常方法拦截参考: 除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
精华推荐