我沒有fitbit帳戶,所以我不能對此進行測試,它可能需要一些調整,但我喜歡的東西開始:
class FitbitConnection{
public function getToken($request_url, $client_id, $client_secret, $code, $redirect_uri){
// base64 encode the client_id and client_secret
$auth = base64_encode("{$client_id}:{$client_secret}");
// urlencode the redirect_url
$redirect_uri = urlencode($redirect_uri);
$request_url .= "?client_id={$client_id}&grant_type=authorization_code&redirect_uri={$redirect_uri}&code={$code}";
// Set the headers
$headers = [
"Authorization: Basic {$auth}",
"Content-Type: application/x-www-form-urlencoded",
];
// Initiate curl session
$ch = curl_init();
// Set headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Options (see: http://php.net/manual/en/function.curl-setopt.php)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_URL, $request_url);
curl_setopt($ch, CURLOPT_POST, 1);
// Execute the curl request and get the response
$response = curl_exec($ch);
// Throw an exception if there was an error with curl
if($response === false){
throw new Exception(curl_error($ch), curl_errno($ch));
}
// Get the body of the response
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$responseBody = substr($response, $header_size);
// Close curl session
curl_close($ch);
// Return response body
return $responseBody;
}
}
你應該注意我註釋掉
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
,如果你在你的本地主機獲得一個SSL證書的問題,你可以把這個選項回來,但你不應該在生產中使用它。
然後你可以只是這樣做:
try{
$fitbitConnection = new FitbitConnection();
$token_response = $fitbitConnection->getToken("https://api.fitbit.com/oauth2/token","22942C","client_secret","1234567890","http://www.example.com");
echo $token_response;
}catch(Exception $e){
// curl error
echo $e->getMessage();
}
的問題是,大多數REST客戶建立關聯數組頭。您可能需要構建自己的curl請求以獲取您的「訪問令牌」,以便您可以使用該特定的頭格式,但是,快速查看API,看起來應該能夠使用類似guzzle的庫所有其他呼叫。 –
我很久沒有使用CURL了,它的使用非常簡單,您是否可以將我指向正確的方向,以及如何使用CURL獲取訪問令牌? –