Setup for SMS Verification
Message Central is a CPaaS solution with a suite of products including OTP SMS APIs, SMS APIs and WhatsApp marketing platform.
- Create a MessageCentral Account: Sign up for a Message Central account to get started. You will receive a customer ID, which you will use in your application.
- Download and Install Flutter:
Download Flutter: Go to the Flutter download page on the official Flutter website: Flutter Downloads.
Download the Flutter SDK for your operating system (Windows, macOS, or Linux).Install Flutter:
Windows:
Extract the downloaded Flutter SDK zip file to a location on your system.
Add the Flutter bin directory to your system PATH variable.
macOS/Linux:
Extract the downloaded Flutter SDK tar.gz file to a location on your system.
Add the Flutter bin directory to your system PATH variable.
Verify Installation:
Open a command prompt (on Windows) or terminal (on macOS/Linux).
Run the following command to verify the installation:
- flutter--version
This should print the installed Flutter version. If installed correctly, you should see something like:
Flutter x.x.x • channel stable • ...
Set PATH Environment Variable (Windows):
Right-click on "This PC" or "My Computer" and select "Properties".
Click on "Advanced system settings" and then "Environment Variables".
In the "System variables" section, select the "Path" variable and click "Edit".
Add the path to the Flutter bin directory (e.g., C:\Flutter\bin) if it's not already present.
Click "OK" to save the changes.
Set PATH Environment Variable (macOS/Linux):
Open a terminal and open or create the .bash_profile file in your home directory.
Add the following line, replacing /path/to/flutter with the actual path to your Flutter bin directory:
export PATH=$PATH:/path/to/flutter/bin
Save the file and restart the terminal for the changes to take effect.
After following these steps, Flutter should be installed and ready to use on your system. You can now use Flutter to develop cross-platform mobile applications.
Integration Steps
This process involves the following three significant steps:
- Message Central Details
- Adding Message Central Details in Code
- Send a Test Otp for verification
a. Message Central Details
After creating an account on Message Central, you need the following details:
- Customer Id - You can get the customer ID from Message Central Home Console
- Login Credentials: You’d require an email and would need to create a password.
b. Adding MessageCentral Details in Code
To add MessageCentral details on the code find out the variable definition with name “customerId”, “email” and “password”:
String customerID = "C-45539F39A44****";
String email = "abhishek****k68@gmail.com";
String password = "*****";
String baseURL = "https://cpaas.messagecentral.com";
String? authToken;String? verificationId;
String? verificationStatus;
Create a new Flutter project:
Start by creating a new Flutter project using the following command:
flutter create otp_app
Navigate to the project directory:
Navigate to the newly created project directory:
cd otp_app
Update pubspec.yaml:
Add the http package to your project's dependencies in the pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3
Replace the contents of lib/main.dart:
Replace the contents of lib/main.dart with the following code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'OTP App',
home: OtpPage(),
);
}
}
class OtpPage extends StatefulWidget {
@override
_OtpPageState createState() => _OtpPageState();
}
class _OtpPageState extends State<OtpPage> {
late TextEditingController _countryCodeController;
late TextEditingController _mobileNumberController;
late TextEditingController _otpController;
String baseURL = "https://cpaas.messagecentral.com";
String customerID = "C-45539F39A449437";
String password = "Test@123";
String email = "abhishekkaushik68@gmail.com";
String? _authToken;
String? _verificationId;
String? _verificationStatus;
@override
void initState() {
super.initState();
_countryCodeController = TextEditingController();
_mobileNumberController = TextEditingController();
_otpController = TextEditingController();
}
@override
void dispose() {
_countryCodeController.dispose();
_mobileNumberController.dispose();
_otpController.dispose();
super.dispose();
}
Future<void> _sendOtp() async {
final countryCode = _countryCodeController.text;
final mobileNumber = _mobileNumberController.text;
final base64String = base64Encode(utf8.encode(password));
final url =
'$baseURL/auth/v1/authentication/token?country=IN&customerId=$customerID&email=$email&key=$base64String&scope=NEW';
try {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
_authToken = jsonDecode(response.body)['token'];
final sendOtpUrl =
'$baseURL/verification/v3/send?countryCode=$countryCode&customerId=$customerID&flowType=SMS&mobileNumber=$mobileNumber';
final sendOtpResponse = await http.post(Uri.parse(sendOtpUrl),
headers: {'authToken': _authToken ?? ''});
if (sendOtpResponse.statusCode == 200) {
setState(() {
_verificationId =
jsonDecode(sendOtpResponse.body)['data']['verificationId'];
});
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('OTP sent successfully')));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Failed to send OTP')));
}
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error generating auth token')));
}
} catch (e) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Error sending OTP')));
}
}
Future<void> _validateOtp() async {
final otpCode = _otpController.text;
final countryCode = _countryCodeController.text;
final mobileNumber = _mobileNumberController.text;
final url =
'$baseURL/verification/v3/validateOtp?countryCode=$countryCode&mobileNumber=$mobileNumber&verificationId=$_verificationId&customerId=$customerID&code=$otpCode';
try {
final response = await http
.get(Uri.parse(url), headers: {'authToken': _authToken ?? ''});
if (response.statusCode == 200) {
_verificationStatus = jsonDecode(response.body)['verificationStatus'];
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('OTP validated successfully')));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Failed to validate OTP')));
}
} catch (e) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('Error validating OTP')));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('OTP App')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: _countryCodeController,
decoration: InputDecoration(labelText: 'Country Code'),
),
TextField(
controller: _mobileNumberController,
decoration: InputDecoration(labelText: 'Mobile Number'),
),
ElevatedButton(
onPressed: _sendOtp,
child: Text('Send OTP'),
),
if (_verificationId != null)
Column(
children: [
TextField(
controller: _otpController,
decoration: InputDecoration(labelText: 'Enter OTP'),
),
ElevatedButton(
onPressed: _validateOtp,
child: Text('Validate OTP'),
),
if (_verificationStatus != null)
Text('Verification Status: $_verificationStatus'),
],
),
],
),
),
);
}
}
c. Send a Test Otp Sms for Verification
If you need to test the service without code, you can go to the free SMS verification page on the Message Central’s website.
To ensure that the integration is successful, send a test OTP SMS as follows:
- Run the Flutter app:
Run the Flutter app on an emulator or a physical device:
flutter run
This will execute your Flutter/Dart script and display any output it generates. If your script contains Flutter UI code, it will run the Flutter application and display the UI on the screen.
- Testing on Emulator/Device:
Run your Flutter app on an emulator or a physical device using flutter run command. Enter a country code, mobile number, and click on the "Send OTP" button to simulate sending OTP. Then, enter the OTP code and click on the "Validate OTP" button to simulate validating OTP.
