kaffe-software/laravel-otp

一个用于生成和验证OTP(一次性密码)的简单包

v1.4.1 2021-05-13 09:01 UTC

This package is not auto-updated.

Last update: 2024-09-22 14:01:19 UTC


README

简介 🖖

这是一个用于生成和验证OTP(一次性密码)的简单包。这主要可以用于身份验证实现。

安装 💽

通过composer安装

composer require ichtrojan/laravel-otp

将服务提供者添加到config/app.php文件

<?php
   /*
    |--------------------------------------------------------------------------
    | Autoloaded Service Providers
    |--------------------------------------------------------------------------
    |
    | The service providers listed here will be automatically loaded on the
    | request to your application. Feel free to add your own services to
    | this array to grant expanded functionality to your applications.
    |
    */

    'providers' => [
        ...
        Ichtrojan\Otp\OtpServiceProvider::class,
    ];
...

将别名添加到config/app.php文件

<?php

   /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

    'aliases' => [
        ...
        'Otp' => Ichtrojan\Otp\Otp::class,
    ];
...

运行迁移

php artisan migrate

用法 🧨

注意
返回的数据作为对象。您可以使用箭头操作符(->)访问其属性。

生成OTP

<?php

Otp::generate(string $identifier, int $digits = 4, int $validity = 10)
  • $identifier:将绑定到OTP的标识。
  • $digit(可选,默认=4):要生成的数字数量,可以是4、5或6。
  • $validity(可选,默认=10):OTP的有效期(分钟)。

示例

<?php

$otp = Otp::generate('michael@okoh.co.uk', 6, 15);

这将生成一个六位数的OTP,有效期为15分钟,成功的响应将是

{
  "status": true,
  "token": "282581",
  "message": "OTP generated"
}

验证OTP

<?php

Otp::validate(string $identifier, string $token)
  • $identifier:与OTP绑定的标识。
  • $token:与身份绑定的令牌。

示例

<?php

$otp = Otp::validate('michael@okoh.co.uk', '282581');

响应

成功时

{
  "status": true,
  "message": "OTP is valid"
}

不存在

{
  "status": false,
  "message": "OTP does not exist"
}

无效*

{
  "status": false,
  "message": "OTP is not valid"
}

过期

{
  "status": false,
  "message": "OTP Expired"
}

删除过期的令牌

您可以通过运行以下Artisan命令来删除过期的令牌

php artisan otp:clean

您还可以将此Artisan命令添加到app/Console/Kernel.php以自动定期清理

<?php

protected function schedule(Schedule $schedule)
{
    $schedule->command('otp:clean')->daily();
}

贡献

如果您发现此包有任何问题或建议,请提供帮助。我并不完美。