nexmo sms otp verification in laravel 8

In today’s world, security is of utmost importance. When it comes to user authentication, one way to ensure that only the intended user can access the system is through phone number verification. Laravel 8 provides an easy and efficient way to add phone number verification using the Nexmo SMS API. In this article, we will guide you through the process of adding Nexmo SMS OTP verification to your Laravel 8 application.

Prerequisites

Before we dive into the process of adding Nexmo SMS OTP verification, you should have the following:

  1. A Laravel 8 application up and running.
  2. Composer installed on your system.
  3. A Nexmo account. You can sign up for a free account at https://dashboard.nexmo.com/sign-up

Step 1: Install Nexmo Client

The first step is to install the Nexmo client using Composer. Open up your terminal and navigate to the root directory of your Laravel 8 application. Once you are there, run the following command:

composer require nexmo/client

This will install the Nexmo client and all its dependencies.

Also Read : how to implement mobile otp verification in laravel 8 step by step

Step 2: Configure Nexmo API credentials

To use the Nexmo API, you need to configure your API credentials in your Laravel application. Open up your .env file and add the following:

NEXMO_API_KEY=your_api_keyNEXMO_API_SECRET=your_api_secretNEXMO_SMS_FROM=your_sms_sender_number

Replace your_api_key and your_api_secret with your actual API key and secret from your Nexmo dashboard. Replace your_sms_sender_number with the number you want to use as the sender for your SMS messages.

Read Also : how to implement mobile otp verification in laravel 8 step by step

Step 3: Create Route and Controller

Now that we have installed the Nexmo client and configured our API credentials, we can create a route and controller for our phone number verification feature.

In your routes/web.php file, add the following route:

Route::get('/verify-phone', 'Auth\PhoneVerificationController@showVerificationForm')->name('verify.phone.form');Route::post('/verify-phone', 'Auth\PhoneVerificationController@verifyPhoneNumber')->name('verify.phone');

In the above code, we have created two routes. The first one is a GET route that will display the phone number verification form, and the second one is a POST route that will verify the phone number.

Next, we need to create a controller for our phone number verification feature. Run the following command in your terminal:

php artisan make:controller Auth/PhoneVerificationController

This will create a new controller called PhoneVerificationController in the app/Http/Controllers/Auth directory.

In the PhoneVerificationController, add the following methods:

use Nexmo\Client as NexmoClient;class PhoneVerificationController extends Controller{    public function showVerificationForm()    {        return view('auth.verify-phone');    }    public function verifyPhoneNumber(Request $request)    {        $request->validate([            'phone_number' => 'required|regex:/^\d{10}$/',        ]);        $verificationCode = rand(100000, 999999);        $nexmo = new NexmoClient(new \Nexmo\Client\Credentials\Basic(config('nexmo.api_key'), config('nexmo.api_secret')));        $message = $nexmo->message()->send([            'to' => $request->input('phone_number'),            'from' => config('nexmo.sms_from'),            'text' => "Your verification code is: $verificationCode",        ]);        session(['verification_code' => $verificationCode]);        session(['phone_number' => $request->input('phone_number')]);        return redirect ()->route('verify.phone.form')->with('success', 'Verification code sent successfully.');}}

In the above code, we have created two methods. The first one is showVerificationForm() which will display the phone number verification form, and the second one is verifyPhoneNumber() which will send the SMS message to the provided phone number.

The verifyPhoneNumber() method first validates the phone number using Laravel’s built-in validation. If the phone number is valid, it generates a random verification code and sends an SMS message to the phone number using the Nexmo client. It then stores the verification code and phone number in the session.

Finally, it redirects back to the phone number verification form and adds a success message using the with() method.

Step 4: Create Verification Form

Now we need to create a view for our phone number verification form. Create a new file called verify-phone.blade.php in the resources/views/auth directory and add the following code:

@if(session('success'))<div class="alert alert-success">{{ session('success') }}</div>@endif<form method="POST" action="{{ route('verify.phone') }}">    @csrf<div class="form-group">    <label for="phone_number">Phone Number</label>    <input type="text" class="form-control @error('phone_number') is-invalid @enderror" id="phone_number" name="phone_number" value="{{ old('phone_number') }}" placeholder="Enter phone number">    @error('phone_number')        <div class="invalid-feedback">{{ $message }}</div>    @enderror</div><button type="submit" class="btn btn-primary">Send Verification Code</button></form>

In the above code, we have created a simple form that allows the user to enter their phone number. We have also added a success message that will be displayed if the SMS message is sent successfully.

Step 5: Verify Phone Number

The final step is to verify the phone number using the verification code. Modify the verifyPhoneNumber() method in the PhoneVerificationController to add the following code:

public function verifyPhoneNumber(Request $request){    $request->validate([        'phone_number' => 'required|regex:/^\d{10}$/',        'verification_code' => 'required',    ]);    if ($request->input('verification_code') == session('verification_code') && $request->input('phone_number') == session('phone_number')) {        // Phone number verified successfully        // Add your own logic here    } else {        return redirect()->back()->withErrors(['verification_code' => 'Invalid verification code'])->withInput();    }}

In the above code, we first validate the phone number and verification code using Laravel’s built-in validation. We then compare the verification code and phone number with the ones stored in the session. If they match, we can add our own logic to authenticate the user.

If the verification code or phone number does not match, we redirect back to the phone number verification form and display an error message using the withErrors() method.

Conclusion

In this article, we have shown you how to add Nexmo SMS OTP verification to your Laravel 8 application. We have created a route and controller for the phone number verification feature, and we have also created a view for the phone number verification form. Finally, we have shown you how to verify the phone number using the verification code. You can use this feature to add an extra layer of security to your Laravel 8 application.

Comments