Laravel结合Redis发送邮箱验证码
每天进步一点点...
我们在某些业务上,需要注册邮箱,为避免邮箱注册混乱、乱用他人邮箱,这就需要对邮箱进行验证。
一、设计思路
1、用户输入邮箱,点击验证
2、后端接收到邮箱后,随机生成一个code,用邮箱作为key,code为值保存到redis中,并使用laravel封闭的Mail类发送给用户
3、用户收到邮件后,获取验证码并输入,后端把email、code和redis保存的值做一个匹对
二、前期准备
1、修改.env配置文件里面email部分的内容
MAIL_MAILER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=465
MAIL_USERNAME=xxxx@qq.com
MAIL_PASSWORD=xxxxxxxxxxxxxxxxx
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=xxxx@qq.com
MAIL_FROM_NAME=糊涂
2、使用命令创建EmailVerifyController.php
控制器
php artisan make:controller Index/EmailVerifyController
3、在routes/web.php中注册相关路由
<?php
use Illuminate\Support\Facades\Route;
Route::get("sendEmailCode", "Index\EmailVerifyController@sendEmailCode");
Route::get("verify", "Index\EmailVerifyController@verify");
4、在resoures/views/mail创建SendEmailCode.blade.php
模块文件
三、实现代码
1、EmailVerifyController.php控制器
<?php
namespace App\Http\Controllers\Index;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
class EmailVerifyController extends Controller
{
/**
* 发送邮箱验证码
* @param Request $request
* @return array
*/
public function sendEmailCode(Request $request)
{
$email = $request->input("email");
$code = rand(100000, 999999);//验证码
$expireTime = 60 * 3;//过期时间
$EMAIL_VERIFY_CODE = "email:verify:code:" . $email;//redis key
Redis::setex($EMAIL_VERIFY_CODE, $expireTime, $code);
Mail::send("mail.SendEmailCode", ["code" => $code, "email" => $email], function (Message $message) use ($email) {
$message->to($email);
$message->subject("糊涂个人博客——邮箱验证");
});
if (Mail::failures()) {
return ["code" => 0, "msg" => "warning"];
}
return ["code" => 1, "msg" => "success"];
}
/**
* 验证
* @param Request $request
* @return array
*/
public function verify(Request $request)
{
$email = $request->input("email");
$code = $request->input("code");
$EMAIL_VERIFY_CODE = "email:verify:code:" . $email;//redis key
$isCode = Redis::get($EMAIL_VERIFY_CODE);
if ($isCode && $isCode === $code) {
return ["code" => 1, "msg" => "success"];
}
return ["code" => 0, "msg" => "warning"];
}
}
2、SendEmailCode.blade.php模块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#app {
line-height: 150%;
}
</style>
</head>
<body>
<div id="app">
<div>亲爱的用户:</div>
<br/>
<div>您好!</div>
<br/>
<div>感谢您使用糊涂个人博客开发平台。您正在进行邮箱验证,请在验证码输入框中输入此次验证码<span style="color: red">{{$code}}</span>(3分钟内有效)以完成验证。</div>
<div>如非本人操作,请忽略此邮件,由此给您带来的不便请谅解!</div>
<br/>
<div>糊涂个人博客开发平台</div>
</div>
</body>
</html>
四、实现效果
自己可以根据相关需要修改样式代码