Reputation: 11
I am building an app that involved authorization so that I can retrieve data from a fitbit user. I have successfully gone through the steps (Link:https://dev.fitbit.com/build/reference/web-api/developer-guide/authorization/) up until Step 4 - Exchange the Authorization Code for the Access and Refresh Tokens.
I am getting the code https://localhost/DailyAppleFit/?code={CODE_IM_RETRIEVING}#=
But do not know how to display the users Id or just something that indicates the software now has access and the user is logged in.
I have checked on postman and all of the information being passed through is correct.
After I tried the authorization code from the url, how do I use it to make a post request with headers? Once I go through that step, it returns a json file I can use to retrieve the access token.
I want to stay in the php file.
<?php
session_start();
function http($url, $params=false) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($params)
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
return json_decode(curl_exec($ch));
}
$client_id = 'CLIENT_ID_VALUE';
$client_secret = 'CLIENT_SECRET_VALUE';
$redirect_uri = 'https://localhost/DailyAppleFit/';
$metadata_url = 'https://www.fitbit.com/oauth2/authorize';
$metadata_UrlRefreshToken = 'https://api.fitbit.com/oauth2/token';
$metadata = http($metadata_url);
$auth = base64_encode("{$client_id}:{$client_secret}");
if(isset($_SESSION['user_id'])) {
echo '<p>Logged in as</p>';
echo '<p>' . $_SESSION['user_id'] . '</p>';
echo '<p><a href="/?logout">Log Out</a></p>';
die();
}
if(isset($_GET['logout'])) {
unset($_SESSION['user_id']);
header('Location: /');
die();
}
if(!isset($_GET['user_id'])) {
$_SESSION['code_verifier'] = '01234567890123456789012345678901234567890123456789';
$code_challenge = base64_urlencode(hash('sha256', $_SESSION['code_verifier'], true));
$authorize_url = 'https://www.fitbit.com/oauth2/authorize?'
.http_build_query([
'client_id' => $client_id,
'response_type' => 'code',
'code_challenge' => $code_challenge,
'code_challenge_method' => 'S256',
'scope' => 'activity heartrate location nutrition oxygen_saturation profile respiratory_rate settings sleep social temperature weight',
], null, '&', PHP_QUERY_RFC3986);
echo '<p>Not logged in</p>';
echo '<p><a href="'.$authorize_url.'">Log In</a></p>';
} else {
if(isset($_GET['error'])) {
die('Authorization server returned an error: '.htmlspecialchars($_GET['error']));
}
$response = http($redirect_uri, [
'code' =>$_GET['code'],
]);
$token = http($metadata, [
'client_id' => $client_id,
'client_secret' => $client_secret,
'token'=>$response
]);
if(!isset($response->access_token)) {
die('Error fetching access token');
}
$userinfo = http($metadata->userinfo_endpoint, [
'access_token' => $response->access_token,
]);
}
function base64_urlencode($string) {
return rtrim(strtr(base64_encode($string), '+/', '-_'), '=');
}
Upvotes: 1
Views: 442