0

Я пытаюсь интегрировать вход Google на моем веб-сайте. Я выполнил инструкции, приведенные на странице Google sign in page. Я правильно установил идентификатор клиента и после создания проекта в соответствии с инструкциями. Значок на странице отображается правильно и просит предоставить разрешения для доступа к базовому профилю и электронной почте. Как только я нажимаю «Принять», я не могу получить данные профиля пользователя и печатать на консоли в функции javascript, которая вызывается после успешного входа в систему. Ниже приведен код:Не удается получить информацию о профиле после входа пользователя на мой сайт с помощью Google.

<html lang="en"> 
    <head> 
    <meta name="google-signin-scope" content="profile email"> 
    <meta name="google-signin-client_id" content="client_id.apps.googleusercontent.com"> 
    <script src="https://apis.google.com/js/platform.js" async defer></script> 
    </head> 
    <body> 
    <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div> 
    <script> 
     function onSignIn(googleUser) { 
     // Useful data for your client-side scripts: 
     console.log("console works"); 
     var profile = googleUser.getBasicProfile(); 
     console.log("ID: " + profile.getId()); // Don't send this directly to your server! 
     console.log("Name: " + profile.getName()); 
     console.log("Image URL: " + profile.getImageUrl()); 
     console.log("Email: " + profile.getEmail()); 

     // The ID token you need to pass to your backend: 
     var id_token = googleUser.getAuthResponse().id_token; 
     console.log("ID Token: " + id_token); 
     }; 

    </script> 



    </body> 
</html> 

Я удалил идентификатор клиента в коде, размещенных выше соображений конфиденциальности, но в фактической реализации я включил его.

+0

Можете ли вы попытаться поставить '' внизу тела? –

ответ

0

Я не вполне понятно, с кодом

Но попробуйте этот код. Его работает отлично для меня

Включите его в <head> теге

<head> 
    <script type="text/javascript"> 
    (function() { 
    var po = document.createElement('script'); 
    po.type = 'text/javascript'; po.async = true; 
    po.src = 'https://plus.google.com/js/client:plusone.js'; 
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(po, s); 
    })(); 
    </script> 
    </head> 

Включите его в <Body>

<body>  
<button class="g-signin " 
         data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email" 
         data-requestvisibleactions="http://schemas.google.com/AddActivity" 
         data-clientId="----YOUR CLIET ID----" 
         data-accesstype="offline" 
         data-callback="mycoddeSignIn" 
         data-theme="dark" 
         data-cookiepolicy="single_host_origin"> 
        </button> 
</body> 

и сценарий для извлечения данных

DonT для прибудете добавить

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

<script type="text/javascript"> 
var gpclass = (function(){ 

//Defining Class Variables here 
var response = undefined; 
return { 
    //Class functions/Objects 

    mycoddeSignIn:function(response){ 
     // The user is signed in 
     if (response['access_token']) { 

      //Get User Info from Google Plus API 
      gapi.client.load('plus','v1',this.getUserInformation); 

     } else if (response['error']) { 
      // There was an error, which means the user is not signed in. 
      //alert('There was an error: ' + authResult['error']); 
     } 
    }, 

    getUserInformation: function(){ 
     var request = gapi.client.plus.people.get({'userId' : 'me'}); 
     request.execute(function(profile) { 
      var email = profile['emails'].filter(function(v) { 
       return v.type === 'account'; // Filter out the primary email 
      })[0].value; 
      var fName = profile.displayName; 
      console.log(fName); 
      console.log(email); 
     }); 
    } 

}; //End of Return 
})(); 

function mycoddeSignIn(gpSignInResponse){ 
    gpclass.mycoddeSignIn(gpSignInResponse); 
} 
</script> 

Проверка на консоли данные будут их.

0

У меня такая же проблема, появляется страница с надписью, но функция onSignIn() никогда не была достигнута. Я пробовал несколько других способов, например, с помощью пользовательской кнопки входа, но у меня такая же проблема.

Возможно, возникла некоторая проблема в Google Developers Console? У меня включен API Google+.