hyperf-chat/app/Support/SendEmailCode.php

104 lines
2.4 KiB
PHP
Raw Normal View History

2020-11-09 17:41:22 +08:00
<?php
namespace App\Support;
class SendEmailCode
{
const FORGET_PASSWORD = 'forget_password';
2021-04-20 16:30:57 +08:00
const CHANGE_MOBILE = 'change_mobile';
2020-11-09 17:41:22 +08:00
const CHANGE_REGISTER = 'user_register';
2021-04-20 16:30:57 +08:00
const CHANGE_EMAIL = 'change_email';
2020-11-09 17:41:22 +08:00
/**
* 获取缓存key
*
* @param string $type
* @param string $mobile
* @return string
*/
private function getKey(string $type, string $mobile)
{
return "email_code:{$type}:{$mobile}";
}
/**
* 检测验证码是否正确
*
2021-04-20 16:30:57 +08:00
* @param string $type 发送类型
2020-11-09 17:41:22 +08:00
* @param string $email 手机号
2021-04-20 16:30:57 +08:00
* @param string $code 验证码
2020-11-09 17:41:22 +08:00
* @return bool
*/
public function check(string $type, string $email, string $code)
{
$sms_code = redis()->get($this->getKey($type, $email));
if (!$sms_code) {
return false;
}
return $sms_code == $code;
}
/**
* 发送邮件验证码
*
2021-04-20 16:30:57 +08:00
* @param string $type 类型
2020-11-09 17:41:22 +08:00
* @param string $title 邮件标题
* @param string $email 邮箱地址
2021-04-22 16:14:34 +08:00
* @return bool
2020-11-09 17:41:22 +08:00
*/
public function send(string $type, string $title, string $email)
{
$key = $this->getKey($type, $email);
if (!$sms_code = $this->getCode($key)) {
$sms_code = mt_rand(100000, 999999);
}
2020-12-26 21:33:40 +08:00
$this->setCode($key, $sms_code);;
2020-11-09 17:41:22 +08:00
2020-12-26 21:33:40 +08:00
// ...执行发送(后期使用队列)
2021-05-24 11:31:36 +08:00
email()->send(
$email, 'Lumen IM(绑定邮箱验证码)',
container()->get(MailerTemplate::class)->emailCode($sms_code)
);
2020-11-09 17:41:22 +08:00
return true;
}
/**
* 获取缓存的验证码
*
* @param string $key
* @return mixed
*/
public function getCode(string $key)
{
return redis()->get($key);
}
/**
* 设置验证码缓存
*
2021-04-20 16:30:57 +08:00
* @param string $key 缓存key
* @param string $sms_code 验证码
* @param float|int $exp 过期时间
2021-04-22 16:14:34 +08:00
* @return bool
2020-11-09 17:41:22 +08:00
*/
public function setCode(string $key, string $sms_code, $exp = 60 * 15)
{
return redis()->setex($key, $exp, $sms_code);
}
/**
* 删除验证码缓存
*
2021-04-20 16:30:57 +08:00
* @param string $type 类型
2020-11-09 17:41:22 +08:00
* @param string $email 邮箱地址
2021-04-22 16:14:34 +08:00
* @return int
2020-11-09 17:41:22 +08:00
*/
public function delCode(string $type, string $email)
{
return redis()->del($this->getKey($type, $email));
}
}