· 5 years ago · May 06, 2020, 04:18 PM
1<script type="text/javascript">
2 // Enter an API key from the Google API Console:
3 // https://console.developers.google.com/apis/credentials
4 var apiKey = 'AIzaSyBEAhjj9bCdYAdMSAQuSL0GD3V600fb_eI';
5
6 // Enter the API Discovery Docs that describes the APIs you want to
7 // access. In this example, we are accessing the People API, so we load
8 // Discovery Doc found here: https://developers.google.com/people/api/rest/
9 var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];
10
11 // Enter a client ID for a web application from the Google API Console:
12 // https://console.developers.google.com/apis/credentials?project=_
13 // In your API Console project, add a JavaScript origin that corresponds
14 // to the domain where you will be running the script.
15 var clientId = '878658374374-k5sgmoil29rf2mpk1h1ipga5uhv7oftv.apps.googleusercontent.com';
16
17 // Enter one or more authorization scopes. Refer to the documentation for
18 // the API or https://developers.google.com/people/v1/how-tos/authorizing
19 // for details.
20 var scopes = 'profile';
21
22 var authorizeButton = document.getElementById('authorize-button');
23 var signoutButton = document.getElementById('signout-button');
24
25 function handleClientLoad() {
26 // Load the API client and auth2 library
27 gapi.load('client:auth2', initClient);
28 }
29
30 function initClient() {
31 gapi.client.init({
32 apiKey: apiKey,
33 discoveryDocs: discoveryDocs,
34 clientId: clientId,
35 scope: scopes
36 }).then(function () {
37 // Listen for sign-in state changes.
38 gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
39
40 // Handle the initial sign-in state.
41 updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
42
43 authorizeButton.onclick = handleAuthClick;
44 signoutButton.onclick = handleSignoutClick;
45 });
46 }
47
48 function updateSigninStatus(isSignedIn) {
49 if (isSignedIn) {
50 authorizeButton.style.display = 'none';
51 signoutButton.style.display = 'block';
52 makeApiCall();
53 } else {
54 authorizeButton.style.display = 'block';
55 signoutButton.style.display = 'none';
56 }
57 }
58
59 function handleAuthClick(event) {
60 gapi.auth2.getAuthInstance().signIn();
61 }
62
63 function handleSignoutClick(event) {
64 gapi.auth2.getAuthInstance().signOut();
65 }
66
67 // Load the API and make an API call. Display the results on the screen.
68 function makeApiCall() {
69 gapi.client.people.people.get({
70 'resourceName': 'people/me',
71 'requestMask.includeField': 'person.names'
72 }).then(function(resp) {
73 var p = document.createElement('p');
74 var name = resp.result.names[0].givenName;
75 p.appendChild(document.createTextNode('Hello, '+name+'!'));
76 document.getElementById('content').appendChild(p);
77 });
78 }
79 </script>