试图简单地实现谷歌+登录按钮HTML

时间:2015-02-17 16:57:13

标签: html button google-plus

我正在尝试在我的网站上实施谷歌+登录按钮!使用HTML,我不知道为什么按钮本身不起作用。我遵循这些指示: https://developers.google.com/+/web/signin/add-button

这是我到目前为止(我最初找到登录和注销按钮的代码,但决定只使用google + API)

我将这段代码放在哪里?

function signinCallback(authResult) {
  if (authResult['status']['signed_in']) {
    // Update the app to reflect a signed in user
    // Hide the sign-in button now that the user is authorized, for example:
    document.getElementById('signinButton').setAttribute('style', 'display: none');
  } else {
    // Update the app to reflect a signed out user
    // Possible error values:
    //   "user_signed_out" - User is signed-out
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatically log in the user
    console.log('Sign-in state: ' + authResult['error']);
  }
}

我错过了一个onclicklistener或者其他什么?谢谢!!!

<!DOCTYPE html>
<html>
<head>
<script src="https://apis.google.com/js/client:platform.js" async defer></script>
</head>
<body>
<!---<input type="button"  value="Login" onclick="login()" />
<input type="button"  value="Logout" onclick="logout()" />--->

 <span id="signinButton">
  <span
    class="g-signin"
    data-callback="signinCallback"
    data-clientid="805034040388-erokn7fetmrl9id1romu3o75m7tbnpqp.apps.googleusercontent.com"
    data-cookiepolicy="single_host_origin"
    data-requestvisibleactions="http://schema.org/AddAction"
    data-scope="https://www.googleapis.com/auth/plus.login">

  </span>

</span>



<div id="profile"></div>
<script type="text/javascript">


function logout()
{
    gapi.auth.signOut();
    location.reload();
}
function login() 
{
  var myParams = {
    'clientid' : 'PUTYOUR_CLIENT_ID.apps.googleusercontent.com',
    'cookiepolicy' : 'single_host_origin',
    'callback' : 'loginCallback',
    'approvalprompt':'force',
    'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
  };
  gapi.auth.signIn(myParams);
}

function loginCallback(result)
{
    if(result['status']['signed_in'])
    {
        var request = gapi.client.plus.people.get(
        {
            'userId': 'me'
        });
        request.execute(function (resp)
        {
            var email = '';
            if(resp['emails'])
            {
                for(i = 0; i < resp['emails'].length; i++)
                {
                    if(resp['emails'][i]['type'] == 'account')
                    {
                        email = resp['emails'][i]['value'];
                    }
                }
            }

            var str = "Name:" + resp['displayName'] + "<br>";
            str += "Image:" + resp['image']['url'] + "<br>";
            str += "<img src='" + resp['image']['url'] + "' /><br>";

            str += "URL:" + resp['url'] + "<br>";
            str += "Email:" + email + "<br>";
            document.getElementById("profile").innerHTML = str;
        });

    }

}
function onLoadCallback()
{
    gapi.client.setApiKey('PUT_YOUR_KEY');
    gapi.client.load('plus', 'v1',function(){});
}

    </script>

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

</body>
</html>

2 个答案:

答案 0 :(得分:2)

我在我的localhost中工作了。 请确保您已按照该链接中的正确步骤。 特别是第一步

完成第一步后,您必须注意两个重要细节:

  1. 无论您添加哪种生产网址,这些都可以用于您的按钮。如果您有托管,请添加,否则我希望您可以使用localhost服务器(wamp,xampp等)运行代码。
  2. 客户ID
  3. 现在,如果您运行特定的客户ID生产网址,这段代码可以正常工作(请注意在下面的代码中添加正确的客户ID)

    <html>
    <head>
      <title>Google+ Sign-in button demo</title>
      <style type="text/css">
      html, body { margin: 0; padding:0;}
      #signin-button {
       padding: 5px;
      }
    
      #oauth2-results pre { margin: 0; padding:0;}
      .hide { display: none;}
      .show { display: block;}
      </style>
      <script type="text/javascript">
    
      var loginFinished = function(authResult) {
        if (authResult) {
          var el = document.getElementById('oauth2-results');
          var label = '';
          toggleDiv('oauth2-results');
          if (authResult['status']['signed_in']) {
            label = 'User granted access:';
            gapi.auth.setToken(authResult);
          } else {
            label = 'Access denied: ' + authResult['error'];
          }
          el.innerHTML =
              label + '<pre class="prettyprint"><code>' +
              // JSON.stringify doesn't work in IE8.
              '{<br />' +
              '  "id_token" : "' + authResult['id_token'] +'",<br />' +
              '  "access_token" : "' + authResult['access_token'] + '",<br />' +
              '  "state" : "' + authResult['state'] + '",<br />' +
              '  "expires_in" : "' + authResult['expires_in'] + '",<br />' +
              '  "error" : "' + authResult['error'] + '",<br />' +
              '  "error_description" : "' + authResult['error_description'] + '",<br />' +
              '  "authUser" : "' + authResult['authuser'] + '",<br />' +
              '  "status" : {"' + '<br />' +
              '    "google_logged_in" : "' + authResult['status']['google_logged_in'] + '",<br />' +
              '    "method" : "' + authResult['status']['method'] + '",<br />' +
              '    "signed_in" : "' + authResult['status']['signed_in'] + '"<br />' +
              '  }<br />' +
              '}</code></pre>';
          toggleDiv('signin-button');
        } else {
          document.getElementById('oauth2-results').innerHTML =
              'Empty authResult';
        }
      };
    
      function toggleDiv(id) {
        var div = document.getElementById(id);
        if (div.getAttribute('class') == 'hide') {
          div.setAttribute('class', 'show');
        } else {
          div.setAttribute('class', 'hide');
        }
      }
      </script>
      <script src="https://plus.google.com/js/client:platform.js" type="text/javascript"></script>
    </head>
    <body>
      <div id="signin-button" class="show">
       <div class="g-signin" data-callback="loginFinished"
        data-approvalprompt="force"
        data-clientid="CLIENT_ID"
        data-requestvisibleactions="http://schema.org/CommentAction"
        data-cookiepolicy="single_host_origin"
        >
      </div>
      </div>
    
    </body>
    </html>

答案 1 :(得分:0)

我看到的控制台中的错误是:

  

回调函数名为&#34; signinCallback&#34;找不到

您没有使用此处的功能:数据回调=&#34; signinCallback&#34; 在你的文档中,它就在那里:

&#13;
&#13;
function signinCallback(authResult) {
  if (authResult['status']['signed_in']) {
    // Update the app to reflect a signed in user
    // Hide the sign-in button now that the user is authorized, for example:
    document.getElementById('signinButton').setAttribute('style', 'display: none');
  } else {
    // Update the app to reflect a signed out user
    // Possible error values:
    //   "user_signed_out" - User is signed-out
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatically log in the user
    console.log('Sign-in state: ' + authResult['error']);
  }
}
&#13;
&#13;
&#13;