【发布时间】:2015-07-31 07:54:10
【问题描述】:
我正在尝试为“Exact Online”创建一个应用程序,但我在 OAuth 安全身份验证方面遇到了一点问题
https://developers.exactonline.com/#OAuth_Tutorial.html%3FTocPath%3DAuthentication%7C_____2
在发出我的第一个身份验证请求并登录后,我收到了一个代码。 使用此代码,我可以获得一个用于进行 api 调用的令牌。
if (!empty($_GET["code"])){
$code = $_GET["code"];
到目前为止,获取代码有效。但是当我尝试发出新请求(针对令牌)时,我没有收到任何响应数据。 我的代码如下:
$data = array(
'code' => $code,
'redirect_uri' => 'http://****/asdf2.php',
'grant_type' => 'authorization_code',
'client_id' => '******-****-****-******-*****',
'client_secret' => '*********'
);
// Create map with request parameters
// Build Http query using params
$query = http_build_query ($data);
// Create Http context details
$contextData = array (
'method' => 'POST',
'header' => "Connection: close\r\n".
"Content-Length: ".strlen($query)."\r\n",
'content'=> $query );
// Create context resource for our request
$context = stream_context_create (array ( 'http' => $contextData ));
// Read page rendered as result of your POST request
$result = file_get_contents (
'https://start.exactonline.nl/api/oauth2/token', // page url
false,
$context);
// Server response is now stored in $result variable so you can process it
if (!empty($result)){
echo "success";
}else{
echo "no result";
}
}else {
echo "error";
}
$result 总是空的,这可能是什么问题。我已经多次检查了我的 client_id 和 secret。
改成cUrl后还是不行:
$result = get_oauth2_token($code);
// Server response is now stored in $result variable so you can process it
if (!empty($result)){
echo "success";
}else{
echo "no result";
}
}else {
echo "error";
}
/*
Function
*/
function get_oauth2_token($code) {
global $client_id;
global $client_secret;
global $redirect_uri;
$oauth2token_url = "https://start.exactonline.nl/api/oauth2/token";
$clienttoken_post = array(
'code' => $code,
'redirect_uri' => 'http://*****/asdf2.php',
'grant_type' => 'authorization_code',
'client_id' => '{*******}',
'client_secret' => '******'
);
$curl = curl_init($oauth2token_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$json_response = curl_exec($curl);
curl_close($curl);
$authObj = json_decode($json_response);
if (isset($authObj->refresh_token)){
//refresh token only granted on first authorization for offline access
//save to db for future use (db saving not included in example)
global $refreshToken;
$refreshToken = $authObj->refresh_token;
}
$accessToken = $authObj->access_token;
return $accessToken;
}
【问题讨论】:
-
也许改用
cURL? -
已经尝试过了,但也没有用...我会再试一次并发布更新;)
-
我没有安装 CURL.. 现在它可以工作了 :)
标签: php authentication oauth request http-post