我正在尝试通过他们的oauth2 mechanism连接到deviantart。我确实得到了获取访问令牌的代码,但在尝试通过file_get_contents获取访问令牌时遇到了一些奇怪的404错误。但是,当我复制网址时,我可以根据需要获取访问令牌。有这个......做标题设置?这是获取访问令牌的代码:
function getAccessToken($code) {
$url = "https://www.deviantart.com/oauth2/token";
$data = array();
$data["grant_type"] = "authorization_code";
$data["client_id"] = $this->client_id;
$data["client_secret"] = $this->client_secret;
$data["redirect_uri"] = $this->redirect_uri;
$data["code"] = $code;
return $this->sendToDeviantArt($url, $data);
}
private function sendToDeviantArt($url=null, $data=array()) {
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
答案 0 :(得分:2)
花了我几个小时但显然,deviantart希望设置USER_AGENT。因此,对于记录,这可以完美地工作(请注意user_agent变量)
private function sendToDeviantArt($url=null, $data=array()) {
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
'user_agent' => $_SERVER["HTTP_USER_AGENT"]
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
编辑:对于记录,我们为一些deviantart函数编写了一个包装器并上传了a small library on github.
答案 1 :(得分:0)
这对我来说也是一种痛苦。感谢Jan对用户代理的提醒。只是觉得我会提供一个卷曲替代品,因为我正在使用它。显然可以编辑你的内容,但如果你通过它传递一个deviantART api url,这就行了。
function curl($url) {
// Initiate curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the user agent
curl_setopt($ch,CURLOPT_USERAGENT,$_SERVER["HTTP_USER_AGENT"]);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
return $result;
}
```
获取访问令牌的示例用法:
$json = json_decode(curl("https://www.deviantart.com/oauth2/token?response_type=code&client_id=0&client_secret=0&grant_type=client_credentials"), true);
$json["access_token"];