How to use curl to get streaming data from twitter in php - php

I trying to get streaming data from twitter, I found curl in twitter developer section to get streaming data
$ curl --request GET
--url 'https://api.twitter.com/1.1/search/tweets.json?q=nasa&result_type=popular'
--header 'authorization: OAuth oauth_consumer_key="consumer-key-for-app",
oauth_nonce="generated-nonce", oauth_signature="generated-signature",
oauth_signature_method="HMAC-SHA1", oauth_timestamp="generated-timestamp",
oauth_token="access-token-for-authed-user", oauth_version="1.0"'
But i found how to use curl to get data at http://collaboradev.com/2011/04/01/twitter-oauth-php-tutorial/ But I am getting
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
I checked my credential but could not solve ,problem persists: My code is below ::
$nonce = time();
$timestamp = time();
$oauth = array('oauth_callback' => 'https://localhost/twitter/curl.php',
'oauth_consumer_key' => 'bGLk7nhcMySEulFeRICCMdmtk',
'oauth_nonce' => $nonce,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => $timestamp,
'oauth_version' => '1.0');
function buildAuthorizationHeader($oauth){
$r = 'Authorization: OAuth '; //header prefix
$values = array(); //temporary key=value array
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\""; //encode key=value string
$r .= implode(', ', $values); //reassemble
return $r; //return full authorization header
}
$header = array( buildAuthorizationHeader($oauth), 'Expect:');
$options = array(CURLOPT_HTTPHEADER => $header, //use our authorization and expect header
CURLOPT_HEADER => false, //don't retrieve the header back from Twitter
CURLOPT_URL => 'https://api.twitter.com/1.1/search/tweets.json?q=nasa&result_type=popular', //the URI we're sending the request to
CURLOPT_POST => true, //this is going to be a POST - required
CURLOPT_RETURNTRANSFER => true, //return content as a string, don't echo out directly
CURLOPT_SSL_VERIFYPEER => false);
$ch = curl_init(); //get a channel
curl_setopt_array($ch, $options); //set options
$response = curl_exec($ch); //make the call
curl_close($ch); //hang up
echo $response;

Related

PHP - Getting bearer token from HERE REST API throws a signature mismatch error

before posting this question I have searched a solution for a long but all the snippets of code I tried always failed. It sounds really weird that there aren't working examples available in PHP!
I want to use HERE Maps REST API to geocode mail addresses. I have created my account and got the credentials as prerequisite.
Reference articles I followed are:
https://developer.here.com/blog/requesting-here-oauth-bearer-token-using-python
Cannot generate token via Here Map API in php
HERE Maps: Invalid Client Authorization header, expecting signed request format
https://developer.here.com/documentation/identity-access-management/dev_guide/topics/postman.html
The code I have developed is a combination/adaption of these referenced articles:
//This snippet is for signature
$timer = time();
$grant_type = 'client_credentials';
$oauth_consumer_key = 'here.access.key.id';
$oauth_nonce = (string)((int) ($timer * 1000));
$oauth_signature_method = 'HMAC-SHA256';
$oauth_timestamp = (string) ((int) ($timer));
$oauth_version = '1.0';
$url = 'https://account.api.here.com/oauth2/token';
$access_key_secret = "here.access.key.secret";
$parameter_string = 'grant_type='.$grant_type;
$parameter_string .= '&oauth_consumer_key='.$oauth_consumer_key;
$parameter_string .= '&oauth_nonce='.$oauth_nonce;
$parameter_string .= '&oauth_signature_method='.$oauth_signature_method;
$parameter_string .= '&oauth_version='.$oauth_version;
$encode_parameter_string = urlencode($parameter_string);
$encoded_base_string = 'POST'.'&'.urlencode($url).'&'.$encode_parameter_string;
$signing_key = $access_key_secret.'&';
$signature = hash_hmac('sha256', $encoded_base_string, $signing_key, true);
$encodedSignature = base64_encode($signature);
//This snippet is for getting the bearer token
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
CURLOPT_HTTPHEADER => array(
'oauth_consumer_key: '.urlencode($oauth_consumer_key),
'oauth_nonce: '.urlencode($oauth_nonce),
'oauth_signature: '.urlencode($encodedSignature),
'oauth_signature_method: '.urlencode($oauth_signature_method),
'oauth_timestamp: '.urlencode($oauth_timestamp),
'oauth_version: '.urlencode($oauth_version),
'Content-Type: application/x-www-form-urlencoded',
'Authorization: OAuth oauth_consumer_key="'.urlencode($oauth_consumer_key).'",oauth_signature_method="'.urlencode($oauth_signature_method).'",oauth_timestamp="'.urlencode($oauth_timestamp).'",oauth_nonce="'.urlencode($oauth_nonce).'",oauth_version="'.urlencode($oauth_version).'",oauth_signature="'.urlencode($encodedSignature).'"'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
This seems to avoid the wrong formatting of the request, the main error message I used to get as response. Unfortunately, the new error thrown with this snippet is "errorCode":401300,"message":"Signature mismatch. Authorization signature or client credential is wrong." but I am sure that the credentials I am passing are correct.
I suspect there is something wrong in the signature snippet. Any clue? Can you help me to provide a reference for HERE Oauth signature in PHP?
Thanks for sharing your comments!
I made it!
I missed a parameter in the signature and the $encodedSignature must be further url-encoded. Then I was able to get my access token.
I am embedding the full working code, hoping that this may help the community:
<?php
$timer = (string) time();
$grant_type = 'client_credentials';
$oauth_consumer_key = 'my_consumer_key';
$oauth_nonce = uniqid(mt_rand(1, 1000));
$oauth_signature_method = 'HMAC-SHA256';
$oauth_timestamp = $timer;
$oauth_version = '1.0';
$url = 'https://account.api.here.com/oauth2/token';
$access_key_secret = "my_access_key_secret";
$parameter_string = 'grant_type='.$grant_type;
$parameter_string .= '&oauth_consumer_key='.$oauth_consumer_key;
$parameter_string .= '&oauth_nonce='.$oauth_nonce;
$parameter_string .= '&oauth_signature_method='.$oauth_signature_method;
$parameter_string .= '&oauth_timestamp='.$oauth_timestamp;
$parameter_string .= '&oauth_version='.$oauth_version;
$encoded_parameter_string = urlencode($parameter_string);
$encoded_base_string = 'POST'.'&'.urlencode($url).'&'.$encoded_parameter_string;
$signing_key = $access_key_secret.'&';
$signature = hash_hmac('SHA256', $encoded_base_string, $signing_key, true);
$encodedSignature = urlencode(base64_encode($signature));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://account.api.here.com/oauth2/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
CURLOPT_HTTPHEADER => array(
'Authorization: OAuth oauth_consumer_key="'.$oauth_consumer_key.'",oauth_signature_method="HMAC-SHA256",oauth_timestamp="'.$oauth_timestamp.'",oauth_nonce="'.$oauth_nonce.'",oauth_version="1.0",oauth_signature="'.$encodedSignature.'"',
'Content-Type: application/x-www-form-urlencoded'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Convert Rest API call from PHP to RUBY

Im trying to convert a post connection to the walmart api, from php to ruby, this is the php version
$client_id = $data['client_id'];
$client_secret = $data['client_secret'];
$url = "https://marketplace.walmartapis.com/v3/token";
$uniqid = uniqid();
$authorization_key = base64_encode($client_id.":".$client_secret);
$code = "";
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HEADER => false,
CURLOPT_POST =>1,
CURLOPT_POSTFIELDS => "grant_type=client_credentials",
CURLOPT_HTTPHEADER => array(
"WM_SVC.NAME: Walmart Marketplace",
"WM_QOS.CORRELATION_ID: $uniqid",
"Authorization: Basic $authorization_key",
"Accept: application/json",
"Content-Type: application/x-www-form-urlencoded",
),
);
curl_setopt_array($ch,$options);
$response = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
and this is what i have so far:
url = "https://marketplace.walmartapis.com/v3/token/"
uniqid = "1234567890a1b"
uri = URI.parse(url)
request = Net::HTTP::Post.new(uri)
request["WM_SVC.NAME"] = "Walmart Marketplace"
request["WM_QOS.CORRELATION_ID"] = uniqid
request.basic_auth(client_id, client_secret)
request["Accept"] = "application/json"
request.content_type = "application/x-www-form-urlencoded"
request["WM_SVC.VERSION"] = "1.0.0"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts "error " + response.code
puts response.body
Now, im getting a 400 error, so something of the data im sending is incorrect or missing... comparing both, i dont have set the postfields option on ruby, for the POST request, not sure if the rest is required as well... any ideas?
Try adding this line:
request.body = 'grant_type=client_credentials'

Missing parameters when requesting OAUTH token survey monkey v3

I'm trying to obtain my "long lived access token" using CURL/PHP but I'm receiving the error "Missing parameters for client_id, client_secret, code, grant_type, redirect_uri".
The URL I'm calling is where you can clearly see the parameters I'm trying to pass in!
https://api.surveymonkey.net/oauth/token?client_secret='.urlencode($client_secret).'&code='.urlencode($short_token).'&redirect_uri='.urlencode($redirect_url).'&client_id='.urlencode($client_id).'&grant_type=authorization_code
I'm also using the content-type of "application/x-www-form-urlencoded" as per the docs (see below).
My CURL request:
function survey_monkey_curl_request($url, $params=[], $request_type = 'get', $access_token) {
print_r($url);
$ch = curl_init();
$headers = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: bearer " .$access_token
];
$opts = [
CURLOPT_URL => $url,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => 0,
];
if ($request_type == 'post') {
$opts[CURLOPT_POST] = 1;
//$opts[CURLOPT_POSTFIELDS] = json_encode($params);
}
if ($request_type == 'patch') {
$opts[CURLOPT_CUSTOMREQUEST] = "PATCH";
$opts[CURLOPT_POSTFIELDS] = json_encode($params);
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if ($result === false) {
curl_close($ch);
throw new Exception(curl_error($ch));
}
curl_close($ch);
return $result;
}
Where am I going wrong?
Straight from the documentation it looks like to get the long-lived token you need to post your fields:
//Exchange for long-lived token
curl -i -X POST https://api.surveymonkey.net/oauth/token -d \
"client_secret=YOUR_CLIENT_SECRET \
&code=AUTH_CODE \
&redirect_uri=YOUR_REDIRECT_URI \
&client_id=YOUR_CLIENT_ID \
&grant_type=authorization_code"
https://developer.surveymonkey.com/api/v3/?shell#new-authentication
When you append your parameters onto your url you are sending then as GET request paramters
You need to put your data string into CURL POSTFIELDS and do not json encode
The PHP Answer
<?php
$ch = curl_init();
$data = [
'client_secret' => $YOUR_CLIENT_SECRET,
'code' => $AUTH_CODE,
'redirect_url' => $YOUR_REDIRECT_URI,
'client_id' => $YOUR_CLIENT_ID,
'grant_type' => 'authorization_code'
];//set your data as an array
$headers = [
"Content-Type: application/x-www-form-urlencoded",
"Authorization: bearer " . $access_token
];
$opts = [
CURLOPT_URL => $url,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYPEER => 0,
];
if ($request_type == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = http_build_query($data);// this will build your data string from the array
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
curl_close($ch);
return $result;

Dropbox HTTP API - PHP cURL added header item boundary automatically

I'm new with the Dropbox API integrations, and I'm using the PHP cURL extension to make calls to the HTTP REST API, and when I try to make a request I receive the following string:
Error in call to API function "files/list_folder":
Bad HTTP "Content-Type" header:
"text/plain; boundary=----------------------------645eb1c4046b".
Expecting one of "application/json", "application/json; charset=utf-8",
"text/plain; charset=dropbox-cors-hack".
I'm sending this with code very similar to this:
$sUrl = "https://api.dropboxapi.com/2/files/list_folder";
$oCurl = curl_init($sUrl);
$aPostData = array('path' => '', 'recursive' => true, 'show_hidden' => true);
$sBearer = "MY_TOKEN";
$aRequestOptions = array(
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array('Content-Type: text/plain',
'Authorization: Bearer ' . $sBearer),
CURLOPT_POSTFIELDS => $aPostData,
CURLOPT_RETURNTRANSFER => true);
curl_setopt_array($aRequestOptions);
$hExec = curl_exec($oCurl);
if ($hExec === false){
// Some error info in JSON format
} else {
var_dump($hExec);
}
As you have it, you're doing a multipart form upload, which isn't what the API expects.
There are a few things you need to do differently:
You should be sending up the parameters as JSON in the body.
You should set the Content-Type to application/json, accordingly.
There isn't a show_hidden parameter on /files/list_folder, but perhaps you meant to send include_deleted.
The curl_setopt_array method takes two parameters, the first of which should be the curl handle.
Here's an updated version of your code that works for me:
<?php
$sUrl = "https://api.dropboxapi.com/2/files/list_folder";
$oCurl = curl_init($sUrl);
$aPostData = array('path' => '', 'recursive' => true, 'include_deleted' => true);
$sBearer = "MY_TOKEN";
$aRequestOptions = array(
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => array('Content-Type: application/json',
'Authorization: Bearer ' . $sBearer),
CURLOPT_POSTFIELDS => json_encode($aPostData),
CURLOPT_RETURNTRANSFER => true);
curl_setopt_array($oCurl, $aRequestOptions);
$hExec = curl_exec($oCurl);
if ($hExec === false){
// Some error info in JSON format
} else {
var_dump($hExec);
}
?>

Oauth header issue with twitter api 1.1

I've been trying to access the new twitter api (1.1) for 3 days now, the new oauth system and i are not compatible. I only want to grab 3 of my latest tweets (which are public so why the need for oauth over simple rss is annoying)
<?php
$header = 'GET /statuses/user_timeline.json?screen_name=NAME&count=3&include_rts=false HTTP/1.1
Host: https://www.twtter.com:443
Authorization: OAuth realm="https://https://www.twtter.com/statuses/user_timeline.json",
oauth_consumer_key="key",
oauth_token="mytoken",
oauth_nonce="",
oauth_timestamp="0",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="O4yJhqnYlxMP5U97rJ%2F4UuLjh84%3D"';
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=NAME&count=3&include_rts=false";
$options = array(
CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
?>
The header seems to be the problem ( i generated it using: http://hueniverse.com/oauth/guide/authentication/ )
NAME, MYTOKEN, KEY are placeholders for posts' sake.
Can anyone see what the problem is?
This is what I use. Just call returnTweet()
For more info about 'user_timeline', visit API documentation
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function returnTweet(){
$oauth_access_token = "xxx";
$oauth_access_token_secret = "xxx";
$consumer_key = "xxx";
$consumer_secret = "xxx";
$twitter_timeline = "user_timeline"; // mentions_timeline / user_timeline / home_timeline / retweets_of_me
// create request
$request = array(
'trim_user' => 1,
'screen_name' => 'budidino',
'count' => '3'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
// merge request and oauth to one array
$oauth = array_merge($oauth, $request);
// do some magic
$base_info = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// make request
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return json_decode($json, true);
}
I hope it helps ;)

Categories