PHP code example of fouladgar / laravel-otp

1. Go to this page and download the library: Download fouladgar/laravel-otp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fouladgar / laravel-otp example snippets




/*
|--------------------------------------------------------------------------
| Send OTP via SMS.
|--------------------------------------------------------------------------
*/
OTP()->send('+98900000000'); 
// Or
OTP('+98900000000');

/*
|--------------------------------------------------------------------------
| Send OTP via channels.
|--------------------------------------------------------------------------
*/
OTP()->channel(['otp_sms', 'mail', \App\Channels\CustomSMSChannel::class])
     ->send('+98900000000');
// Or
OTP('+98900000000', ['otp_sms', 'mail', \App\Channels\CustomSMSChannel::class]);

/*
|--------------------------------------------------------------------------
| Send OTP for specific user provider
|--------------------------------------------------------------------------
*/
OTP()->useProvider('admins')
     ->send('+98900000000');
 
/*
|--------------------------------------------------------------------------
|  Validate OTP
|--------------------------------------------------------------------------
*/
OTP()->validate('+98900000000', 'token_123');
// Or
OTP('+98900000000', 'token_123');

/*
|--------------------------------------------------------------------------
| Validate OTP for specific user provider
|--------------------------------------------------------------------------
*/
OTP()->useProvider('users')
     ->validate('+98900000000', 'token_123');
/*
|--------------------------------------------------------------------------
| You may wish to only confirm the token
|--------------------------------------------------------------------------
*/
OTP()->onlyConfirmToken()   
     ->validate('+98900000000', 'token_123');

// config/otp.php



return [
    /**
    |Supported drivers: "cache", "database"
    */
    'token_storage' => 'cache',
];

// config/otp.php



return [

    'mobile_column' => 'mobile',

    'token_table'   => 'otp_token',

    //...
];


// config/otp.php



return [
    //...

    'default_provider' => 'users',

    'user_providers'  => [
        'users' => [
            'table'      => 'users',
            'model'      => \App\Models\User::class,
            'repository' => \Fouladgar\OTP\NotifiableRepository::class,
        ],

       // 'admins' => [
       //   'model'      => \App\Models\Admin::class,
       //   'repository' => \Fouladgar\OTP\NotifiableRepository::class,
       // ],
    ],

    //...
];



namespace App\Models;

use Fouladgar\OTP\Concerns\HasOTPNotify;
use Fouladgar\OTP\Contracts\OTPNotifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements OTPNotifiable
{
    use Notifiable;
    use HasOTPNotify;

    // ...
}



namespace App;

use Fouladgar\OTP\Contracts\SMSClient;
use Fouladgar\OTP\Notifications\Messages\MessagePayload;

class SampleSMSClient implements SMSClient
{
    public function __construct(protected SampleSMSService $SMSService)
    {
    }

    public function sendMessage(MessagePayload $payload): mixed
    {
        return $this->SMSService->send($payload->to(), $payload->content());
    }

    // ...
}

// config/otp.php



return [

  'sms_client' => \App\SampleSMSClient::class,

  //...
];



namespace App\Http\Controllers;

use App\Models\User;
use Fouladgar\OTP\Exceptions\InvalidOTPTokenException;
use Fouladgar\OTP\OTPBroker as OTPService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;

class AuthController
{
    public function __construct(private OTPService $OTPService)
    {
    }

    public function sendOTP(Request $request): JsonResponse
    {
        try {
            /** @var User $user */
            $user = $this->OTPService->send($request->get('mobile'));
        } catch (Throwable $ex) {
          // or prepare and return a view.
           return response()->json(['message'=>'An unexpected error occurred.'], 500);
        }

        return response()->json(['message'=>'A token has been sent to:'. $user->mobile]);
    }

    public function verifyOTPAndLogin(Request $request): JsonResponse
    {
        try {
            /** @var User $user */
            $user = $this->OTPService->validate($request->get('mobile'), $request->get('token'));

            // and do login actions...

        } catch (InvalidOTPTokenException $exception){
             return response()->json(['error'=>$exception->getMessage()],$exception->getCode());
        } catch (Throwable $ex) {
            return response()->json(['message'=>'An unexpected error occurred.'], 500);
        }

         return response()->json(['message'=>'Logged in successfully.']);
    }
}


//config/otp.php

return [
    // ...

    'channel' => \Fouladgar\OTP\Notifications\Channels\OTPSMSChannel::class,
];



use Fouladgar\OTP\Notifications\OTPNotification;
use Fouladgar\OTP\Notifications\Messages\OTPMessage;
use Illuminate\Notifications\Messages\MailMessage;

public function boot()
{
    // ...

    // SMS Customization
    OTPNotification::toSMSUsing(fn($notifiable, $token) =>(new OTPMessage())
                    ->to($notifiable->mobile)
                    ->content('Your OTP Token is: '.$token));

    //Email Customization
    OTPNotification::toMailUsing(fn ($notifiable, $token) =>(new MailMessage)
            ->subject('OTP Request')
            ->line('Your OTP Token is: '.$token));
}

// resources/lang/vendor/OTP/en/otp.php



return [
    'otp_token' => 'Your OTP Token is: :token.',

    'otp_subject' => 'OTP request',
];

php artisan vendor:publish --provider="Fouladgar\OTP\ServiceProvider" --tag="config"

php artisan migrate

php artisan vendor:publish --provider="Fouladgar\OTP\ServiceProvider" --tag="lang"