2013-04-03 32 views
1

我正在寫一個與Twitter API集成的基本Web應用程序。我使用jQuery和AJAX請求身份驗證令牌Twitter require,但我違反了異步跨站點請求策略或任何它。JSONP郵政代理

我會使用JSONP,但Twitter API需要POST。我讀過我應該使用一個itermediate代理。我不知道這涉及到什麼,也找不到任何資源?我可以用PHP編寫。

任何人都可以解釋什麼是代理頁面?

UPDATE

繼閱讀接受的答案下面我寫了一個PHP代理腳本,這是我想出了和得到了工作:

<?php 

    class proxy { 

     public $serviceURL; 
     public $postString; 
     public $headers; 
     public $response; 

     public function __construct($url) { 
      $this->serviceURL = $url; 
      $this->postStringify($_POST); 
     } 

     private function postStringify($postArray) { 
      $ps = ''; 
      foreach($postArray as $key => $value) { 
       $ps .= $key . '=' . $value . '&'; 
      } 
      rtrim($ps, '&'); 
      $this->postString = $ps;  
     } 

     private function isCurlInstalled() { 
      return (in_array('curl', get_loaded_extensions())) ? true : false; 
     } 

     public function makeRequest() { 
      if ($this->isCurlInstalled()) { 
       $ch = curl_init(); 
       curl_setopt($ch, CURLOPT_URL, $this->serviceURL); 
       curl_setopt($ch, CURLOPT_POST, 1); 
       curl_setopt($ch, CURLOPT_TIMEOUT, 10);    
       curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postString); 
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
       curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers); 
       $this->response = curl_exec($ch); 
       if ($this->response === false) $this->response = curl_error($ch); 
       curl_close($ch); 
      } else { 
       $this->response = 'Need to install Curl!'; 
      } 

      return $this->response; 

     } 

     public function debug() { 
      var_dump($this->response); 
     } 

    } 

?> 

,並在另一個文件,AJAX請求電話:

<?php 

    include ('proxy.php'); 

    ini_set('display_errors',1); 
    error_reporting(E_ALL); 

    $consumerKey = 'myKEY!'; 
    $consumerSecret = 'mySecret!'; 
    $bearerTokenCredentials = $consumerKey . ':' . $consumerSecret; 
    $base64TokenCredentials = base64_encode($bearerTokenCredentials); 

    $authProxy = new proxy('https://api.twitter.com/oauth2/token/'); 
    $authProxy->headers = array(
     'Content-Type: application/x-www-form-urlencoded', 
     'Authorization: Basic ' . $base64TokenCredentials, 
    ); 

    $response = $authProxy->makeRequest(); 
    if (is_null($response)) $authProxy->debug(); else echo $response; 

?> 

回答

2

代理腳本將簡單地將您的POST數據傳遞給Twitter。

在您的客戶端代碼中,不是使用Twitter的URL,而是使用類似yourProxyScript.php的內容。在該代理腳本中,您將從$_POST以及您需要的任何其他數據以及POST it to the Twitter API URL using cURL中獲取所有內容。

+0

酷了你。我會這樣做,並在完成時標記爲正確! – 2013-04-03 20:54:34

+0

完成它,謝謝。 – 2013-04-04 09:14:19