Skip to content

Instantly share code, notes, and snippets.

@valenting
Last active March 16, 2017 01:09
Show Gist options
  • Save valenting/cd9299750d32742f031ef93b9ac9d32f to your computer and use it in GitHub Desktop.
Save valenting/cd9299750d32742f031ef93b9ac9d32f to your computer and use it in GitHub Desktop.
<!--
Copyright (c) 2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
To run this sample, set apiKey to your application's API key and clientId to
your application's OAuth 2.0 client ID. They can be generated at:
https://console.developers.google.com/apis/credentials?project=_
Then, add a JavaScript origin to the client that corresponds to the domain
where you will be running the script. Finally, activate the People API at:
https://console.developers.google.com/apis/library?project=_
-->
<!DOCTYPE html>
<html>
<head>
<title>Say hello using the People API</title>
<meta charset='utf-8' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<p>Say hello using the People API.</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<div id="content"></div>
<script type="text/javascript">
// Enter an API key from the Google API Console:
// https://console.developers.google.com/apis/credentials
var apiKey = 'AIzaSyA12lwIiye4yrMvo7yYtjthmIrJhATbi9w';
// 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",
//"https://people.googleapis.com/v1/people/me/connections"
];
// 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.
var clientId = '63031313402-l3mdar0929ae7eaq7jn6stc54c1eunpc.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 = 'https://www.google.com/m8/feeds';
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;
}, e => console.error(e));
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
makeApiCall();
listConnectionNames();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
// gapi.auth2.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization);
}
function handleAuthorization(authorizationResult) {
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/contacts/default/full?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
//process the response here
console.log(response);
});
}
}
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
// Load the API and make an API call. Display the results on the screen.
function makeApiCall() {
var user = gapi.auth2.getAuthInstance().currentUser.get();
var oauthToken = user.getAuthResponse().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET',
'https://www.google.com/m8/feeds/contacts/default/full?max-results=500&v=3.0&alt=json'+
'&access_token=' + encodeURIComponent(oauthToken));
// xhr.setRequestHeader('Authorization',
// 'Bearer ' + oauthToken.access_token);
xhr.send();
gapi.client.people.people.get({
resourceName: 'people/me'
}).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);
}, e => console.error(e));
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the display name if available for 10 connections.
*/
function listConnectionNames() {
gapi.client.people.people.connections.list({
'resourceName': 'people/me',
// 'pageSize': 10,
}).then(function(response) {
var connections = response.result.connections;
appendPre('Connections:');
if (connections.length > 0) {
for (i = 0; i < connections.length; i++) {
var person = connections[i];
console.log(person);
// if (person.names && person.names.length > 0) {
// console.log(person.names[0].displayName);
// appendPre(person.names[0].displayName);
// } else {
// appendPre("No display name found for connection.");
// }
}
} else {
appendPre('No upcoming events found.');
}
}, e => console.error(e));
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment