Sunday 24 June 2018

How to login with google auth using javascript

<meta name="google-signin-client_id" content="XXXYYY.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js?onload=onLoadGoogleCallback" async defer></script>

  <script type="text/javascript">
    function onLoadGoogleCallback(){
  gapi.load('auth2', function() {
    auth2 = gapi.auth2.init({
      client_id: 'XXXYYY.apps.googleusercontent.com',
      cookiepolicy: 'single_host_origin',
      scope: 'profile'
    });

  auth2.attachClickHandler(element, {},
    function(googleUser) {
       
   var profile = googleUser.getBasicProfile();
   console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
  console.log('Name: ' + profile.getName());
  console.log('Image URL: ' + profile.getImageUrl());
  console.log('Email: ' + profile.getEmail());
   var name = profile.getName();
   var id = profile.getId();
   //var gender = response.gender;
   var email = profile.getEmail();
   $.ajax({
            type: "get",
            async: false,
            url: "loginByAjaxg",
            dataType: 'json',
            data : {
                    'id' : id,
                    'name': name,
                    'email' : email
                  },
            success: function (data) {
                console.log("login user");
                console.log(data.msg);
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });

      }, function(error) {
        console.log('Sign-in error', error);
      }
    );
  });
  element = document.getElementById('googleSignIn');
}
 </script>



   <div class="center" >
          <button id="googleSignIn" class="loginBtn loginBtn--google">
  Login with Google
</button>
        </div>