1

I have create some personal project with wordpress + php + google firebase. I want to execute function if Google firebase OTP verification is success.

Here is the code

function devsol_customer_form() { ?>
<form>
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">  
<label for="number"><?php esc_html_e( 'Mobile Number', 'woocommerce' ); ?>&nbsp;<span class="required">*</span></label>
<input type="tel" class="woocommerce-Input woocommerce-Input--text input-text" name="number" id="number"/>
</p>
<div id="recaptcha-container"></div>
<button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="phoneAuth();">SendCode</button>
</form>
<br/>
<h1>Enter Verification code</h1>
<form>
    <input type="text" id="verificationCode" placeholder="Enter verification code" class="woocommerce-Input woocommerce-Input--text input-text">
    <button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="codeverify();">Verify code</button>
</form>

<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#config-web-app -->

<script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
    apiKey: "*****",
    authDomain: "*****",
    databaseURL: "*****",
    projectId: "*****",
    storageBucket: "*****",
    messagingSenderId: "*****",
    appId: "*****"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
</script>

<script>
window.onload=function () {
  render();
};
function render() {
    window.recaptchaVerifier=new firebase.auth.RecaptchaVerifier('recaptcha-container');
    recaptchaVerifier.render();
}
function phoneAuth() {
    //get the number
    var number=document.getElementById('number').value;
    //phone number authentication function of firebase
    //it takes two parameter first one is number,,,second one is recaptcha
    firebase.auth().signInWithPhoneNumber(number,window.recaptchaVerifier).then(function (confirmationResult) {
        //s is in lowercase
        window.confirmationResult=confirmationResult;
        coderesult=confirmationResult;
        console.log(coderesult);
        alert("Message sent");
    }).catch(function (error) {
        alert(error.message);
    });
}
function codeverify() {
    var code=document.getElementById('verificationCode').value;
    coderesult.confirm(code).then(function (result) {
        alert("Successfully registered");
        var user=result.user;
        console.log(user);
    }).catch(function (error) {
        alert(error.message);
    });
}    
</script>
<?php }
add_action('woocommerce_after_customer_login_form', 'devsol_customer_form');

I want if user successfully verify the OTP then this function call in my php file. I am using function.php file in my wordpress theme.

function devsol_customer_auth() {
    $user_phone = sanitize_text_field( $_POST['number'] );
    if ( $user = get_user_by( 'login', $user_phone) ) {
        $user_id = $user->ID;
        $user_roles = $user->roles;
        $user_role = array_shift($user_roles);
        if ( $user_role === 'customer') {
            if ( apply_filters( 'woocommerce_registration_auth_new_customer', true, $user_id ) ) {  
                wc_set_customer_auth_cookie( $user_id );
                }   
            }
        }           
}
add_action('init', 'devsol_customer_auth');

Someone please help

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
Iqbal
  • 9
  • 4
  • 2
    You just posted your Firebase credentials, you'll want to change them immediately. – Alex Howansky Jan 03 '20 at 18:04
  • 1
    @AlexHowansky The stuff in `firebaseConfig` are not really credentials. It's configuration that's always visible to everyone who has the URL to the app. The configuration can't be changed (except appId, which is tied to a particular app within a project that can be deleted and re-added). – Doug Stevenson Jan 03 '20 at 18:18
  • @DougStevenson Ahhh I see, it's inside a JS block, didn't even notice that. Hmm, doesn't the API key allow you arbitrary read access? Is that not a concern? – Alex Howansky Jan 03 '20 at 18:22
  • @AlexHowansky Hi, I have added a domain only access in my google firebase settings, so it only receive access from specific domain only. – Iqbal Jan 03 '20 at 18:24
  • @AlexHowansky The API key is just a unique project identifier used with some products. If you want to restrict access to public web and mobile clients, it's advised to use Firebase Authentication and security rules to lock down access. – Doug Stevenson Jan 03 '20 at 18:58
  • @AlexHowansky: see https://stackoverflow.com/questions/37482366/is-it-safe-to-expose-firebase-apikey-to-the-public – Frank van Puffelen Jan 03 '20 at 20:00
  • @FrankvanPuffelen Nice, thanks for the info. I saw "apiKey" and assumed the worst. (Would be probably the fourth time this week I've seen somebody post an API key....) – Alex Howansky Jan 03 '20 at 20:04
  • Yeah, I wish we'd given that key a different name. Especially since there are server-side API keys that you definitely should not be using in your client-side code. :-/ – Frank van Puffelen Jan 03 '20 at 20:15

1 Answers1

2

You cannot directly call php function from javascript(JS) as JS runs on the client side like on the browser and your php file exists on the webserver. In order to do something like that, you'll need to make request to the php file and pass parameter in the request(could be GET or POST). A simple example of such could be

  1. create a separate php file, lets say actions.php, that will be hit by the request.

  2. make a request to the file from JS E.g.

    function httpGet(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return xmlHttp.responseText;
    }
    httpGet('www.yourSite.com/actions.php?phone=' + userPhoneNumber);
    

This should resolve your problem.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • This, of course, is what's called "AJAX." Your JavaScript composes and posts an HTTP request to the PHP-based server, which receives the request and returns a response. Your JavaScript then specifies a handler which will be called *asynchronously* when that response arrives. – Mike Robinson Jan 03 '20 at 20:55