dev*_*r10 1 php oauth google-api google-oauth google-api-php-client
在阅读此实施OAuth 2.0身份验证(服务器端)时,我注意到该流程可能适用于创建应用程序的情况,该应用程序允许用户使用其Google凭据登录并随后显示其Google+帖子,Youtube视频等.
我需要的是能够根据谷歌用户的用户名或用户ID获取谷歌数据.我确实有来自Google的client_id,client_secret等 - 而且我愿意按照我的要求发送它们.
第1步似乎没问题.提出类似这样的请求:
https://accounts.google.com/o/oauth2/auth?
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
scope=https://www.googleapis.com/auth/youtube&
response_type=code&
access_type=offline
Run Code Online (Sandbox Code Playgroud)
在这一步之后可能会有什么好处,只需要获取代码,以便我可以验证我的请求(通过Google_Client() - > authenticate($ _ GET ['code']);或类似的),然后将其交换为auth_token.
我使用Facebook API for PHP获得类似于获取Facebook个人资料/页面公共帖子的内容 - 因此与FB流程的登录不同 - 不需要用户同意也不需要用户同意.
您应该使用服务帐户.使用服务帐户访问Google API非常有用.有时您只想访问自己的数据而不是其他用户拥有的数据.在这种情况下,没有理由使用OAuth2并提示用户授予您访问信息的权限,以及您已有权访问的信息.这就是我们使用服务帐户的原因.
可以在此处找到PHP客户端库中的Google服务帐户示例: 示例
您没有确切地说出您要访问的API,我不喜欢仅链接的答案.这是使用Google AnalyticsAPI的基本示例.
<?php
session_start();
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
Run Code Online (Sandbox Code Playgroud)
我有一个教程,可以在这里找到它的代码. Google服务帐户PHP
归档时间: |
|
查看次数: |
3713 次 |
最近记录: |