Get Twitter Following Count - php

Im creating a widget for a Wordpress site and i am trying to get the twitter following count, I can get the followers count which is taken from http://www.wpbeginner.com/wp-tutorials/displaying-the-total-number-of-twitter-followers-as-text-on-wordpress/. Any help would be great.
thanks Pierce
Current code in functions.php:
// Twitter
function getTwitterFollowers($screenName = 'hellowWorld')
{
// some variables
$consumerKey = 'hidden';
$consumerSecret = 'hidden';
$token = get_option('cfTwitterToken');
// get follower count from cache
$numberOfFollowers = get_transient('cfTwitterFollowers');
// cache version does not exist or expired
if (false === $numberOfFollowers) {
// getting new auth bearer only if we don't have one
if(!$token) {
// preparing credentials
$credentials = $consumerKey . ':' . $consumerSecret;
$toSend = base64_encode($credentials);
// http post arguments
$args = array(
'method' => 'POST',
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => 'Basic ' . $toSend,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
),
'body' => array( 'grant_type' => 'client_credentials' )
);
add_filter('https_ssl_verify', '__return_false');
$response = wp_remote_post('https://api.twitter.com/oauth2/token', $args);
$keys = json_decode(wp_remote_retrieve_body($response));
if($keys) {
// saving token to wp_options table
update_option('cfTwitterToken', $keys->access_token);
$token = $keys->access_token;
}
}
// we have bearer token wether we obtained it from API or from options
$args = array(
'httpversion' => '1.1',
'blocking' => true,
'headers' => array(
'Authorization' => "Bearer $token"
)
);
add_filter('https_ssl_verify', '__return_false');
$api_url = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
$response = wp_remote_get($api_url, $args);
if (!is_wp_error($response)) {
$followers = json_decode(wp_remote_retrieve_body($response));
$numberOfFollowers = $followers->followers_count;
} else {
// get old value and break
$numberOfFollowers = get_option('cfNumberOfFollowers');
// uncomment below to debug
//die($response->get_error_message());
}
// cache for an hour
set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);
update_option('cfNumberOfFollowers', $numberOfFollowers);
}
return $numberOfFollowers;
}

It was pretty simple if I just read the documentation anyway...
Instead of followers_count i replaced it with friends_count as outlined in the API 1.1 documentation. :)

Related

OpenSubtitles API 401 Unauthorized how to fix?

I'm trying to fetch subtitles from OpenSubtitles (http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC) like this:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//Opensubtitles listing
function data($request){
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml\r\nUser-Agent: PHPRPC/1.0\r\n",
'content' => $request
)));
$server = 'http://api.opensubtitles.org/xml-rpc'; // api url
$file = file_get_contents($server, false, $context);
$response = xmlrpc_decode($file);
return $response;
}
//Get token
$request = xmlrpc_encode_request("LogIn", array('', '', 'eng', 'TemporaryUserAgent'));
$token = data($request)['token'];
//Get listing
$request = xmlrpc_encode_request("SearchSubtitles", array(
'imdb' => '0462499',
'sublanguageid' => 'eng',
'season' => '',
'episode' => '',
'token' => $token
));
$response = data($request);
var_dump($response);
?>
However I keep getting 401 Unauthorized. Does anyone know how to fix this problem? I know it's not a problem with the API because I am able to retrieve the token just fine.
Try using your username/password instead empty string.
And change UserAgent in TemporaryUserAgent in Header as written in
http://trac.opensubtitles.org/projects/opensubtitles/wiki/DevReadFirst
The second request should be in the following format:-
$request = xmlrpc_encode_request("SearchSubtitles", array($token, array(array('sublanguageid' => 'eng', 'imdbid' => 'your_imdbid'))));
Hope this helps.

how to integrate Assently api for e-signature transaction in PHP

In my wp project, I am using Assently for e-signature implementation. Though I have an account and created a pdf form file to be filled by the user I just am not able to proceed a bit. I am finding documentation not clear.
Also, I am not clear about what needs to be done so that the user will be shown form to process the transaction.
So, any help/suggestions to proceed forward is appreciated.
I have tried the following based on assently-laravel. But it's asking me to login. What is an error here?
Code:
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$url = 'https://test.assently.com/api/v2/createcasefromtemplate';
$default = array(
'Id' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce'
);
$data = array(
'auth' => $assently->auth(),
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce',
'agentUsername' => ''
);
$data = array(
'json' => $data
);
$options = array(
'http' => array(
'header' => "Content-type: application/json; charset=utf-8\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo '<pre>';
print_r($result);
die;
create this class inside assently folder
use Assently\AssentlyCase;
use Exception;
class CustomAssentlyCase extends AssentlyCase
{
public function createFromTemplate($data)
{
$default = [
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce'
];
$json = array_merge($default, $data);
try{
$response = $this->client->post($this->url('createcasefromtemplate'), [
'auth' => $this->assently->auth(),
'json' => $json
]);
}catch(Exception $e){
print_r($e->getMessage());
}
return $response;
}
}
Use
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
include_once('assently/CustomAssentlyCase.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$data = array(
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce',
'agentUsername' => 'agentUsername' // PUT your agent username here it is required
);
$customAssentlyCase = new CustomAssentlyCase($assently);
$result = $customAssentlyCase->createFromTemplate($data);
print_r($result);
Try this, though not tested but should work. Good luck.

Can not fetch value of an element using Symfony Dom Crawler

I am fetching a URL using guzzle POST method . its working and returning the page that I want . but the problem is when I want to get the value of an input element in a form in that page, the crawler returns nothing . I don't know why .
PHP:
<?php
use Symfony\Component\DomCrawler\Crawler;
use Guzzle\Http\Client;
$client = new Client();
$request = $client->get("https://example.com");
$response = $request->send();
$getRequest = $response->getBody();
$cookie = $response->getHeader("Set-Cookie");
$request = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
'param1' => 5,
'param2' => 10,
'param3' => 20
));
$response = $request->send();
$pageHTML = $response->getBody();
//fetch orderID
$crawler = new Crawler($pageHTML);
$orderID = $crawler->filter("input[name=orderId]")->attr('value');//there is only one element with this name
echo $orderID; //returns nothing
What should I do ?
You don't have to create a Crawler:
$crawler = $client->post('https://example.com/page_example.php', array(
'Content-Type' => 'application/x-www-form-urlencoded',
'Cookie' => $cookie
), array(
'param1' => 5,
'param2' => 10,
'param3' => 20
));
$orderID = $crawler->filter("input[name=orderId]")->attr('value');
This assumes your POST isn't being redirected, if it is redirected you should add before calling the filter function:
$this->assertTrue($client->getResponse()->isRedirect());
$crawler = $client->followRedirect();

How to set request headers in WordPress Rest API calls

Hi am new to WP development, I would like to add request headers to WordPress Rest API calls but don't know how, can anyone help me in this?
I tried following code but no luck
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( Fk-Affiliate-Id . ':' . YOUR_PASSWORD )
)
);
$api_url = 'https://affiliate.com/api/';
global $affiliate;
$response = wp_remote_request( add_query_arg( array(
'Affiliate-Id' => $affiliate['aff-id'],
'Affiliate-Token' => $affiliate['aff-token']
), $api_url ) , array( 'timeout' => 10));
You can send the headers you need by including those in request options - second argument of wp_remote_request function($args in my example)
$args = [
'method' => 'GET',
'timeout' => 10,
'headers' => array() //add headers here
];
wp_remote_request('http://test.com', $args);

Cannot login to MediaWiki-API with file_get_contents()

Where did I make a mistake? My PHP-script:
<?php
// Set username and password
$lgname = "someUsername";
$lgpassword = "somePassword";
// First login to receive 1) token, 2) sessionid and 3) cookieprefix
$parameters = array('action' => 'login', 'lgname' => "$lgname", 'lgpassword' => "$lgpassword", 'format' => 'json');
options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($parameters)
),
);
$context = stream_context_create($options);
$result = file_get_contents("http://en.wikipedia.org/w/api.php", false, $context);
// Echo out the answer from MediaWiki-API
echo "$result";
// Put the needed parts of the answer into variables and echo them out
$array = json_decode($result,true);
$token = $array["login"]["token"];
$sessionid = $array["login"]["sessionid"];
$cookieprefix = $array["login"]["cookieprefix"];
echo "</BR>token: $token, sessionid: $sessionid, cookieprefix: $cookieprefix</BR>";
// Second login to 1) post token and 2) send sessionID within the header
$parameters = array('action' => 'login', 'lgname' => "$lgname", 'lgpassword' => "$lgpassword", 'lgtoken' => "$token", 'format' => 'json');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n" .
"Cookie: " . $cookieprefix . "_session = $sessionid\r\n",
'method' => 'POST',
'content' => http_build_query($parameters)
),
);
$context = stream_context_create($options);
$result = file_get_contents("http://en.wikipedia.org/w/api.php", false, $context);
// Echo out result
echo "$result";
?>
What I get as an answer to my second POST-request is (exactly the same as to my first POST-request) that I need a token (even though I posted the token and even the sessionID in my second POST-request):
{"login": {
"result":"NeedToken",
"token":"82b3f2e1f1aa702ca6ceae473bb16bde",
"cookieprefix":"dewiki",
"sessionid":"531143bd7425722bf1be88e520dea6d5"}
}
The mistake is in using file_get_contents() in the first place. Use a PHP library for the MediaWiki web API, instead.
If you really want to do things yourself, ask a token from meta=tokens.

Categories