获取用户电子邮件 - Google+登录

时间:2013-12-01 03:33:51

标签: javascript google-plus google-oauth

我使用JavaScript G+ Sign In让用户登录网站。我想显示他们登录的电子邮件,并将其放在网站上以确保用户知道他们已登录。我认为它可能是一个按钮属性,但是所有指向按钮属性的链接页面(例如this)链接到G +登录的概述。

HTML:

<span id="signinButton">
  <span
    class="g-signin"
    data-callback="signinCallback"
    data-clientid="26589332632-6ueke39kltk5cejpk5sdiu1i4i89m45a.apps.googleusercontent.com"
    data-cookiepolicy="single_host_origin"
    data-requestvisibleactions="http://schemas.google.com/AddActivity"
    data-scope="https://www.googleapis.com/auth/plus.login">
  </span>
</span>

JS:

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

P.S。这似乎并没有显示在jsFiddle中。

2 个答案:

答案 0 :(得分:1)

更改行:  数据范围= “https://www.googleapis.com/auth/plus.login” &GT; 至  data-scope =“https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email”&gt; 如此处所述:https://developers.google.com/+/api/oauth#scopes

这会将控制用户电子邮件地址访问权限的范围添加到您的代码中。

答案 1 :(得分:0)

在回调功能中,您可以执行以下操作:

<script type="text/javascript">

        var profile, email;

        function loginFinishedCallback(authResult) {
            if (authResult) {
                if (authResult['error'] == undefined){
                    gapi.client.load('plus','v1', loadProfile);  // Trigger request to get the email address.
                } else {
                    console.log('An error occurred');
                }
            } else {
                console.log('Empty authResult');  // Something went wrong
            }
        }

        /**
         * Uses the JavaScript API to request the user's profile, which includes
         * their basic information.
         */
        function loadProfile(){
            var request = gapi.client.plus.people.get( {'userId' : 'me'} );
            request.execute(loadProfileCallback);
        }

        function loadProfileCallback(obj) {
            profile = obj;
            email = obj['emails'].filter(function(v) {
                return v.type === 'account'; // Filter out the primary email
            })[0].value; // get the email from the filtered results, should always be defined.
            $('#name').html(email);
        }
 </script>