duanniu4106
2018-01-17 17:26
浏览 42

PHP项目与谷歌API和JavaScript:继承混乱

So I have inherited a few projects at work that user php. I have no experience using php so of course have been struggling to fix a problem we found. At this point I am simply just trying to get the google id of who ever happens to be logged in when they visit the site. Weird thing is that some of the time my code works great and i get the google id, but it only works for some of the accounts we have tried, others just return null. The code below I am just trying to get who is signed in right, but I am so ignorant of how this all works that I can't tell what's wrong.

<!DOCTYPE html>
<html class="no-js" lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Career Opportunities</title>


  <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script src="https://apis.google.com/js/client:platform.js"></script>
  <script type="text/javascript">
    function startUp(onSuccess, onFailure) {
      gapi.client.init({
        apiKey: 'API KEY',
        clientId: 'CLIENTID.apps.googleusercontent.com',
        scope: 'profile',
      }).then(function() {
        var x = gapi.auth2.getAuthInstance();
        console.log("gapi.auth2.getAuthInstance() : " + x);
            console.log("userId is : " + x.currentUser.get().getId());

        gapi.client.load('people', 'v1', function() {
          var request = gapi.client.people.people.get({
            'resourceName': 'people/me',
            'requestMask.includeField': 'person.phone_numbers,person.organizations,person.email_addresses,person.names'
          });
          console.log('request: ' + request);
          request.execute(function(resp) {
            console.log(resp);

          });
        });
      });

    }
    gapi.load('client', startUp);
  </script>


  <script src="js/validation.js" async defer></script>



</head>

<body>



</body>

</html>

This is the error i get when it doesn't like the user for whatever reason. EDIT: This error is in the console. This page does nothing but show me who is logged in via the console.log.

code:401

data:undefined

error:{code: 401, data: undefined, message: "The request does not have valid authentication credentials."}

message:"The request does not have valid authentication credentials."

proto:Object

I have tried so many different things that I assume this code will be a conglomeration of a bunch of different approaches, sorry lol.

EDIT- Added more console.logs - edited above code to reflect this

bobtest.php:101 gapi.auth2.getAuthInstance() : [object Object]
bobtest.php:102 userId is : null
bobtest.php:108 request: [object Object]
cb=gapi.loaded_0:148 GET https://content-people.googleapis.com/v1/people/me?requestMask.includeField=person.phone_numbers&key=401 ()
zu @ cb=gapi.loaded_0:148
n @ cb=gapi.loaded_0:148
Cu @ cb=gapi.loaded_0:149
(anonymous) @ cb=gapi.loaded_0:149
g @ cb=gapi.loaded_0:123
c @ cb=gapi.loaded_0:119
postMessage (async)
(anonymous) @ cb=gapi.loaded_0:122
setTimeout (async)
call @ cb=gapi.loaded_0:122
call @ cb=gapi.loaded_0:134
l @ cb=gapi.loaded_0:195
(anonymous) @ cb=gapi.loaded_0:194
g @ cb=gapi.loaded_0:126
c @ cb=gapi.loaded_0:122
postMessage (async)
(anonymous) @ cb=gapi.loaded_0:119
setTimeout (async)
call @ cb=gapi.loaded_0:119
call @ cb=gapi.loaded_0:131
_.Xj.Rl @ cb=gapi.loaded_0:149
_.Xj.kc @ cb=gapi.loaded_0:149
window.startup @ proxy.html?usegapi=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en.tZDXb_qbHrc.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Frs%:8
(anonymous) @ googleapis.proxy.js?onload=startup:10
ba @ googleapis.proxy.js?onload=startup:3
b @ googleapis.proxy.js?onload=startup:10
Y.r.(anonymous function) @ googleapis.proxy.js?onload=startup:10
Y.x.(anonymous function) @ googleapis.proxy.js?onload=startup:11
(anonymous) @ cb=gapi.loaded_0:1
bobtest.php:110 {code: 401, data: undefined, message: "The request does not have valid authentication credentials.", error: {…}}

EDIT 3 Added more console.logs

----STARTING CLIENT.INIT
bobtest.php:101 ----CLIENT.INIT SUCCESSFUL
bobtest.php:103 gapi.auth2.getAuthInstance() : [object Object]
bobtest.php:104 userId is : null
bobtest.php:110 ----CLIENT.LOAD SUCCESSFUL
bobtest.php:111 request: [object Object]
cb=gapi.loaded_0:148 GET https://content-people.googleapis.com/v1/people/me?requestMask.includeField=person.phone_numbers%2Cperson.organizations%2Cperson.email_addresses%2Cperson.names&key=AIzaSyATLxJElwrDoYaBJtcWCOOP4JI7CUKlXUk 401 ()
zu @ cb=gapi.loaded_0:148
n @ cb=gapi.loaded_0:148
Cu @ cb=gapi.loaded_0:149
(anonymous) @ cb=gapi.loaded_0:149
g @ cb=gapi.loaded_0:123
c @ cb=gapi.loaded_0:119
postMessage (async)
(anonymous) @ cb=gapi.loaded_0:122
setTimeout (async)
call @ cb=gapi.loaded_0:122
call @ cb=gapi.loaded_0:134
l @ cb=gapi.loaded_0:195
(anonymous) @ cb=gapi.loaded_0:194
g @ cb=gapi.loaded_0:126
c @ cb=gapi.loaded_0:122
postMessage (async)
(anonymous) @ cb=gapi.loaded_0:119
setTimeout (async)
call @ cb=gapi.loaded_0:119
call @ cb=gapi.loaded_0:131
_.Xj.Rl @ cb=gapi.loaded_0:149
_.Xj.kc @ cb=gapi.loaded_0:149
window.startup @ proxy.html?usegapi=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en.tZDXb_qbHrc.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAGLTcCOgQjGru3ruZo70XwAerRmnfOfOeA:8
(anonymous) @ googleapis.proxy.js?onload=startup:10
ba @ googleapis.proxy.js?onload=startup:3
b @ googleapis.proxy.js?onload=startup:10
Y.r.(anonymous function) @ googleapis.proxy.js?onload=startup:10
Y.x.(anonymous function) @ googleapis.proxy.js?onload=startup:11
(anonymous) @ cb=gapi.loaded_0:1
bobtest.php:113 ----REQUEST.EXECUTE CALLBACK
bobtest.php:114 {code: 401, data: undefined, message: "The request does not have valid authentication credentials.", error: {…}}

EDIT 4 Added the successful console log

----STARTING CLIENT.INIT

bobtest.php:101 ----CLIENT.INIT SUCCESSFUL
bobtest.php:103 gapi.auth2.getAuthInstance() : [object Object]
bobtest.php:104 userId is : 9999(actually shows id, just removed just in case)
bobtest.php:110 ----CLIENT.LOAD SUCCESSFUL
bobtest.php:111 request: [object Object]
bobtest.php:113 ----REQUEST.EXECUTE CALLBACK
bobtest.php:114 {resourceName: "people/9999999", etag: "%999999=", names: Array(1), emailAddresses: Array(1), result: {…}}
</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxie7339 2018-01-18 14:55
    已采纳

    I didn't really find this answer, my coworker did, but i figured I should post what we ended up getting to work.

    gapi.auth.authorize({
                'client_id': myClientId,
                'scope': 'email',
                'immediate': true
            }, function(authResult) {
                if (authResult['status']['signed_in']) {
                    // Update the app to reflect a signed in user
                    gapi.client.load('plus','v1', function(){
                        var request = gapi.client.plus.people.get({'userId': 'me'});
                        request.execute(function(resp) {
    
                            var userId = '<?php echo $_SESSION["userID"]; ?>';
    
                            if(userId == resp.id) {
                                onSuccess();
                            }
                            else {
                                onFailure();
                            }
                        });
                    });
                }
                else {
                    onFailure();
                }   
            });
    
    点赞 评论
  • dongshan4549 2018-01-17 17:42

    Instead of continuing through comments, I'll make some suggestions here and edit as you edit your question.

    First of all, please copy the output of your console to your question. This will help us see what is happening thus far in the code.

    edit 4:

    I'm not familiar with the google apis you're working with, so my best advice would be test this code and if it returns logged in = true sometimes and false other times, ask a new question on stackoverflow with this simplified code. Tag it with javascript and google api (whatever the main tag is for it). Looking at answers like https://stackoverflow.com/a/33380879/3650835 your code is quite different. So my guess now is that the api calls you make need to be rewritten/aren't being called in the correct order. But give this simplified code a try, does it show signed in sometimes, sometimes not? If so, then we have narrowed down the problem enough for you to ask and probably get a response from someone really familiar with the google apis.

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Career Opportunities</title>
    
      <script src="https://apis.google.com/js/client:platform.js"></script>
      <script type="text/javascript">
      $(document).ready(function() {
        gapi.load('client', startUp);
    
        function startUp(onSuccess, onFailure) {
          gapi.client.init({
            apiKey: 'API KEY',
            clientId: 'CLIENTID.apps.googleusercontent.com',
            scope: 'profile',
          }).then(function() {
            // here we log whether the user is signed in or not, and it changes unexpectedly
            var x = gapi.auth2.getAuthInstance();
            console.log(x.isSignedIn.get());
          });
        }
        });
      </script>
    
    </head>
    <body>
    </body>
    </html>
    
    点赞 评论

相关推荐 更多相似问题