在Symfony2中使用OAuth 1类

时间:2013-09-16 14:52:20

标签: php symfony oauth

您好我想将Yahoo BOSS API与Symfony2集成,但Yahoo建议的OAuth代码类似乎不适用于现代PHP框架。

http://oauth.googlecode.com/svn/code/php/OAuth.php

/* Generic exception class
 */
class OAuthException extends Exception {
  // pass
}

class OAuthConsumer {
  public $key;
  public $secret;

  function __construct($key, $secret, $callback_url=NULL) {
    $this->key = $key;
    $this->secret = $secret;
    $this->callback_url = $callback_url;
  }

  function __toString() {
    return "OAuthConsumer[key=$this->key,secret=$this->secret]";
  }
} [...]

http://developer.yahoo.com/boss/search/boss_api_guide/codeexamples.html#oauth_php

我认为OAuth类存在名称空间问题,在Symfony2中需要采取哪些步骤来实现此类?

2 个答案:

答案 0 :(得分:5)

1)创建一个类似Project / src / OAuth

的目录

2)将类放在该目录中的单独文件中。

3)在每个OAuth类的开头添加namespace OAuth;

4)向Exception类添加反斜杠(或添加use Exception;):

class OAuthException extends \Exception

5)避免在班级名称中使用下划线(Laravel-Oauth2 Issue in Laravel 4Underscores in Namespaces and Class Names):

abstract class OAuthSignatureMethodRSASHA1 extends OAuthSignatureMethod

class OAuthSignatureMethodPLAINTEXT extends OAuthSignatureMethod

class OAuthSignatureMethodHMACSHA1 extends OAuthSignatureMethod

6)修复OAuthUtil中的array_map调用:

return array_map(array('OAuth\OAuthUtil', 'urlencode_rfc3986'), $input);

7)最后使用它:

<?php

namespace My\PlaygroundBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use OAuth\OAuthConsumer;
use OAuth\OAuthRequest;
use OAuth\OAuthSignatureMethodHMACSHA1;
use OAuth\OAuthUtil;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     * @Template()
     */
    public function indexAction()
    {
        $cc_key  = "your consumer key here";
        $cc_secret = "your consumer secret here";
        $url = "http://yboss.yahooapis.com/ysearch/news,web,images";
        $args = array();
        $args["q"] = "yahoo";
        $args["format"] = "json";

        $consumer = new OAuthConsumer($cc_key, $cc_secret);
        $request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
        $request->sign_request(new OAuthSignatureMethodHMACSHA1(), $consumer, NULL);
        $url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
        $ch = curl_init();
        $headers = array($request->to_header());
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $rsp = curl_exec($ch);
        $results = json_decode($rsp);

        return array(
            'results' => $results
        );
    }
}

所以这些是我遵循的步骤并且有效;你可以从这里获取课程:https://github.com/coma/OAuthSOSample

答案 1 :(得分:4)

在Symfony 2中,我可以推荐支持OAuth 1&amp;的第三方软件包。 2。

看看:https://github.com/hwi/HWIOAuthBundle