Can not authenticate user with Twitter V1.1 API - php

I've implemented everything up through Creating a Signature. I created a function to collect the required parameters (I've added some comments here for clarity):
function collect_parameters(){
global $credentials; // This is an Object with my App's credentials and stuff
$oAuth = get_user_oauth(); // This returns an object with the the personal user OAuth tokens retrieved from the earlier docs.
$encoded_collection = array();
$collection = array(
'status' => rawurlencode( $_GET['tweet'] ),
'include_entities' => 'true',
'oauth_consumer_key' => $credentials->key,
'oauth_nonce' => $credentials->nonce, // md5( str_shuffle( uniqid() . mt_rand(0,9999999999) ) )
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => $credentials->time, // current timestamp
'oauth_token' => $oAuth->oauth_token,
'oauth_version' => '1.0',
);
// Percent encode every key and value that will be signed.
foreach( $collection as $key => $value ){
$encoded_collection[rawurlencode($key)] = rawurlencode($value);
}
// Sort the list of parameters alphabetically by encoded key.
ksort( $encoded_collection );
return http_build_query( $encoded_collection );
}
I use this function to build the Signature Base String
function create_signature_base_string( $parameter_string, $url = 'https://api.twitter.com/1.1/statuses/update.json', $method = 'POST' ){
return strtoupper( $method ) .'&'. rawurlencode( $url ) .'&'. rawurlencode( $parameter_string );
}
I use this function to calculate the signature
function calculate_signature( $signature_base_string, $signing_key ){
return base64_encode( hash_hmac('sha1', $signature_base_string, $signing_key, true) );
}
Now to building the OAuth Header. here's a function for it, that uses the helper functions from above (plus some others that return the required information):
function get_oauth_headers(){
global $credentials;
$oAuth = get_user_oauth();
$parameters = collect_parameters();
$signature_base_string = create_signature_base_string( $parameters );
$signing_key = get_signing_key();
$signature = calculate_signature( $signature_base_string, $signing_key );
$auth_array = array(
'oauth_consumer_key' => $credentials->key,
'oauth_nonce' => $credentials->nonce,
'oauth_signature' => $signature,
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => $credentials->time,
'oauth_token' => $oAuth->oauth_token,
'oauth_version' => '1.0'
);
ksort( $auth_array );
return $auth_array;
}
Now I've got everything in a nice & neat little array, it's time to actually try and send this to Twitter.
function create_tweet( $build_query = true ){
global $credentials;
$ch = curl_init();
$url = 'https://api.twitter.com/1.1/statuses/update.json';
$fields = array(
'status' => rawurlencode( $_GET['tweet'] ) // I've just been using "Test" or "WhyNoWork" style text in this $_GET param
);
$oAuth_headers = get_oauth_headers(); // This uses that function above that returns all of the specific parameters for OAuth, sorted, and ready to go.
$oAuth_array = array();
// Loop through the oauth headers, and encode them
foreach( $oAuth_headers as $key => $value ){
$oAuth_array[] = rawurlencode($key) .'="'. rawurlencode($value) .'"';
}
// Implode it into a single line
$oAuth_string = implode(', ', $oAuth_array );
$headers = array(
'Content-Type: application/x-www-form-rawurlencoded',
'Authorization: OAuth '. $oAuth_string,
);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_ENCODING, 'gzip' );
curl_setopt( $ch, CURLOPT_POST, true );
// It seems to prefer this as a query string instead of postfields?
if( $build_query == true ){
curl_setopt( $ch, CURLOPT_URL, $url.'?'.http_build_query($fields) );
} else {
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $fields );
}
$result = curl_exec( $ch );
$info = curl_getinfo( $ch );
curl_close( $ch );
if( isset($_GET['debug']) ){
echo $result;
var_dump( $info );
} else {
echo $result;
}
}
For example, here's the order of everything in the OAuth header. I've run through each of my little helper functions a dozen times making sure they take in the right arguments and output the appropriate values. I've even replaced my own OAuth credentials with the ones from the docs, and end up with the same results they do for the signing key, signature, etc.:
Yet, everytime I try and run the create_tweet() function, I get a 401 status code with error 32: {"errors":[{"code":32,"message":"Could not authenticate you."}]}. What the heck am I missing? Is it possible to see why they couldn't authenticate the request?
Here's the output from collect_parameters();
include_entities=true&oauth_consumer_key=APP_API_KEY&oauth_nonce=ABC123&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1597456781&oauth_token=USER_AUTH_TOKEN&oauth_version=1.0&status=TESTING
That is passed to the Signature Base String function, which returns the following:
POST&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3DAPP_API_KEY%26oauth_nonce%3DABC123%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1597457034%26oauth_token%3DUSER_AUTH_TOKEN%26oauth_version%3D1.0%26status%3DTESTING
That looks good, and now I take the signing key: APP_SECRET&USER_AUTH_SECRET and pass those to calculate the signature gives me a value just like the one in the Docs (and using the params in the docs gives me the same signature that they show): thIsiSeEmSUnNecEssArYPOs3OxQdSNpI=
I don't understand how I can replace my data with the test data and get the same result, but I still can't get an API Request authenticated?

You are performing a couple of extra encodings.
First, in collect_parameters you are encoding keys and values for the $encoded_collection array and then passing that to http_build_query which will further encode them. You can completely remove the loop to encode items and instead pass them directly to http_build_query. The trick there is that it defaults to + encoding, so you need to tell it to switch to % encoding using the fourth parameter:
function collect_parameters()
{
global $credentials; // This is an Object with my App's credentials and stuff
$oAuth = get_user_oauth(); // This returns an object with the the personal user OAuth tokens retrieved from the earlier docs.
$collection = [
'status' => 'Hello Ladies + Gentlemen, a signed OAuth request!',
'include_entities' => 'true',
'oauth_consumer_key' => $credentials->key,
'oauth_nonce' => $credentials->nonce, // md5( str_shuffle( uniqid() . mt_rand(0,9999999999) ) )
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => $credentials->time, // current timestamp
'oauth_token' => $oAuth->oauth_token,
'oauth_version' => '1.0',
];
// Sort the list of parameters alphabetically by encoded key.
ksort($collection);
return http_build_query($collection, '', '&', PHP_QUERY_RFC3986);
}
Next, in your create_tweet function, in the first loop, you are encoding both keys and values again which isn't needed and can be removed:
foreach ($oAuth_headers as $key => $value) {
$oAuth_array[] = $key . '="' . $value . '"';
}
I unfortunately don't have a Twitter account to test all of this, but their docs have sample keys that I was able to use and a sample output, and using that these changes and the docs produced the same output.

Related

How to use curl to get streaming data from twitter in 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;

GoToTraining API rejecting json?

OK, I'm using the GoToTraining API to try to create a new Training. The docs say to "post" JSON to the endpoint.
So I have my array of data in PHP (this is a WordPress site, and here I'm grabbing stuff from Advanced Custom Fields data)
$my_data_array = array(
'name' => get_the_title( $_POST['acf']['field_5ab508b853122'] ),
'description' => $_POST['acf']['field_5ab50b2406457'],
'timeZone' => 'America/Los_Angeles',
'times' => array(
array(
'startDate' => date( 'Y-m-d', strtotime( $_POST['acf']['field_5ab50908347ef'] ) ) . 'T' . $_POST['acf']['field_5ab50bc6af8df'] . 'Z',
'endDate' => date( 'Y-m-d', strtotime( $_POST['acf']['field_5ab50908347ef'] ) ) . 'T' . $_POST['acf']['field_5abbd96c6ff8d'] . 'Z',
),
),
'registrationSettings' => array(
'disableConfirmationEmail' => false,
'disableWebRegistration' => true,
)
);
and then I'm just doing:
$payload = json_encode( $my_data_array )
to create the payload, which looks like this, if I print_r the value of $payload:
{"name":"Today’s Class","description":"We can add some default content here","timeZone":"America\/Los_Angeles","times":[{"startDate":"2018-04-24T06:00:00Z","endDate":"2018-04-24T09:00:00Z"}],"registrationSettings":{"disableConfirmationEmail":false,"disableWebRegistration":true}}
If I make the curl request, posting $payload, I get back:
Array
(
[errorCode] => InternalError
[description] => We have encountered an internal error. The request may
be retried, but it may have the same result.
[incident] => 5102160953111715072
)
Could be lots of things, right? But here is thing that's driving me crazy:
If cut and paste that dumped value of $payload above into the "body" field in the sandbox thing on the API reference page (see the link above), it works fine and I get an ID for the new Training back as the response.
Moreover, if I cut and paste that same string and just hardcode it as a string value of my $payload variable in my script (using the exact same code for the curl stuff) -- only difference being I'm hardcoding the value of $payload, like this
$payload = '{"name":"Today’s Class","description":"We can add some default content here","timeZone":"America\/Los_Angeles","times":[{"startDate":"2018-04-24T06:00:00Z","endDate":"2018-04-24T09:00:00Z"}],"registrationSettings":{"disableConfirmationEmail":false,"disableWebRegistration":true}}';
... and make the request that way, it also works and gives me a successful response!
protected function make_request( $url, $method, $fields ) {
// $payload = json_encode( $fields );
$payload = '{"name":"Getting to Know Today’s Electric Utility Industry","description":"We can add some default content here","timeZone":"America\/Los_Angeles","times":[{"startDate":"2018-04-24T06:00:00Z","endDate":"2018-04-24T09:00:00Z"}],"registrationSettings":{"disableConfirmationEmail":false,"disableWebRegistration":true}}';
$http_headers = array(
'Accept: application/json',
'Content-Type: application/json',
'Authorization: OAuth oauth_token=' . $this->access_token,
);
$ch = curl_init();
if ( 'post' == $method ) {
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload ); // define what you want to post
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); // return the output in string format
curl_setopt( $ch, CURLOPT_HTTPHEADER, $http_headers );
}
$response = curl_exec( $ch );
curl_close( $ch ); // close curl handle
return $response;
}
But what's assigned to $payload here is exactly the same thing I'm getting if I print_r what json_encode() returns. Whaa??
I do notice, if I run
mb_detect_encoding( $payload );
I get 'ASCII' from the json_encode version and I get 'UTF-8' on the version where I hardcode the string as the value of the variable. Would that make any difference?
Am I missing something simple? Anyone have any idea what I might be doing wrong here? Been beating my head against the wall for too many hours.
So for posterity: Turns out that apostrophe in the name of the Training was causing GTT to choke on the data getting sent over. But it had something to do with the get_the_title() function, which handles apostrophes and quotes differently than just grabbing the value from $post->post_title. When I changed the code that was assembling the data for the API call to $post->post_title instead of get_the_title(), it worked.

How to return errors from MailChimp API v3.0 batch operation

I’m struggling with the new MailChimp API and the batch functionality, specifically, how to return any errors from the underlying operations that were batched, not the batch operation itself.
My code is below and works to add the two test subscribers. The response only shows success for the overall batch:
[errored_operations] => 0
If I run it again, it will return a similar response, but with two errors:
[errored_operations] => 2
Other than that, there is no indication as to what failed or why. In this case, we know that it’s because the users are already subscribed. If I try to add a single user without the batch call, using POST /lists/{list_id}/members, I get a response that details exactly what failed.
stdClass Object
(
[type] => http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
[title] => Member Exists
[status] => 400
[detail] => mary#jackson.net is already a list member. Use PUT to insert or update list members.
[instance] =>
)
How can I capture individual errors when adding (or updating or deleting) hundreds of subscribers?
I have tried just looping through users, making multiple individual calls, and that works: it adds the users and/or provides detailed error reporting. But it seems goofy to make 500 calls when the API is set up to handle this in a single call. Thanks for any ideas!
Here is my code:
$list_id = 'xyz123';
$subscribers = array(
array(
'email' => 'jeff#jackson.net',
'status' => 'subscribed',
'firstname' => 'Jeff',
'lastname' => 'Jackson'
),
array(
'email' => 'mary#jackson.net',
'status' => 'subscribed',
'firstname' => 'Mary',
'lastname' => 'Jackson'
)
);
$add_subs_batch = add_subs_batch($list_id, $subscribers);
echo '<pre>add_subs_batch: ';
print_r($add_subs_batch);
echo '</pre>';
function add_subs_batch($list_id, $data) {
$method = 'POST';
$batch_path = 'lists/' . $list_id . '/members';
$result = mc_request_batch($method, $batch_path, $data);
if($result && $result->id) {
$batch_id = $result->id;
$batch_status = get_batch_status($batch_id);
return $batch_status;
}
else {
return $result;
}
}
function get_batch_status($batch_id, $i=1) {
$method = 'GET';
$target = 'batches/'.$batch_id;
$result = mc_request($method, $target, $data);
sleep(1); // wait 1 second and try
if($result->status == 'finished' ) {
return $result;
}
else {
return get_batch_status($batch_id, $i+1);
}
}
function mc_request_batch( $method, $batch_path, $data = false ) {
$api_key = '12345-us1';
$dataCenter = substr($api_key,strpos($api_key,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/';
$target = 'batches';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $target );
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $api_key);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_USERAGENT, 'YOUR-USER-AGENT' );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if( $data ) {
$batch_data = new stdClass();
$batch_data->operations = array();
foreach ($data as $item) {
$batch = new stdClass();
$batch->method = $method;
$batch->path = $batch_path;
$batch->body = json_encode( array(
'email_address' => $item['email'],
'status' => $item['status'],
'merge_fields' => array(
'FNAME' => $item['firstname'],
'LNAME' => $item['lastname']
)
) );
$batch_data->operations[] = $batch;
}
$batch_data = json_encode($batch_data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $batch_data );
$response = curl_exec( $ch );
}
curl_close( $ch );
return json_decode($response);
}
You will get an id in response of the batch operation. This is 'Batch ID' which is a string that uniquely identifies the batch request.
To get the status of a batch request, you have to call a GET request to the URL, /batches/{batch_id}.
From the response, you can find a URL in response_body_url field which has the gzipped archive of the results of all the operations in the batch call.
Reference:
http://developer.mailchimp.com/documentation/mailchimp/reference/batches
http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-batch-operations/
Note
For security reasons, response_body_url is only valid for 10 minutes.
After 10 minutes, generate another with a GET call to
/3.0/batches/{batch_id}.
After you make the batch operation request, results are available for
7 days.

Can't get Twitter Widget working

I wondered if someone can help?
I've purchased a web theme for a client but can't get the twitter widget working. It's probably something really simple but as I'm not a web developer I'm struggling to figure out what's preventing it form working.
Here's the webpage http://www.blackrocksearch.co.uk/new/ - the twitter feed should display in the footer. It works on the templates demo site but I notice in the item comments other customers having the same issue so think there could be a glitch somewhere.
Demo where it's working here:http://vasterad.com/themes/sensation/index.html
Here's the snippet of code from the twitter.php file which is apparently the only area I need to configure (I've left out the actual access token numbers for security):
<?php
/**
* Usage:
* Send the url you want to access url encoded in the url paramater, for example (This is with JS):
* /twitter-proxy.php?url='+encodeURIComponent('statuses/user_timeline.json?screen_name=MikeRogers0&count=2')
*/
// The tokens, keys and secrets from the app you created at https://dev.twitter.com/apps
$config = array(
'oauth_access_token' => 'token-here',
'oauth_access_token_secret' => 'token-here',
'consumer_key' => 'token-here',
'consumer_secret' => 'token-here',
'use_whitelist' => true, // If you want to only allow some requests to use this script.
'base_url' => 'http://api.twitter.com/1.1/'
);
/*
* Ok, no more config should really be needed. Yay!
*/
// We'll get the URL from $_GET[]. Make sure the url is url encoded, for example encodeURIComponent('statuses/user_timeline.json?screen_name=MikeRogers0&count=10&include_rts=false&exclude_replies=true')
if(!isset($_GET['url'])){
die('No URL set');
}
$url = $_GET['url'];
if($config['use_whitelist'] && !isset($whitelist[$url])){
die('URL is not authorised');
}
// Figure out the URL parmaters
$url_parts = parse_url($url);
parse_str($url_parts['query'], $url_arguments);
$full_url = $config['base_url'].$url; // Url with the query on it.
$base_url = $config['base_url'].$url_parts['path']; // Url with the query.
/**
* Code below from http://stackoverflow.com/questions/12916539/simplest-php-example-retrieving-user-timeline-with-twitter-api-version-1-1 by Rivers
* with a few modfications by Mike Rogers to support variables in the URL nicely
*/
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;
}
// Set up the oauth Authorization array
$oauth = array(
'oauth_consumer_key' => $config['consumer_key'],
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $config['oauth_access_token'],
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$base_info = buildBaseString($base_url, 'GET', array_merge($oauth, $url_arguments));
$composite_key = rawurlencode($config['consumer_secret']) . '&' . rawurlencode($config['oauth_access_token_secret']);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// Make Requests
$header = array(
buildAuthorizationHeader($oauth),
'Expect:'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $full_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false
);
$feed = curl_init();
curl_setopt_array($feed, $options);
$result = curl_exec($feed);
$info = curl_getinfo($feed);
curl_close($feed);
// Send suitable headers to the end user.
if(isset($info['content_type']) && isset($info['size_download'])){
header('Content-Type: '.$info['content_type']);
header('Content-Length: '.$info['size_download']);
}
echo($result);
?>
Hope someone can help!
By looking on your site on PHP file that doing a request to Twitter's response, it appears that your request needs to do a secure connection. So, my guesses are:
1. Connecting through https
Change your base_url key on $config variable to https.
$config = array(
'oauth_access_token' => 'token-here',
'oauth_access_token_secret' => 'token-here',
'consumer_key' => 'token-here',
'consumer_secret' => 'token-here',
'use_whitelist' => true,
'base_url' => 'https://api.twitter.com/1.1/' //was http://api.twitter.com/1.1/
);
2. Adding CA (Certificate Authority) cert file
In case my first guess doesn't resolve anything, adding CA cert on cURL request might help. First, get your own cacert.pem from here. Save it on some path you could recognize. Then simply set cURL option CURLOPT_SSL_VERIFYPEERto true and optionally you can also explicitly set CURLOPT_SSL_VERIFYHOST to its default value which is 2.
In example, according to your snippet, saving in a same path as your Twitter cURL PHP file.
$options = array(
CURLOPT_CAINFO => __DIR__ . '/cacert.pem', //or dirname(__FILE__) . '/cacert.pem' for PHP < 5.3
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $full_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => true,
);
As an option you can also predefine the cacert.pem in your php.ini configuration file. Just add/edit following line and don't forget about the path too
curl.cainfo = "some/path/cacert.pem"
Let me know

Getting values from json query [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 months ago.
First of all I've never used JSON before. As you might know twitter has changed their api to v1.1 and i am trying to show count of followers on the page. I've followed this post and now able to see all of the json values
this is the code i am using
$token = 'CODE';
$token_secret = 'CODE';
$consumer_key = 'CODE';
$consumer_secret = 'CODE';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'username',
'count' => '2'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
This is the minimised output
[{"created_at":"Thu Mar 21 12:11:51 +0000 2013", ....
"id":314710946549465088,"followers_count": "3" }]
and my question is how can i GET the followers_count value from this output and echo in a div.
Found the answer
Change this
$result = json_decode($json);
to
$result = json_decode($json, true);
Then add
echo $result[0][user][followers_count];

Categories