Twitter API upload with PHP OAuth - php

I've been trying to find the best OAuth PHP lib for Twitter for hours. the TmhOAuth by Matt Harris seems kinda bloated (no offence) and started shooting PHP Warnings and Strict Standards notices right after I "installed" it.
All I want is to update my bg photo through the API. Just mine, so there is no need for any login and callbacks of any kind, all the keys are hard-coded.
In the end I found out about PHP's own thing: http://php.net/manual/en/book.oauth.php
Seemed cool because everything has 4 lines of code. The auth works and I can push stuff through the API, I just can't seem to send the image parameter though. This is the method: https://dev.twitter.com/docs/api/1/post/account/update_profile_background_image
I've found some examples that were using upload forms, but I have the photo already saved in a file, so how do I provide the, quote, base64-encoded image as raw multipart data?
$oauth->fetch
(
'https://api.twitter.com/1/account/update_profile_background_image.json',
array
(
'image' => '#' . $img_path . ';type=image/jpeg'
),
'POST'
);
Doesn't work, instead I get
Fatal error: Uncaught exception 'OAuthException' with message 'Invalid auth/bad request (got a 500, expected HTTP/1.1 20X or a redirect)'

You can encode the image like this:
<?php
$im = imagecreatefromjpeg('file.jpg');
$im_Data = base64_encode($im);
?>
Then you should be able to add $img_Data into the api call.

I don't know if it is an open issue yet but the "image" key must start with "#" too.
$oauth->fetch
(
'https://api.twitter.com/1/account/update_profile_background_image.json',
array
(
'#image' => '#' . $img_path . ';type=image/jpeg'
),
'POST'
);

In case anyone is interested I ended up using TmhOAuth in the end. Bloated but it did the job.
$image = array
(
"#$path",
'type=image/jpeg',
"filename=$name"
);
$params = array
(
'image' => implode(';', $image),
'use' => 'true'
);
// Request
$code = $tmhOAuth->request('POST', $tmhOAuth->url
(
'1/account/update_profile_background_image'
),
$params, true, true);

Related

Active Collab API: How to get projects

I'm trying out the ActiveCollab API for my first time. I had to use StackOveflow to figure out how to get the API token since the docs don't tell me this.
Below is my code:
/* GET INTENT */
$url = 'https://my.activecollab.com/api/v1/external/login';
$fields = array(
'email' => "email#email.com",
'password' => "****"
);
$intent = curl_post_connector($url, $fields);
$intent = $intent->user->intent;
/* GET TOKEN */
$url = 'https://app.activecollab.com/my_app_id/api/v1/issue-token-intent';
$fields = array(
'intent' => $intent,
'client_name' => 'My App Name',
'client_vendor' => 'My Company Name'
);
$token = curl_post_connector($url, $fields);
$token = $token->token;
Everything above works and get's the token properly. What I find really weird is that I have to use API v1 to get this, and the docs on ActiveCollab's site don't mention any URL for API v5. It seems like this is the approach everything is taking here on StackOverflow.
Now with the token, I try to get my list of projects:
/* GET PROJECT */
$url = 'https://app.activecollab.com/my_app_id/api/v1/users';
$headers = array (
"X-Angie-AuthApiToken" => $token
);
$projects = curl_get_connector($url, $headers);
var_dump($projects);
But this does not work. There is no error returned - it instead returns an array of languages for some reason! I don't want to paste the massive json object here, so instead I'll link you to a photo of it: https://www.screencast.com/t/7p5JuFB4Gu
UPDATE:
When attempting to use the SDK, it works up until I try getting the token (which is just as far as I got without the SDK). I'm getting Server Error 500, and when looking at the logs, it says:
/home/working/public_html/ac/index.php(21): ActiveCollab\SDK\Authenticator\Cloud->issueToken(123456789)
#1 {main}
thrown in /home/working/public_html/ac/SDK/Authenticator/Cloud.php on line 115
This is line 115 of Cloud.php:
throw new InvalidArgumentException("Account #{$account_id} not loaded");
I honestly don't think I did anything wrong... there must be something wrong with my account ID.
Just for kicks, I commented out that line, and the error disappears and the page loads fine - except now I have no token...

Generate thumbnail in php, posting to Azure Computer Vision API

I want to use Azure Computer Vision API to generate thumbnails for my Wordpress site. I'm trying to make it work in php with wp_remote_post, but i don't know how to parse the parameters ? It returns a thumbnail in really bad quality and default 500x500px. Any ideas on how to resolve this issue ?
function get_thumbnail($URL) //* * * * Azure Computer Vision API - v1.0 * * * *
{
$posturl='https://api.projectoxford.ai/vision/v1.0/generateThumbnail';
$request = wp_remote_post($posturl, array(
'headers' => array(
'Content-Type' => 'application/json',
'Ocp-Apim-Subscription-Key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'),
'body' => array('url' => $URL)
));
if ( is_wp_error( $request ) )
{
$error_message = $request->get_error_message();
return "Something went wrong: $error_message";
} else
{
return $request['body'];
}
}
EDIT 1
Thanks #Gary your right! Now the cropping is correct, but i got a huge problem with the quality! I'm using a trial but i see no info from Azure on downgrading the thumb quality for trial users. They are claiming to deliver high quality thumbnails, but if thats the standard it's totaly useless.
I must have overlooked something i guess?
Of course Gary, if i get no correct answer on my quality question i will close the thread with your answer as correct.
According the description of Get Thumbnail, the width,height and smartCropping should be set as request parameters which should combined in URL.
However the second args in wp_remote_post() do not accept the URL parameters and will do nothing on them. So you need to combine the url first before set into wp_remote_post().
You can try to use add_query_arg() to combine your url first,
$posturl='https://api.projectoxford.ai/vision/v1.0/generateThumbnail';
$posturl=add_query_arg( array(
'width' => 600,
'height' => 400,
'smartCropping' => true
), $posturl);

Plivo Rent a number Api not Working for me

require 'vendor/autoload.php';
use Plivo\RestAPI;
$auth_id = "My AUTH_ID";
$auth_token = "My AUTH_TOKEN";
$p = new RestAPI($auth_id, $auth_token);
$params = array(
'number' => '12512077502' # Phone number to buy
);
$response = $p->get_number($params);
print_r ($response);
It Will Give me Error Message
Array (
[status] => 404
[response] => Array (
[api_id] => 0b6214ee-aec4-11e5-ae4f-22000ac69a0d
[error] => not found
) )
See here https://www.plivo.com/docs/getting-started/phone-number-api/#rent-a-number
You seem to be using the wrong function (get_number) from the python helper library. The correct one is "buy_phone_number" function which uses PhoneNumber API.
Reference - https://github.com/plivo/plivo-python/blob/master/plivo.py#L175
I was using the Python plivo module and had the same problem.
From Plivo Support: "Use the new API: https://www.plivo.com/docs/api/number/phonenumber/#buy-number "
What I found that the the plivo module uses the wrong URL when renting a phone number. My work around is to make the call without the helper library. The following is Python code but it might help give you an idea what to do.
import requests
params = {
'number' : phone_number # Phone number to buy
}
host = 'https://api.plivo.com/v1/Account/%s/PhoneNumber/%s/' % \
(account_sid, phone_number)
r = requests.post(host, timeout=5, json=params, auth=(account_sid, auth_token))
assert r.status_code == 201, 'r.status_code=%s' % `r.status_code`
Update: The above might not be necessary after all. I just got an update from Plivo support. The new method name is buy_phone_number() instead of get_number(). That solved the problem for me. I assume the same is true for the PHP library.

twitter api (php) - statuses/destroy - returns nothing

I am using the tmOAuth library.
With the new 1.1 API, the following is returning an error code 400 - but authentication was done (same authentication for statuses works)! The library I am using works fine for all calls, except this one!
$tmhOAuth->request(
'POST', $tmhOAuth->url('https://api.twitter.com/1.1/statuses/destroy/MYIDHERE.json'),
array(
'id' => MYIDHERE
)
);
The twitter API documentation states that you don't have to send the id in post - but this doesn't make any difference.
I have tested this today with two different libraries, and neither work.
Any suggestions - does anyone know if there is an issue with it??
According to your comment, you have tested this in two libraries for the 1.1 API.
You haven't tested it in this one though. Instructions here, although you seem to already have your credentials in hand.
This basically proves that the library you are using has the issue, not the twitter API. So either submit a bug report on github (how else are they to know?), or use another library like the one above.
The exact code required using the above library (and it works, I just tested it):
// Require the library file
require_once('TwitterAPIExchange.php');
// Set up your credentials
$settings = array(
'oauth_access_token' => "YOUR_TOKEN",
'oauth_access_token_secret' => "YOUR_TOKEN_SECRET",
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
// Put the correct ID in the URL
$url = 'https://api.twitter.com/1.1/statuses/destroy/YOURIDHERE.json';
// Set the request type
$requestMethod = 'POST';
// Set the post fields
$postfields = array('id' => 'YOURIDHERE');
// Make the request
$twitter = new TwitterAPIExchange($settings);
$json = $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
// Dump the response
$result = json_decode($json);
var_dump($result);
If you're using the twitteroauth php library from Abraham Williams and trying to delete old tweets/retweets you need to construct the post() query as such:
$response = $connection->post('statuses/destroy/'.$tweetID, array()); //Curl url output = statuses/destroy/$tweetID.json

ZF2 SOAP "Procedure not present" Error

I'm having serious trouble to solve this issue. I got an APP with 3 modules that got different services to provide by SOAP. What happens is that 2 of them are getting this response:
SoapFault
File:
/var/www/empreendimentos/vendor/zendframework/zendframework/library/Zend/Soap/Client.php:10
Message:
Procedure not present
I already double checked, and the names of the functions are right and I use the method getFunctions. This is the return from getFunctions():
array
0 => string 'Array getCliAll(anyType $filter)' (length=32)
1 => string 'Array insertCli(anyType $data)' (length=30)
2 => string 'Array editCli(anyType $data, anyType $id)' (length=41)
3 => string 'void setServiceLocator(anyType $serviceLocator)' (length=47)
4 => string 'void getServiceLocator()' (length=24)
My handle methods look like this:
public function handleWSDL() {
$autodiscover = new AutoDiscover();
$autodiscover->setClass('\Cli\Service\CliService');
$autodiscover->setUri($this->_URI);
$wsdl = $autodiscover->generate();
$wsdl = $wsdl->toDomDocument();
// geramos o XML dando um echo no $wsdl->saveXML()
echo $wsdl->saveXML();
}
public function handleSOAP() {
$soap = new \Zend\Soap\Server($this->_WSDL_URI);
$soap->setWSDLCache(false);
$classHandle = new CliService();
$classHandle->setServiceLocator($this->getServiceLocator());
$soap->setClass($classHandle);
$soap->handle();
}
I get no errors on the server side. Only this response for all the methods. What is wrong?
UPDATE:
Turns out it's a "Problem" of the ZF2 config. overload. I had my modile.config.php to hold my WSDL and URI information, but used the same label for the config on the file. The overload was making every WSDL and URI the same, and giving me the problem.
Like this:
Emp Module modile.config.php
'service_url' => array(
"wsdl" => 'http://localhost/empreendimentos/public/emp/service?wsdl',
"return" => 'http://localhost/empreendimentos/public/emp/service',
),
Emp Module modile.config.php
'service_url' => array(
"wsdl" => 'http://localhost/empreendimentos/public/cli/service?wsdl',
"return" => 'http://localhost/empreendimentos/public/cli/service',
),
Anyone know why this is like this? is it suposed to mix module configs?
Had this problem yesterday, found the answer was in the server wsdl call.
The server calls its own wsdl to introspect the available methods. If your wsdl url is wrong, it sees what methods are available in another server and says 'Procedure not present'.
In my case the AdmintoolsController had the line
$wsdl_url = 'http://' . $_SERVER['HTTP_HOST'] . '/news/?wsdl';
so it was looking in the News service for the method.
Change it to
$wsdl_url = 'http://' . $_SERVER['HTTP_HOST'] . '/admintools/?wsdl';
and it works fine.
I searched Google for hours looking for this fix, and my colleague looked at the code and spotted it straight away.
Hope this helps
John
Also try to do the below changes and then check if it works:
Remove the files starting with "wsdl-" in the tmp folder of your zend server.
Make a php setting: phpSettings.soap.wsdl_cache_enabled = 0 in your application.ini file.

Categories