I am writing a fairly basic web app that integrates with the Twitter API. I am requesting the auth token Twitter require with jQuery and AJAX but I am violating the asynchronous cross site request policy or whatever it is.
I would use JSONP but the Twitter API requires a POST. I have read I should use an itermediate proxy. I have no idea what that involves and can't find any resources? I can write in PHP.
Can anyone explain what a proxy page is?
UPDATE
Following reading the accepted answer below I wrote a PHP proxy script, this is what I came up with and got working:
<?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);
}
}
?>
and in another file which the AJAX request calls:
<?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;
?>
A proxy script will simply take your POST data and relay it on to Twitter.
In your client-side code, instead of using the URL for Twitter, you will use something like yourProxyScript.php
. In that proxy script, you will take everything from $_POST
, along with any other data you need, and POST it to the Twitter API URL using cURL.