![](/img/trans.png)
[英]Unknown authorization header error with Buzz API - Using Zend OAuth
[英]Laravel OAuth Authorization Header for FitBit API
我已經為尋找Laravel的一個體面的解決方案而努力了幾天,但無濟於事。
那里有很多庫可能曾經提供過Laravel-FitBit API OAuth集成,但是嘗試了15種以上的庫之后,我都無法使用。
閱讀FitBit文檔,我發現收到令牌后,必須將授權代碼與訪問令牌交換。 為此,您需要發送一個授權標頭,如下所示:
POST https://api.fitbit.com/oauth2/token
Authorization: Basic Y2xpZW50X2lkOmNsaWVudCBzZWNyZXQ=
Content-Type: application/x-www-form-urlencoded
client_id=22942C&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fexample.com%2Fcallback&code=1234567890
我已經嘗試過使用guzzle和其他一些庫來發送請求,但是它們都不支持FitBit所需的格式。
我見過集成了FitBit API的網站,因此必須為此提供解決方案。
如果有人設法集成了FitBit API,請讓我知道我要怎么做。
謝謝。
我沒有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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.