ibrahem-kamal/laravel-otp

生成和验证发送给用户的 OTP

2.1.2 2024-04-14 15:55 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Laravel Otp 是一个用于生成和验证发送给用户的 OTP 的工具

安装

您可以通过 composer 安装此包

composer require ibrahem-kamal/laravel-otp

您可以使用以下命令发布和运行迁移

php artisan vendor:publish --tag="laravel-otp-migrations"
php artisan migrate

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="laravel-otp-config"

这是已发布配置文件的内容

return [
    'services' => [
        'default' => [
            'expires_in' => 5, // in minutes
            'otp_generator_options' => [
                'length' => 4, // no of digits
                'numbers' => true,
                'letters' => false,
                'symbols' => false,
            ],
            'validate_uniqueness_after_generation' => true,
            'delete_after_verification' => false,
        ],
    ],
    'fallback_options' => [
        'otp_generator_options' => [
            'length' => 4, // no of digits
            'numbers' => true,
            'letters' => false,
            'symbols' => false,
        ],
        'validate_uniqueness_after_generation' => true, // whether to validate the uniqueness of the otp after generation by checking the database
        'delete_after_verification' => false, // whether to delete the otp after verification
    ]

];

您可以添加任意多的服务,并且可以使用回退选项来设置 OTP 生成和验证的默认选项

使用方法

  • 首先,您需要通过实现 HasOtp 接口和使用 InteractsWithOtp 特性来准备您的模型
class User extends Authenticatable implements HasOtp
{
    use InteractsWithOtp;
}

如果您在模型中没有 phone 列,您可以重写 getPhoneNumber 方法来返回用户电话号码,如下所示

    public function getPhoneNumber(): string
    {
        return $this->mobile_number;
    }
  • 然后,您可以使用 Otp 来生成 OTP
$user->otp()->generate() // returns OtpCode Model instance

// you can also pass the service name to generate otp for a specific service or modify the options

$user->otp()
        ->setPhone('11111')
        ->setValidateUniquenessAfterGeneration(false)
        ->setService('other service')
        ->setGeneratorOptions(
            length: 6,
            letters: false,
            numbers: true, 
            symbols: false
        )->generate()  // returns OtpCode Model instance
  • 您可以使用 verify 方法来验证 OTP
$otp = $user->otp()->verifyOtp('1234') // returns ServiceResponse instance
    $otp->isSuccess(); //bool
    $otp->getErrorsString(); // errors as string
    $otp->getErrors(); // errors as array
    $otp->getData(); // OtpCode Model instance when success
    $otp->toArray(); // array of all the above

测试

composer test

变更日志

有关最近更改的详细信息,请参阅 变更日志

贡献

有关详细信息,请参阅 贡献指南

安全漏洞

有关如何报告安全漏洞的信息,请参阅 我们的安全策略

鸣谢

许可证

MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件