Firebase Number Authentication with OTP in JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Firebase Phone Auth</title>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
</head>
<body>
    <div id="recaptcha-container"></div>
    <input type="text" id="verificationcode" placeholder="Enter verification code">
    <button onclick="codeverify()">Verify Code</button>

    <script>
        const firebaseConfig = {
            apiKey: "AIzaSyC3MIN64hy_oTQfQWUHl0lID-CJkIfci0M",
            authDomain: "yt-project-a29f8.firebaseapp.com",
            projectId: "yt-project-a29f8",
            storageBucket: "yt-project-a29f8.appspot.com",
            messagingSenderId: "159898773748",
            appId: "1:159898773748:web:2985334de4f06ff73356a1",
            measurementId: "G-DLWR9M5SJC"
        };

        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);

        // Configure reCAPTCHA verifier
        window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', {
            'size': 'invisible',
            'callback': function(response) {
                // reCAPTCHA solved - allow user to proceed with phone auth.
                phoneAuth();
            }
        });

        // Function to send OTP
        function phoneAuth() {
            var number = "++9191...";
            firebase.auth().signInWithPhoneNumber(number, window.recaptchaVerifier).then(function (confirmationResult) {
                window.confirmationResult = confirmationResult;
                console.log('OTP Sent');
            }).catch(function (error) {
                // Error in sending OTP
                alert(error.message);
            });
        }

        // Function to verify OTP
        function codeverify() {
            var code = document.getElementById('verificationcode').value;
            window.confirmationResult.confirm(code).then(function (result) {
                // OTP verified
                console.log('OTP Verified');
                var user = result.user;
                console.log(user);
            }).catch(function (error) {
                // Error in verifying OTP
                console.log('OTP Not correct: ' + error.message);
            });
        }

        // Trigger phoneAuth function when the page loads
        phoneAuth();
    </script>
</body>
</html>



Post a Comment

Previous Post Next Post