Просто проверьте пользовательскую организацию Google в JavaScript, а затем отобразите содержимое? - PullRequest
0 голосов
/ 17 февраля 2019

Я пытаюсь выяснить, как использовать службу API Google, и у меня есть клиент и ключ API для Google OAuth.В частности, хотя я хочу проверить организацию пользователя, а затем повторить некоторую информацию для них.Я понимаю, что эта информация будет отображаться с помощью простого CTRL-SHIFT-I или CTRL-U, но сейчас это не имеет значения для меня.Заранее спасибо за вашу помощь (JavaScript, потому что я хочу попробовать разместить ее на страницах GitHub)!

Вот пример Google, который я пробовал, и я просто получаю ошибку 400 (ключи клиента и API были удалены).

// Enter an API key from the Google API Console:
//   https://console.developers.google.com/apis/credentials
var apiKey = 'AIzaSyDyyNLwHpVqy88tRamPt1NbyVWFzYkLuhA';
// Enter the API Discovery Docs that describes the APIs you want to
// access. In this example, we are accessing the People API, so we load
// Discovery Doc found here: https://developers.google.com/people/api/rest/
var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];
// Enter a client ID for a web application from the Google API Console:
//   https://console.developers.google.com/apis/credentials?project=_
// In your API Console project, add a JavaScript origin that corresponds
//   to the domain where you will be running the script .apps.googleusercontent.com.
var clientId = '873243932753-jfebiqi1ja0b9a2jiqdiirb8vtjlk4n9.apps.googleusercontent.com.apps.googleusercontent.com';
// Enter one or more authorization scopes. Refer to the documentation for
// the API or https://developers.google.com/people/v1/how-tos/authorizing
// for details.
var scopes = 'profile';
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');

function handleClientLoad() {
  // Load the API client and auth2 library
  gapi.load('client:auth2', initClient);
}

function initClient() {
  gapi.client.init({
    apiKey: apiKey,
    discoveryDocs: discoveryDocs,
    clientId: clientId,
    scope: scopes
  }).then(function() {
    // Listen for sign-in state changes.
    gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
    // Handle the initial sign-in state.
    updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
    authorizeButton.onclick = handleAuthClick;
    signoutButton.onclick = handleSignoutClick;
  });
}

function updateSigninStatus(isSignedIn) {
  if (isSignedIn) {
    authorizeButton.style.display = 'none';
    signoutButton.style.display = 'block';
    makeApiCall();
  } else {
    authorizeButton.style.display = 'block';
    signoutButton.style.display = 'none';
  }
}

function handleAuthClick(event) {
  gapi.auth2.getAuthInstance().signIn();
}

function handleSignoutClick(event) {
  gapi.auth2.getAuthInstance().signOut();
}
// Load the API and make an API call.  Display the results on the screen.
function makeApiCall() {
  gapi.client.people.people.get({
    'resourceName': 'people/me',
    'requestMask.includeField': 'person.names'
  }).then(function(resp) {
    var p = document.createElement('p');
    var name = resp.result.names[0].givenName;
    p.appendChild(document.createTextNode('Hello, ' + name + '!'));
    document.getElementById('content').appendChild(p);
  });
}
<p>Say hello using the People API.</p>

<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button">Authorize</button>
<button id="signout-button">Sign Out</button>

<div id="content"></div>

<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

Редактировать: Я обнаружил, что это нужно сделать с помощью Admin SDK .Хотя все еще немного запутался, как это сделать.

1 Ответ

0 голосов
/ 13 июня 2019

Как вы упомянули, это необходимо сделать с помощью Admin SDK API .в разделе users> get вы можете попробовать этот API, и он предоставит вам пример того, как использовать его на JS.

function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/admin.directory.user https://www.googleapis.com/auth/admin.directory.user.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("YOUR_API_KEY");
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/admin/directory_v1/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.directory.users.get({
      "userKey": "<user email address>"
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "YOUR_CLIENT_ID"});
  });`

Также я рекомендую вам воспользоваться Quickstart , чтобы получить более подробную информацию об использовании API Google.

...