使用PHP的OAuth类进行Tumblr OAuth

3

好的,这个让我有些困惑。

最近我下载并安装了php的OAuth库,链接在这里:http://us3.php.net/manual/en/book.oauth.php

我用它创建了一些测试代码来尝试连接我的Tumblr帐户并发布一篇文章。

我成功获取了RequestToken和授权。但是当我实际发出请求时,出现了一个错误:

Invalid auth/bad request (got a 404, expected HTTP/1.1 20X or a redirect)

我的请求URL格式正确,是http://api.tumblr.com/v2/blog/account/post。我正在进行POST请求。所以我不确定为什么它返回404。
以下是我的代码:
<?php
$req_url = 'http://www.tumblr.com/oauth/request_token';
$authurl = 'http://www.tumblr.com/oauth/authorize';
$acc_url = 'http://www.tumblr.com/oauth/access_token';

$conskey = '123';
$conssec = '456';

session_start();

// In state=1 the next request should include an oauth_token.
// If it doesn't go back to 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
  $oauth = new OAuth($conskey,$conssec);
  $oauth->enableDebug();
  if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
    $request_token_info = $oauth->getRequestToken($req_url, 'http://www.domain.com/oauth.php');
    $_SESSION['secret'] = $request_token_info['oauth_token_secret'];
    $_SESSION['state'] = 1;

    //Make authorize request with oauth_token
    header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
    exit;
  } else if($_SESSION['state']==1) {

    //Callback code

    $oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
    $access_token_info = $oauth->getAccessToken($acc_url);
    $_SESSION['state'] = 2;
    $_SESSION['token'] = $access_token_info['oauth_token'];
    $_SESSION['secret'] = $access_token_info['oauth_token_secret'];

  } 

  //Make tumblr post request
  $oauth->setToken($_SESSION['token'],$_SESSION['secret']);
  $oauth->fetch("http://api.tumblr.com/v2/blog/account/post", null, OAUTH_HTTP_METHOD_POST, array('type'=>'text', 'body'=>'this is a test'));  //error happens here
  $json = json_decode($oauth->getLastResponse());
  print_r($json);
} catch(OAuthException $E) {
  print_r($E);
}
?>

非常感谢任何提示

1个回答

8
我找到了答案。
问题出在这里:
$oauth->fetch("http://api.tumblr.com/v2/blog/account/post", null, OAUTH_HTTP_METHOD_POST, array('type'=>'text', 'body'=>'this is a test'));  //error happens here

首先,对于账户,我只用了我的博客名字。实际上,在tumblr api中描述的基本主机名需要以'blogname.tumblr.com'的格式而不仅仅是'blogname',否则会返回400错误。

其次,获取参数的顺序不正确。正确的顺序应该是这样的:

string $protected_resource_url [, array $extra_parameters [, string $http_method [, array $http_headers ]]] 

翻译成我的例子就是...

$oauth->fetch("http://api.tumblr.com/v2/blog/blogname.tumblr.com/post", array('type'=>'text', 'body'=>'this is a test'), OAUTH_HTTP_METHOD_POST );

我写了一篇关于如何使这个工作的教程,链接在这里:这里

在进行授权的获取调用之前,请不要忘记调用setToken方法。 - JacopKane

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接