2014-12-24 105 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調用,但在此之前,您必須指定要訪問的功能的範圍。