Maybe someone can point out what I may be doing wrong here. I'm messing around with the Google API and OAuth so I can register users through google to my application. I found the PHP they provide pretty cumbersome so I decided to get more practice performing https requests and such. I've had some success so far, but the final step in getting a token to exchange for user information requires a POST method. Simply redirecting the browser, copying the final url with a GET method returns an error. I'm about to start digging around in the cURL extension next, but maybe someone can spot whats wrong with this code?
$url = "https://accounts.google.com/o/oauth2/token";
$fields = array(
'code' => $_GET['code'],
'client_id' => $google['clientID'],
'client_secret' => $google['clientSecret'],
'redirect_uri' => "http://www.qwiku.com/scripts/php/google/reg_response.php",
'grant_type' => "authorization_code"
);
$data = http_build_query($fields);
echo $data."<br />";
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $data
)
));
$result = file_get_contents($url, false, $context);
var_dump($result);
The dump of result is false. You can see the google documentation here but I'm 99% sure the data is formulated correctly. http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#formingtheurl
UPDATE
I'm now using curl and it appears to be working. Only problem is google is returning an error of "invalid_grant." Not sure why as it's set to exactly what they specify.
$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
Update 2
I refreshed the whole process as I was just refreshing the redirect and bingo, it's working. Code must have expired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With