google+api使用_如何使用Google JS API获取您的Google+个人资料信息和朋友的活动

google+api使用

How to get your Google+ profile info and friend's activity using the Google JS API
How to get your Google+ profile info and friend's activity using the Google JS API

How to get your Google+ profile info and friend’s activity using the Google JS API Today I would like to tell you about several interesting things. It is Google JavaScript API v3 and new generation of jQuery Templates – JsRender. I will show you how to setup authentication with Google (OAuth 2.0) and perform some API requests. One of them is obtaining info of logged-in member, and second one is obtaining an activity feed of your friends. Another side of our tutorial is jQuery templating. I will show you how to render HTML content using templates.

如何使用Google JS API获取您的Google+个人资料信息和朋友的活动今天,我想告诉您一些有趣的事情。 它是Google JavaScript API v3和新一代的jQuery模板– JsRender。 我将向您展示如何使用Google(OAuth 2.0)设置身份验证并执行一些API请求。 其中之一是获取登录会员的信息,第二个是获取朋友的活动提要。 本教程的另一面是jQuery模板。 我将向您展示如何使用模板呈现HTML内容。

I hope that you’ve already created your own API project in the Google APIs Console as I’ve described recently in my Google API – Get contact list tutorial. If you haven’t – please do it and create your own Google API project. Next step is enabling of ‘Google+ API’, so, please open your Google API console and then select ‘Services’. Here we should Enable ‘Google+ API’:

希望您已经在Google API控制台中创建了自己的API项目,正如我最近在“ Google API-获取联系人列表”教程中所述。 如果还没有,请做,并创建自己的Google API项目。 下一步是启用“ Google+ API”,因此,请打开您的Google API控制台,然后选择“服务”。 在这里,我们应该启用“ Google+ API”:

Google+ API - step 1

Google+ API-步骤1

After, please open ‘API Access’ and copy your ‘Client ID’ and ‘API key’ (at the end) keys:

之后,请打开“ API访问权限”并复制“客户端ID”和“ API密钥”(最后)密钥:

Google+ API - step 2

Google+ API-步骤2

Now we are ready to start coding !

现在我们准备开始编码!

现场演示

[sociallocker]

[社交储物柜]

打包下载

[/sociallocker]

[/ sociallocker]

步骤1. HTML (Step 1. HTML)

Right now create an empty index.html file and put next code:

现在,创建一个空的index.html文件并放入下一个代码:

index.html (index.html)

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="utf-8" />
    <title>How to get your Google+ profile info and friend's activity using the Google JS API | Script Tutorials</title>
    <link href="css/main.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script>
        google.load("jquery", "1.7.1");
    </script>
    <script type="text/javascript" src="js/jsrender.js"></script>
    <!-- define template for our units -->
    <script id="gplusTemplate" type="text/x-jsrender">
        <div id="{{>id}}" class="gp">
            <img src="{{:actor.image.url}}" />
            <div>
                <p><a href="{{:actor.url}}" target="_blank">{{:actor.displayName}}</a><span>{{:published}}</span></p>
                <p><a href="{{:url}}" target="_blank">{{:title}}</a></p>
                <p>{{:object.content}}</p>
            </div>
        </div>
    </script>
</head>
<body>
    <header>
        <h2>How to get your Google+ profile info and friend's activity using the Google JS API</h2>
        <a href="https://www.script-tutorials.com/google-javascript-api-practice-with-jquery-templates/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
    </header>
    <img src="google-plus.jpg" class="google" alt="google plus" />
    <center>
        <button id="login" style="visibility: hidden">Authorize</button>
        <div id="author"></div>
        <div id="actList"></div>
    </center>
    <script type="text/javascript">
        // Your client ID
        var clientId = 'YOUR_CLIENT_ID_KEY';
        // Your API key
        var apiKey = 'YOUR_API_KEY';
        // The authorization scope
        var scopes = 'https://www.googleapis.com/auth/plus.me';
        // onliad initialization
        function onloadInitialization() {
            // set our own api key
            gapi.client.setApiKey(apiKey);
            // and checkAuth in 1 ms
            window.setTimeout(checkAuth, 1);
        }
        // check authorization
        function checkAuth() {
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                immediate: true
            }, handleAuthResult);
        }
        // handle authorization result
        function handleAuthResult(authResult) {
            var authorizeButton = document.getElementById('login');
            if (authResult && ! authResult.error) {
                authorizeButton.style.visibility = 'hidden';
                makeGoogleApiCalls();
            } else {
                authorizeButton.style.visibility = '';
                authorizeButton.onclick = handleAuthClick;
            }
        }
        // handle onclick event of Login button
        function handleAuthClick(event) {
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                immediate: false
            }, handleAuthResult);
            return false;
        }
        // make Google API calls: obtain logged-in member info and activity of friends
        function makeGoogleApiCalls() {
            gapi.client.load('plus', 'v1', function() {
                // Request1: obtain logged-in member info
                var request = gapi.client.plus.people.get({
                    'userId': 'me'
                });
                request.execute(function(aInfo) {
                    // prepare author info array for rendering
                    var authorInfo = [
                        {
                            'id': aInfo.id,
                            'actor': {'image': {'url': aInfo.image.url}, 'url': aInfo.url, 'displayName': aInfo.displayName},
                            'published': '',
                            'url': aInfo.url,
                            'title': 'My page at G+',
                            'object': {'content': ''}
                        }
                    ];
                    // and render it using 'gplusTemplate' template
                    $('#author').html(
                        $('#gplusTemplate').render(authorInfo)
                    );
                });
                // Request2: obtain friend's activity feed
                var restRequest = gapi.client.request({
                    'path': '/plus/v1/activities',
                    'params': {'query': 'Google+', 'orderBy': 'best'}
                });
                restRequest.execute(function(activityInfo) {
                    // render activity items using 'gplusTemplate' template
                    $('#actList').html(
                        $('#gplusTemplate').render(activityInfo.items)
                    );
                });
            });
        }
    </script>
    <script src="https://apis.google.com/js/client.js?onload=onloadInitialization"></script>
</body>
</html>

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="utf-8" />
    <title>How to get your Google+ profile info and friend's activity using the Google JS API | Script Tutorials</title>
    <link href="css/main.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script>
        google.load("jquery", "1.7.1");
    </script>
    <script type="text/javascript" src="js/jsrender.js"></script>
    <!-- define template for our units -->
    <script id="gplusTemplate" type="text/x-jsrender">
        <div id="{{>id}}" class="gp">
            <img src="{{:actor.image.url}}" />
            <div>
                <p><a href="{{:actor.url}}" target="_blank">{{:actor.displayName}}</a><span>{{:published}}</span></p>
                <p><a href="{{:url}}" target="_blank">{{:title}}</a></p>
                <p>{{:object.content}}</p>
            </div>
        </div>
    </script>
</head>
<body>
    <header>
        <h2>How to get your Google+ profile info and friend's activity using the Google JS API</h2>
        <a href="https://www.script-tutorials.com/google-javascript-api-practice-with-jquery-templates/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
    </header>
    <img src="google-plus.jpg" class="google" alt="google plus" />
    <center>
        <button id="login" style="visibility: hidden">Authorize</button>
        <div id="author"></div>
        <div id="actList"></div>
    </center>
    <script type="text/javascript">
        // Your client ID
        var clientId = 'YOUR_CLIENT_ID_KEY';
        // Your API key
        var apiKey = 'YOUR_API_KEY';
        // The authorization scope
        var scopes = 'https://www.googleapis.com/auth/plus.me';
        // onliad initialization
        function onloadInitialization() {
            // set our own api key
            gapi.client.setApiKey(apiKey);
            // and checkAuth in 1 ms
            window.setTimeout(checkAuth, 1);
        }
        // check authorization
        function checkAuth() {
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                immediate: true
            }, handleAuthResult);
        }
        // handle authorization result
        function handleAuthResult(authResult) {
            var authorizeButton = document.getElementById('login');
            if (authResult && ! authResult.error) {
                authorizeButton.style.visibility = 'hidden';
                makeGoogleApiCalls();
            } else {
                authorizeButton.style.visibility = '';
                authorizeButton.onclick = handleAuthClick;
            }
        }
        // handle onclick event of Login button
        function handleAuthClick(event) {
            gapi.auth.authorize({
                client_id: clientId,
                scope: scopes,
                immediate: false
            }, handleAuthResult);
            return false;
        }
        // make Google API calls: obtain logged-in member info and activity of friends
        function makeGoogleApiCalls() {
            gapi.client.load('plus', 'v1', function() {
                // Request1: obtain logged-in member info
                var request = gapi.client.plus.people.get({
                    'userId': 'me'
                });
                request.execute(function(aInfo) {
                    // prepare author info array for rendering
                    var authorInfo = [
                        {
                            'id': aInfo.id,
                            'actor': {'image': {'url': aInfo.image.url}, 'url': aInfo.url, 'displayName': aInfo.displayName},
                            'published': '',
                            'url': aInfo.url,
                            'title': 'My page at G+',
                            'object': {'content': ''}
                        }
                    ];
                    // and render it using 'gplusTemplate' template
                    $('#author').html(
                        $('#gplusTemplate').render(authorInfo)
                    );
                });
                // Request2: obtain friend's activity feed
                var restRequest = gapi.client.request({
                    'path': '/plus/v1/activities',
                    'params': {'query': 'Google+', 'orderBy': 'best'}
                });
                restRequest.execute(function(activityInfo) {
                    // render activity items using 'gplusTemplate' template
                    $('#actList').html(
                        $('#gplusTemplate').render(activityInfo.items)
                    );
                });
            });
        }
    </script>
    <script src="https://apis.google.com/js/client.js?onload=onloadInitialization"></script>
</body>
</html>

In the header of our file we load jQuery library, jsrender.js (JsRender library) and define custom HTML template (gplusTemplate). We will use this template to generate G+ friend’s activity list.

在文件的标题中,我们加载jQuery库jsrender.js(JsRender库)并定义自定义HTML模板(gplusTemplate)。 我们将使用此模板生成G +朋友的活动列表。

In the body of our page we have ‘Authorize’ button and 2 containers (to display our own info and activity list:

在页面的主体中,我们具有“授权”按钮和2个容器(用于显示我们自己的信息和活动列表:


<button id="login" style="visibility: hidden">Authorize</button>
<div id="author"></div>
<div id="actList"></div>

<button id="login" style="visibility: hidden">Authorize</button>
<div id="author"></div>
<div id="actList"></div>

Now we should understand our JS code. Important note – please put your own ClientID and API keys in the beginning of this JavaScript code. Several functions in the middle are for handling with Login button (authorization). When the page has loaded we set API key and set timeout to check authorization. If we are logged in – we hide Login button. Otherwise – display it and add ‘onclick’ handler (to evoke authorization). The standard authorize() method always shows a popup window, which can be a little annoying if you are just trying to refresh an OAuth 2.0 token. Google’s OAuth 2.0 implementation also supports “immediate” mode, which refreshes a token without a popup window.

现在我们应该了解我们的JS代码。 重要说明–请在此JavaScript代码的开头放置您自己的ClientID和API密钥。 中间的几个功能用于使用“登录”按钮(授权)进行处理。 页面加载后,我们设置API密钥并设置超时以检查授权。 如果我们已登录–我们将隐藏“登录”按钮。 否则–显示它并添加“ onclick”处理程序(以唤起授权)。 标准的authorize()方法始终显示一个弹出窗口,如果您只是尝试刷新OAuth 2.0令牌,可能会有些烦人。 Google的OAuth 2.0实现还支持“立即”模式,该模式无需刷新窗口即可刷新令牌。

Well, when we are logged in – we can make Google API calls. We are going to make 2 api requests: get member info and get friends activity. This is very easy:

好吧,当我们登录时–我们可以进行Google API调用。 我们将提出2个api请求:获取会员信息并获得好友活动。 这很简单:

Well, when we are logged in – we can make Google API calls. We are going to make 2 api requests: get member info and get friends activity. This is very easy:

好吧,当我们登录时–我们可以进行Google API调用。 我们将提出2个api请求:获取会员信息并获得好友活动。 这很简单:


// Request1: obtain logged-in member info
var request = gapi.client.plus.people.get({
    'userId': 'me'
});
request.execute(function(aInfo) {
    // do something else
});
// Request2: obtain friend's activity feed
var restRequest = gapi.client.request({
    'path': '/plus/v1/activities',
    'params': {'query': 'Google+', 'orderBy': 'best'}
});
restRequest.execute(function(activityInfo) {
    // do something else
});

// Request1: obtain logged-in member info
var request = gapi.client.plus.people.get({
    'userId': 'me'
});
request.execute(function(aInfo) {
    // do something else
});
// Request2: obtain friend's activity feed
var restRequest = gapi.client.request({
    'path': '/plus/v1/activities',
    'params': {'query': 'Google+', 'orderBy': 'best'}
});
restRequest.execute(function(activityInfo) {
    // do something else
});

Next part is very interesting too. As you can see – as usual we get response in JSON format. Thus I have a question – how to use data from JSON response in order to generate result HTML code? Some people can offer ‘for’ method (to pass through all the elements of the JSON array), but I would like you to suggest a new method – templates. It has one important advantage – speed. The result speed can be very high especially during generation of big lists. Look at this code and you will understand that this is very easy to render html content using JsRender library:

下一部分也非常有趣。 如您所见-与往常一样,我们以JSON格式获取响应。 因此,我有一个问题–如何使用JSON响应中的数据生成结果HTML代码? 有人可以提供“ for”方法(以传递JSON数组的所有元素),但我希望您提出一个新方法-模板。 它具有一个重要的优势-速度。 结果速度可能非常高,尤其是在生成大列表的过程中。 查看下面的代码,您将了解,使用JsRender库很容易呈现html内容:


var restRequest = gapi.client.request({
    'path': '/plus/v1/activities',
    'params': {'query': 'Google+', 'orderBy': 'best'}
});
restRequest.execute(function(activityInfo) {
    // render activity items using 'gplusTemplate' template
    $('#actList').html(
        $('#gplusTemplate').render(activityInfo.items)
    );
});

var restRequest = gapi.client.request({
    'path': '/plus/v1/activities',
    'params': {'query': 'Google+', 'orderBy': 'best'}
});
restRequest.execute(function(activityInfo) {
    // render activity items using 'gplusTemplate' template
    $('#actList').html(
        $('#gplusTemplate').render(activityInfo.items)
    );
});

You can download JsRender jQuery library here. JsRender templates Syntax:

您可以在此处下载JsRender jQuery库。 JsRender模板语法:

DescriptionExampleOutput
Value of firstName property of the data item with no encoding{{:firstName}}Madelyn
Simple object path to nested property, with no encoding{{:movie.releaseYear}}1987
Simple comparison{{:movie.releaseYear < 2000}}true
Value with no encoding{{:movie.name}}Star Wars IV: Return of the Jedi
HTML-encoded value{{>movie.name}}Star Wars: Episode VI: <span style=’color:purple;font-style: italic;’>Return of the Jedi</span>
HTML-encoded value{{html:movie.name}}Star Wars: Episode VI: <span style=’color:purple;font-style: italic;’>Return of the Jedi</span>
描述 输出量
数据项的firstName属性值,无编码 {{:名字}} 马德琳
嵌套属性的简单对象路径,无需编码 {{:movie.releaseYear}} 1987年
比较简单 {{:movie.releaseYear <2000}} 真正
没有编码的值 {{:movie.name}} 星球大战四:绝地归来
HTML编码的值 {{> movie.name}} 星球大战:第六集:<span style ='color:purple; font-style:italic;'>绝地归来</ span>
HTML编码的值 {{html:movie.name}} 星球大战:第六集:<span style ='color:purple; font-style:italic;'>绝地归来</ span>
现场演示

结论 (Conclusion)

If you have any suggestions about further ideas for articles – you are welcome to share them with us. Good luck in your work!

如果您对文章的进一步建议有任何建议,欢迎与我们分享。 祝您工作顺利!

翻译自: https://www.script-tutorials.com/google-javascript-api-practice-with-jquery-templates/

google+api使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值