turahe/otp

向任何地方发送OTP

dev-master 2023-10-08 00:17 UTC

This package is auto-updated.

Last update: 2024-09-08 02:06:05 UTC


README

简介 🖖

这是一个用于生成和验证OTP(一次性密码)的简单包。这通常用于身份验证。

安装 💽

通过composer安装

composer require turahe/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' => [
        ...
        Turahe\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' => [
        ...
        'Token' => Turahe\Otp\Otp::class,
    ];
...

运行迁移

php artisan migrate

用法 🧨

注意
响应以对象的形式返回。您可以使用箭头运算符(->)访问其属性

生成OTP

<?php

Otp::generate(string $identifier int $validity = 10)
  • $identifier: 将与OTP关联的身份。
  • $validity (可选 | 默认 = 10): OTP的有效期(分钟)。

示例

<?php
use Turahe\otp\Facades\Otp;
$otp = Otp::generate('nur@wach.id', 15);

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

{
  "id": 1,
  "identity": "nur@wach.id",
  "token": "282581",
  "created_at": "2020-01-01 00:00:00",
  "updated_at": "2020-01-01 00:00:00"
}

验证OTP

<?php

Otp::validate(string $identifier, string $token)
  • $identifier: 与OTP关联的身份。
  • $token: 与身份关联的令牌。

示例

<?php

$otp = Otp::validate('nur@wach.id', '282581');

删除过期的令牌

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

php artisan otp:clean

您还可以将此 artisan 命令添加到 app/Console/Kernel.php 中,以自动按计划清理

<?php

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

贡献

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