107 lines
2.1 KiB
PHP
107 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Notifications\SmsCodeCreated;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Notifications\Notifiable;
|
|
|
|
class SmsCode extends Model
|
|
{
|
|
use HasFactory;
|
|
use Notifiable;
|
|
|
|
public const TYPE_REGISTER = 1;
|
|
public const TYPE_RESET_PASSWORD = 2;
|
|
|
|
/**
|
|
* @var array
|
|
*/
|
|
protected $attributes = [
|
|
'is_use' => false,
|
|
];
|
|
|
|
/**
|
|
* @var array
|
|
*/
|
|
protected $fillable = [
|
|
'user_id',
|
|
'phone',
|
|
'type',
|
|
'code',
|
|
'is_use',
|
|
'expires_at',
|
|
];
|
|
|
|
/**
|
|
* @var array
|
|
*/
|
|
protected $casts = [
|
|
'type' => 'int',
|
|
'is_use' => 'bool',
|
|
'expires_at' => 'datetime',
|
|
];
|
|
|
|
/**
|
|
* 允许发送短信的验证码类型
|
|
*
|
|
* @var array
|
|
*/
|
|
public static $allowedTypes = [
|
|
self::TYPE_REGISTER,
|
|
self::TYPE_RESET_PASSWORD,
|
|
];
|
|
|
|
/**
|
|
* 阿里云短信模板
|
|
*
|
|
* @var array
|
|
*/
|
|
public static $aliyunTemplates = [
|
|
// self::TYPE_REGISTER => 'SMS_231444585',
|
|
// self::TYPE_RESET_PASSWORD => 'SMS_231444585',
|
|
];
|
|
|
|
/**
|
|
* {@inheritdoc}
|
|
*/
|
|
protected static function booted()
|
|
{
|
|
static::created(function ($smsCode) {
|
|
if (app()->isProduction()) {
|
|
$smsCode->notify(new SmsCodeCreated($smsCode));
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 确认此验证码是否无效
|
|
*
|
|
* @return bool
|
|
*/
|
|
public function isInvalid(): bool
|
|
{
|
|
return $this->is_use || ($this->expires_at && $this->expires_at->lte(now()));
|
|
}
|
|
|
|
/**
|
|
* 阿里云短信模板
|
|
*
|
|
* @return string
|
|
*/
|
|
public function getAliyunTemplate()
|
|
{
|
|
return static::$aliyunTemplates[$this->type] ?? 'SMS_228470015';
|
|
}
|
|
|
|
/**
|
|
* @param \Illuminate\Notifications\Notification $notification
|
|
* @return string
|
|
*/
|
|
public function routeNotificationForSms($notification): string
|
|
{
|
|
return $this->phone;
|
|
}
|
|
}
|