EDIT (7/8/16): The code below DOES work as it is. I tested it on my desktop PC. I want to leave the code because another developer may find it useful. The problem I have is unrelated -- I seem to be unable to do any HTTP POST with the WAMP server on my laptop, possibly due to firewall or some security software. I am going to look more into it today.
I am following the steps here, "Connect your Application to a User's Health Graph Account": https://runkeeper.com/developer/healthgraph/getting-started
I am stuck at step #3 (Make a POST request to the Health Graph API token endpoint.)
After the code below, $response is blank and $httpResponseCode is 0. I think the CURL POST is well-formed, and I am not sure how to proceed.
This is my redirect page, where the user is directed after step #1, located at "http://localhost/my-site/redirect.php". I only removed the client_id and client_secret.
<!DOCTYPE html>
<body>
<?php
# RunKeeper API
define('client_id', xxxxxxx);
define('client_secret', xxxxxxx);
define('auth_url', 'https://runkeeper.com/apps/authorize');
define('access_token_url', 'https://runkeeper.com/apps/token');
define('redirect_uri','http://localhost/my-site/redirect.php');
define('api_base_url','https://api.runkeeper.com');
if ($_GET['code']) {
$auth_code = $_GET['code'];
$params = http_build_query(array(
'grant_type' => 'authorization_code',
'code' => $auth_code,
'client_id' => client_id,
'client_secret' => client_secret,
'redirect_uri' => redirect_uri
));
$options = array(
CURLOPT_URL => access_token_url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
CURLOPT_RETURNTRANSFER => true
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$responseInfo = curl_getinfo($curl);
$httpResponseCode = $responseInfo['http_code'];
curl_close($curl);
$decoderesponse = json_decode($response);
$access_token = $decoderesponse->access_token;
}
?>
</body>
</html>
You have to pass the $params array as application/x-www-form-urlencoded
.
You can use the below code for urlencoded.
$fields_string="";
foreach($params as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
Then pass to $option array with value as
CURLOPT_POSTFIELDS => $fields_string,