How to Add Login With SMS Function in Flutter App?
By Webotapp Academy•
<!-- wp:heading -->\n<h3 class=\"wp-block-heading\">1. At first we will design the UI. Where we will be adding three buttons for login with SMS, Facebook And Google.</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>Container(\n child: Text('Or Login With'),\n ),\n SizedBox(\n height: 10,\n ),\n Container(\n alignment: Alignment.center,\n child: Row(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n\n\n GestureDetector(\n onTap: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => const Register()),\n );\n },\n child: Icon(Icons.sms),\n ),\n SizedBox(\n width: 20,\n ),\n GestureDetector(\n onTap: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => const Register()),\n );\n },\n child: Icon(Icons.facebook),\n ),\n SizedBox(\n width: 20,\n ),\n GestureDetector(\n onTap: () {\n Navigator.push(\n context,\n MaterialPageRoute(\n builder: (context) => const Register()),\n );\n },\n child: Icon(Icons.g_translate),\n ),\n ],\n ),\n )</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading -->\n<h3 class=\"wp-block-heading\">2. Next, we will create a screen for login with SMS called smslogin screen.</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>return Scaffold(\n body: SingleChildScrollView(\n child: Column(\n mainAxisAlignment: MainAxisAlignment.center,\n children: [\n Container(\n margin: EdgeInsets.only(top: 100, bottom: 0),\n ),\n Image.network(\n 'https://indiawebdesigns.in/assets/img/forgot.png',\n height: 300,\n ),\n Container(\n margin: EdgeInsets.only(left: 20, right: 20, top: 0, bottom: 5),\n child: Text(\n 'Login to your Account',\n style: TextStyle(fontSize: 25),\n )),\n Container(\n margin: EdgeInsets.only(left: 20, right: 20, top: 5, bottom: 5),\n child: TextField(\n controller: phoneController,\n decoration: InputDecoration(\n border: OutlineInputBorder(),\n hintText: '10 Digit Mobile Number',\n focusColor: Colors.black,\n ),\n ),\n ),\n\n Container(\n margin: EdgeInsets.symmetric(horizontal: 50),\n // Add left and right margin here\n child: ElevatedButton(\n onPressed: () {\n forgotsms(context);\n },\n child: Text(\n 'Reset Password',\n style: TextStyle(fontSize: 18, color: Colors.white),\n ),\n style: ElevatedButton.styleFrom(\n backgroundColor: Colors.deepPurple,\n shape: RoundedRectangleBorder(\n borderRadius: BorderRadius.circular(10),\n ),\n minimumSize: Size(double.infinity, 40),\n padding: EdgeInsets.symmetric(\n horizontal: 20), // Add padding here if needed\n ),\n ),\n ),\n Container(\n margin: EdgeInsets.only(top: 20, bottom: 5),\n child: GestureDetector(\n onTap: () {\n Navigator.push(\n context,\n MaterialPageRoute(builder: (context) => const Login()),\n );\n },\n child: Text('Back to Previous',\n style: TextStyle(fontSize: 15))),\n ),\n\n ],\n ),\n ),\n );</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading -->\n<h3 class=\"wp-block-heading\">3. Now, we will create the function for checking if the number exists in database and if yes then hit the API of SMS</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>final TextEditingController phoneController = TextEditingController();\n\n Future<void> forgotsms(BuildContext context) async {\n String getPhone = phoneController.text;\n\n\n // Make a POST request to the PHP file endpoint\n var url = Uri.parse(\n 'https://indiawebdesigns.in/corporate-admin/controllers/Flutter/forgotsms.php');\n var response = await http.post(url, body: {\n 'phone': getPhone\n });\n\n // Print the response and its body for debugging\n print('Response status: ${response.statusCode}');\n print('Response body: ${response.body}');\n\n // Parse the response JSON\n var data = jsonDecode(response.body);\n\n if (data != null && data['success'] != null && data['success']) {\n // Navigate to the dashboard screen\n Navigator.pushReplacement(\n context,\n MaterialPageRoute(\n builder: (context) => Home(),\n ),\n );\n } else {\n // Show an error message\n showDialog(\n context: context,\n builder: (BuildContext context) {\n return AlertDialog(\n title: Text('Error'),\n content: Text('Mobile Number Not Found.'),\n actions: [\n TextButton(\n onPressed: () {\n Navigator.pop(context);\n },\n child: Text('OK'),\n ),\n ],\n );\n },\n );\n }\n }\n</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading -->\n<h3 class=\"wp-block-heading\"><strong>4. We will then visit a website called mysms.webotapp.com and create an account and link it to our mobile</strong></h3>\n<!-- /wp:heading -->\n\n<!-- wp:paragraph -->\n<p>Once we receive the SMS API Key we will then create the script for sending SMS.</p>\n<!-- /wp:paragraph -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code>\n//curl\n\n$curl = curl_init();\n$message1 = \"Dear $name, your otp for login is $otp. Thank you.\";\n$message2 = urlencode(\"$message1\");\n\ncurl_setopt_array($curl, array(\nCURLOPT_URL => \"https://mysms.webotapp.com/services/send.php?key=<strong>YOUR-API-KEY</strong>&number=91$phone&message=$$message2&devices=3%7C0&type=sms&prioritize=0\",\nCURLOPT_RETURNTRANSFER => true,\nCURLOPT_ENCODING => '',\nCURLOPT_MAXREDIRS => 10,\nCURLOPT_TIMEOUT => 0,\nCURLOPT_FOLLOWLOCATION => true,\nCURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\nCURLOPT_CUSTOMREQUEST => 'GET',\n));\n$response = curl_exec($curl);\ncurl_close($curl);\n//echo $response;</code></pre>\n<!-- /wp:code -->\n\n<!-- wp:heading -->\n<h3 class=\"wp-block-heading\">5. Now we will create the API for SMS Login and check if the phone number exists in database.</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code><?php\n\n// Enable CORS headers\nheader(\"Access-Control-Allow-Origin: *\");\nheader(\"Access-Control-Allow-Methods: GET, POST\");\nheader(\"Access-Control-Allow-Headers: Content-Type\");\n\n\n \n\nob_start();\nrequire_once('../../database.php');\n\n// Retrieve the username and password from the POST request\n$userphone = $_POST['phone'];\n\n// Query the database to check if credentials match\n$query = \"SELECT * FROM users WHERE user_phone = :phone AND status = 'Active'\";\n$stmt = $dbconn->prepare($query);\n$stmt->bindParam(':phone', $userphone);\n$stmt->execute();\n$user = $stmt->fetch(PDO::FETCH_ASSOC);\n\nif ($user) {\n \n //Add the SMS API CODE HERE \n \n //curl\n $phone = $user['user_phone'];\n $name = $user['user_name'];\n $id = $user['id'];\n $curl = curl_init();\n $message1 = \"Dear $name, your otp for login is $otp. Thank you.\";\n $message2 = urlencode(\"$message1\");\n \n curl_setopt_array($curl, array(\n CURLOPT_URL => \"https://mysms.webotapp.com/services/send.php?key=d9786be3e0b77c6dab3e83479e27b1d94ee72235&number=91$phone&message=$message2&devices=3%7C0&type=sms&prioritize=0\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => '',\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 0,\n CURLOPT_FOLLOWLOCATION => true,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => 'GET',\n ));\n $response = curl_exec($curl);\n curl_close($curl);\n //echo $response;\n \n \n // Valid credentials\n $response = [\n 'success' => true,\n 'message' => 'Succesfully Validated',\n 'user_phone' => $user['user_phone'],\n 'user_name' => $user['user_name'],\n 'id' => $user['id'],\n ];\n \n \n\n\n} else {\n // Invalid credentials\n $response = [\n 'success' => false,\n 'message' => 'Invalid username or password',\n ];\n}\n\n// Send the response as JSON\nheader('Content-Type: application/json');\necho json_encode($response);</code></pre>\n<!-- /wp:code -->\n\n\n\n<!-- wp:heading -->\n<h3 class=\"wp-block-heading\">6. In the next step we will have to create a new password and store it in our database</h3>\n<!-- /wp:heading -->\n\n<!-- wp:code -->\n<pre class=\"wp-block-code\"><code><?php\n\n// Enable CORS headers\nheader(\"Access-Control-Allow-Origin: *\");\nheader(\"Access-Control-Allow-Methods: GET, POST\");\nheader(\"Access-Control-Allow-Headers: Content-Type\");\n\n\n \n\nob_start();\nrequire_once('../../database.php');\n\n// Retrieve the username and password from the POST request\n$userphone = $_POST['phone'];\n\n// Query the database to check if credentials match\n$query = \"SELECT * FROM users WHERE user_phone = :phone AND status = 'Active'\";\n$stmt = $dbconn->prepare($query);\n$stmt->bindParam(':phone', $userphone);\n$stmt->execute();\n$user = $stmt->fetch(PDO::FETCH_ASSOC);\n\nif ($user) {\n \n //Add the SMS API CODE HERE \n \n //curl\n $phone = $user['user_phone'];\n $name = $user['user_name'];\n $id = $user['id'];\n \n \n \n //Update OTP\n $otp = rand(100000,999999);\n $encrypted_password = md5($otp);\n $sql_1 = \"UPDATE users SET user_password = :value1 WHERE id = :id\";\n $stmt_1 = $dbconn->prepare($sql_1);\n $stmt_1->bindParam(':value1', $encrypted_password);\n $stmt_1->bindParam(':id', $id);\n $stmt_1->execute();\n \n \n \n $curl = curl_init();\n $message1 = \"Dear $name, your otp for login is $otp. Thank you.\";\n $message2 = urlencode(\"$message1\");\n \n curl_setopt_array($curl, array(\n CURLOPT_URL => \"https://mysms.webotapp.com/services/send.php?key=d9786be3e0b77c6dab3e83479e27b1d94ee72235&number=91$phone&message=$message2&devices=3%7C0&type=sms&prioritize=0\",\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_ENCODING => '',\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 0,\n CURLOPT_FOLLOWLOCATION => true,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => 'GET',\n ));\n $response = curl_exec($curl);\n curl_close($curl);\n //echo $response;\n \n \n \n \n \n \n // Valid credentials\n $response = [\n 'success' => true,\n 'message' => 'Succesfully Validated',\n 'user_phone' => $user['user_phone'],\n 'user_name' => $user['user_name'],\n 'id' => $user['id'],\n ];\n \n \n\n\n} else {\n // Invalid credentials\n $response = [\n 'success' => false,\n 'message' => 'Invalid username or password',\n ];\n}\n\n// Send the response as JSON\nheader('Content-Type: application/json');\necho json_encode($response);</code></pre>\n<!-- /wp:code -->