PHP code example of nealyip / laravel-otp-validation
1. Go to this page and download the library: Download nealyip/laravel-otp-validation 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/ */
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements Nealyip\LaravelOTPValidation\OTP\OTPTarget {
/**
* Provide the email for the user used by the Email Provider,
* the return value may varies by the scene.
* May return empty string if you use only SMS otp.
*
* @param string $scene
* @return string
*/
public function otpEmail($scene = null)
{
return $this->email;
}
/**
* Provide the mobile phone number for the user used by the SMS Provider,
* the return value may varies by the scene.
*
* @param null $scene
* @return string
*/
public function otpMobile($scene = null)
{
return $this->country_code . $this->area_code . $this->mobile_number;
}
/**
* A unique user id, for example
*
* @return string
*/
public function otpIdentifier()
{
return $this->id;
}
}
use Nealyip\LaravelOTPValidation\Services\OTPValidationService;
class FormController{
protected $_service;
public function __construct(OTPValidationService $service) {
$this->_service = $service;
}
public function create(){
...
$user = request()->user();
$payload = $this->_service->scene('changepassword')->send($user, ['id' => $user->id], [], 'You are about to change your password, please complete with this one time password :otp');
return response()->json(['sent' => true, 'key' => $payload->key]);
}
use Nealyip\LaravelOTPValidation\Services\OTPValidationService;
class FormController{
protected $_service;
public function __construct(OTPValidationService $service) {
$this->_service = $service;
}
public function create(Request $request){
...
$user = request()->user();
if ($request->input('otp')) {
// WrongTargetException will be thrown if the otp is incorrect
$this->_service->scene('changepassword')->consume($user, ['id' => $user->id], $request->input('otp'));
// success validate the otp
// do your staff here
return .....
} else {
$payload = $this->_service->scene('changepassword')->send($user, ['id' => $user->id], [], 'You are about to change your password, please complete with this one time password :otp');
return response()->json(['sent' => true, 'key' => $payload->key]);
}
}