[英]Use OAuth 1 Class in Symfony2
嗨,我想將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中實現該類需要采取哪些步驟?
1)創建一個目錄,例如Project / src / OAuth
2)將類放在該目錄內的單獨文件中。
3)添加namespace OAuth;
在每個OAuth類的開頭。
4)在Exception類中添加一個反斜杠(或添加use Exception;
):
class OAuthException extends \Exception
5)避免在類名中使用下划線( Laravel 4中的Laravel-Oauth2問題 , 在名稱空間和類名中使用下划線 ):
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
在Symfony 2中,我可以推薦一個支持OAuth 1和2的第三方捆綁軟件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.