Reputation: 21
I've been googling for 2 days for html and JavaScript code for adding firebase phone number authentication in my website. I saw the firebaseui doing this job. But it has their own form elements. I haven't found any articles or videos showing "how to make Firebase web auth with phone number, without using Firebaseui/nodejs. Is it really possible to do this with my own textbox and other buttons? I had written a code for this and it's not working. Please do a checkup or prefer any best articles, showing the exact thing I want. The code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Untitled</title>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "*****",
authDomain: "********.firebaseapp.com",
databaseURL: "https://********.firebaseio.com",
projectId: "*******",
storageBucket: "*********.appspot.com",
messagingSenderId: "**********"
};
firebase.initializeApp(config);
</script>
</head>
<body>
<script>
var phoneNumber = getPhoneNumberFromUserInput();
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
alert('sms sent');
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
}).catch(function (error) {
// Error; SMS not sent
// ...
alert('sms not send');
});
</script>
<form>
<input type="tel" id="number">
<input type="number" id="otp_code">
<input type="submit">
</form>
</body>
</html>
Thanks in advance.
Upvotes: 1
Views: 5825
Reputation: 1
# Try This Code. I have only add js/jquery code#
<script>
// Paste the config your copied earlier
var firebaseConfig = {
apiKey: "############################",
authDomain: "############################",
databaseURL: "############################",
projectId: "############################",
storageBucket: "############################",
messagingSenderId: "############################",
appId: "############################",
measurementId: "############################"
};
firebase.initializeApp(firebaseConfig);
// Create a Recaptcha verifier instance globally
// Calls submitPhoneNumberAuth() when the captcha is verified
//set size: "normal" to add recaptcha
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier(
"recaptcha-container",
{
size: "invisible",
callback: function(response) {
submitPhoneNumberAuth();
}
}
);
// This function runs when the 'sign-in-button' is clicked
// Takes the value from the 'phoneNumber' input and sends SMS to that phone number
function submitPhoneNumberAuth() {
$("#wait").css("display", "block");
$("#sign-in-button").attr("disabled", true);
var userPhone = document.getElementById("phoneNumber").value;
if(userPhone.length != 11){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Please Insert 11 digit Phone Number!!!");
$("#message").css("display", "block");
$("#wait").css("display", "none");
$("#sign-in-button").attr("disabled", false);
return false;
}
var phoneNumber = "+88"+userPhone;
//+88 only for bangladesh.Add your own country code
var appVerifier = window.recaptchaVerifier;
firebase
.auth()
.signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function(confirmationResult) {
document.getElementById('codeDiv').style.display='block';
document.getElementById('getCodeButton').style.display='none';
window.confirmationResult = confirmationResult;
$("#message").html("Please check your inbox and insert code!!!");
$("#message").css("display", "block");
$("#wait").css("display", "none");
})
.catch(function(error) {
$("#sign-in-button").attr("disabled", false);
$("#wait").css("display", "none");
console.log(error.code);
if(error.code == 'auth/invalid-phone-number'){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Invalid Phone Number!! Try Another Number!!!");
$("#message").css("display", "block");
document.getElementById('getCodeButton').style.display='block';
document.getElementById('codeDiv').style.display='none';
}
else if(error.code == 'auth/too-many-requests'){
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Too many request from this number. Try Another Number!!");
$("#message").css("display", "block");
document.getElementById('getCodeButton').style.display='block';
document.getElementById('codeDiv').style.display='none';
}
});
}
// This function runs when the 'confirm-code' button is clicked
// Takes the value from the 'code' input and submits the code to verify the phone number
// Return a user object if the authentication was successful, and auth is complete
function submitPhoneNumberAuthCode() {
$("#wait").css("display", "block");
$('#confirm-code').attr("disabled", true);
var code = document.getElementById("code").value;
confirmationResult
.confirm(code)
.then(function(result) {
var user = result.user;
$("#wait").css("display", "block");
$("#message").removeClass("alert-danger");
$("#message").addClass("alert-info");
$("#message").html("Thank you!!Code Matched!!");
$("#message").css("display", "block");
})
.catch(function(error) {
$("#wait").css("display", "none");
$('#confirm-code').attr("disabled", false);
console.log(error);
$("#message").removeClass("alert-info");
$("#message").addClass("alert-danger");
$("#message").html("Code Not Matched!!!");
$("#message").css("display", "block");
});
}
//This function runs everytime the auth state changes. Use to verify if the user is logged in
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
//You are logged IN from firebase
$("#message").removeClass("alert-danger");
$("#message").addClass("alert-info");
$("#message").html("Congratulations!!!Logging...");
$("#message").css("display", "block");
var phone = user.phoneNumber;
firebase.auth().signOut().then(function() {
////You are logged Out from firebase
console.log("Firebase Signout");
}).catch(function(error) {
console.log("Firebase Signout Problem!!");
});
}
Upvotes: 0
Reputation: 30848
There are a lot of examples including the Firebase GitHub sample quick start apps: https://github.com/firebase/quickstart-js/blob/master/auth/phone-invisible.html
Also check the official docs on this: https://firebase.google.com/docs/auth/web/phone-auth
Here is a quick snippet on signing in a user with phone number:
firebase.auth().signInWithPhoneNumber("+xxxxxxxx", window.recaptchaVerifier)
.then((confirmationResult) => {
// At this point SMS is sent. Ask user for code.
let code = window.prompt('Please enter the 6 digit code');
return confirmationResult.confirm(code);
})
.then((result) {
// User is now signed in and accessible via result.user.
});
.catch((error) => {
// Error occurred.
});
Upvotes: 1