+91 7002160093 / 7002484119 HOSTEL FACILITIES AVAILABLE Download App
Uncategorized

How to Add Login With SMS Function in Flutter App?

Admin May 04, 2024 1 views

1. At first we will design the UI. Where we will be adding three buttons for login with SMS, Facebook And Google.

Container(
              child: Text('Or Login With'),
            ),
            SizedBox(
              height: 10,
            ),
            Container(
              alignment: Alignment.center,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [


                  GestureDetector(
                      onTap: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => const Register()),
                        );
                      },
                      child: Icon(Icons.sms),
                  ),
                  SizedBox(
                    width: 20,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => const Register()),
                      );
                    },
                    child: Icon(Icons.facebook),
                  ),
                  SizedBox(
                    width: 20,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => const Register()),
                      );
                    },
                    child: Icon(Icons.g_translate),
                  ),
                ],
              ),
            )

2. Next, we will create a screen for login with SMS called smslogin screen.

return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              margin: EdgeInsets.only(top: 100, bottom: 0),
            ),
            Image.network(
              'https://indiawebdesigns.in/assets/img/forgot.png',
              height: 300,
            ),
            Container(
                margin: EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 5),
                child: Text(
                  'Login to your Account',
                  style: TextStyle(fontSize: 25),
                )),
            Container(
              margin: EdgeInsets.only(left: 20, right: 20, top: 5, bottom: 5),
              child: TextField(
                controller: phoneController,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: '10 Digit Mobile Number',
                  focusColor: Colors.black,
                ),
              ),
            ),

            Container(
              margin: EdgeInsets.symmetric(horizontal: 50),
              // Add left and right margin here
              child: ElevatedButton(
                onPressed: () {
                  forgotsms(context);
                },
                child: Text(
                  'Reset Password',
                  style: TextStyle(fontSize: 18, color: Colors.white),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.deepPurple,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  minimumSize: Size(double.infinity, 40),
                  padding: EdgeInsets.symmetric(
                      horizontal: 20), // Add padding here if needed
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 20, bottom: 5),
              child: GestureDetector(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => const Login()),
                    );
                  },
                  child: Text('Back to Previous',
                      style: TextStyle(fontSize: 15))),
            ),

          ],
        ),
      ),
    );

3. Now, we will create the function for checking if the number exists in database and if yes then hit the API of SMS

final TextEditingController phoneController = TextEditingController();

  Future<void> forgotsms(BuildContext context) async {
    String getPhone = phoneController.text;


    // Make a POST request to the PHP file endpoint
    var url = Uri.parse(
        'https://indiawebdesigns.in/corporate-admin/controllers/Flutter/forgotsms.php');
    var response = await http.post(url, body: {
      'phone': getPhone
    });

    // Print the response and its body for debugging
    print('Response status: ${response.statusCode}');
    print('Response body: ${response.body}');

    // Parse the response JSON
    var data = jsonDecode(response.body);

    if (data != null && data['success'] != null && data['success']) {
      // Navigate to the dashboard screen
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(
          builder: (context) => Home(),
        ),
      );
    } else {
      // Show an error message
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Error'),
            content: Text('Mobile Number Not Found.'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text('OK'),
              ),
            ],
          );
        },
      );
    }
  }

4. We will then visit a website called mysms.webotapp.com and create an account and link it to our mobile

Once we receive the SMS API Key we will then create the script for sending SMS.


//curl

$curl = curl_init();
$message1 = "Dear $name, your otp for login is $otp. Thank you.";
$message2 = urlencode("$message1");

curl_setopt_array($curl, array(
CURLOPT_URL => "https://mysms.webotapp.com/services/send.php?key=YOUR-API-KEY&number=91$phone&message=$$message2&devices=3%7C0&type=sms&prioritize=0",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
));
$response = curl_exec($curl);
curl_close($curl);
//echo $response;

5. Now we will create the API for SMS Login and check if the phone number exists in database.

<?php

// Enable CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type");


 

ob_start();
require_once('../../database.php');

// Retrieve the username and password from the POST request
$userphone = $_POST['phone'];

// Query the database to check if credentials match
$query = "SELECT * FROM users WHERE user_phone = :phone AND status = 'Active'";
$stmt = $dbconn->prepare($query);
$stmt->bindParam(':phone', $userphone);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
    
    //Add the SMS API CODE HERE 
    
    //curl
        $phone = $user['user_phone'];
        $name = $user['user_name'];
        $id =  $user['id'];
        $curl = curl_init();
        $message1 = "Dear $name, your otp for login is $otp. Thank you.";
        $message2 = urlencode("$message1");
        
        curl_setopt_array($curl, array(
        CURLOPT_URL => "https://mysms.webotapp.com/services/send.php?key=d9786be3e0b77c6dab3e83479e27b1d94ee72235&number=91$phone&message=$message2&devices=3%7C0&type=sms&prioritize=0",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        //echo $response;
        
        
    // Valid credentials
    $response = [
        'success' => true,
        'message' => 'Succesfully Validated',
        'user_phone' => $user['user_phone'],
        'user_name' => $user['user_name'],
        'id' => $user['id'],
    ];
    
    


} else {
    // Invalid credentials
    $response = [
        'success' => false,
        'message' => 'Invalid username or password',
    ];
}

// Send the response as JSON
header('Content-Type: application/json');
echo json_encode($response);

6. In the next step we will have to create a new password and store it in our database

<?php

// Enable CORS headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Headers: Content-Type");


 

ob_start();
require_once('../../database.php');

// Retrieve the username and password from the POST request
$userphone = $_POST['phone'];

// Query the database to check if credentials match
$query = "SELECT * FROM users WHERE user_phone = :phone AND status = 'Active'";
$stmt = $dbconn->prepare($query);
$stmt->bindParam(':phone', $userphone);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
    
    //Add the SMS API CODE HERE 
    
    //curl
        $phone = $user['user_phone'];
        $name = $user['user_name'];
        $id =  $user['id'];
        
        
        
          //Update OTP
        $otp = rand(100000,999999);
        $encrypted_password = md5($otp);
        $sql_1 = "UPDATE users SET user_password = :value1 WHERE id = :id";
        $stmt_1 = $dbconn->prepare($sql_1);
        $stmt_1->bindParam(':value1', $encrypted_password);
        $stmt_1->bindParam(':id', $id);
        $stmt_1->execute();
        
        
        
        $curl = curl_init();
        $message1 = "Dear $name, your otp for login is $otp. Thank you.";
        $message2 = urlencode("$message1");
        
        curl_setopt_array($curl, array(
        CURLOPT_URL => "https://mysms.webotapp.com/services/send.php?key=d9786be3e0b77c6dab3e83479e27b1d94ee72235&number=91$phone&message=$message2&devices=3%7C0&type=sms&prioritize=0",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        //echo $response;
        
        
        
      
        
        
    // Valid credentials
    $response = [
        'success' => true,
        'message' => 'Succesfully Validated',
        'user_phone' => $user['user_phone'],
        'user_name' => $user['user_name'],
        'id' => $user['id'],
    ];
    
    


} else {
    // Invalid credentials
    $response = [
        'success' => false,
        'message' => 'Invalid username or password',
    ];
}

// Send the response as JSON
header('Content-Type: application/json');
echo json_encode($response);

Share this article: