2014-12-24 55 views
2

我在google api url中有一段代码,现在我该如何将它转换为访问令牌? 我用卷曲,但它不工作。 任何连击和简单的想法,我必须在codeigniter中使用。 和那个authorization_code是什么?Google api + php + codeigniter + curl

<?php 

$field='code='.$_REQUEST['code'].'&client_id=clirnt-id 
&client_secret=client-secret 
&redirect_uri=http: // localost/googleapi/curlreq.php 
&grant_type=authorization_code'; 



$ch = curl_init(); 

curl_setopt($ch, CURLOPT_URL,"https://www.googleapis.com/oauth2/v3/token"); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS,$field); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/x-www-form-urlencoded')); 

$server_output = curl_exec ($ch); 

echo 'end'; 

echo '<br/>'; 
//echo $server_output; 
print_r($server_output); 

curl_close ($ch); 
?> 
+0

尝试https://github.com/google/google-api-php-client –

+0

我通过Hybrid Auth获得此信息。它给所有的apis雅虎,fb,g +,twitter everthing ..它真的很好 –

回答

1

首先你需要获取访问令牌。

require_once 'google-api-php-client/autoload.php'; 

$client = new Google_Client(); 
$client->setApplicationName("Client_Library_Examples"); 
$client->setDeveloperKey("YOUR_PUBLIC_API_ACCESS_KEY"); 
$client->setScopes(array('https://www.googleapis.com/auth/plus.me')); 
$client->setClientId('CLIENT_ID'); 
$client->setClientSecret('CLIENT_SECRET'); 
$client->setApprovalPrompt('force'); 
$client->setAccessType('offline'); 
$client->setRedirectUri('http://yourdomain.com/oauthCallback'); 

$access_token = ''; 

if (!isset($_GET['code'])) { 

    redirect($client->createAuthUrl()); 

} else { 

    // Exchanging code with access token 
    $client->authenticate(urldecode($_GET['code'])); // Exchange code for auth 

    $access_token = $client->getAccessToken(); // Get access token 

    // Send your curl request to any api with access token here and get data 

} 

这是一般流程。你应该先看看implementing OAuth here in official documentation

访问令牌后,您可以对任何api进行REST调用,但在此之前,您必须指定要访问的功能的范围。