oAuth signature creation issue with PHP (posting photoset to Tumblr) - php

I've made a simple script that posts images on tumblr.
everything is fine, but I've noticed some performance issues right after I've changed the host provider (my new host is limited and cheaper).
now, after debugging the script and after contacting the tumblr api helpdesk, I'm stuck on a problem:
there are 3 functions:
function oauth_gen($method, $url, $iparams, &$headers) {
$iparams['oauth_consumer_key'] = CONSUMER_KEY;
$iparams['oauth_nonce'] = strval(time());
$iparams['oauth_signature_method'] = 'HMAC-SHA1';
$iparams['oauth_timestamp'] = strval(time());
$iparams['oauth_token'] = OAUTH_TOKEN;
$iparams['oauth_version'] = '1.0';
$iparams['oauth_signature'] = oauth_sig($method, $url, $iparams);
$oauth_header = array();
foreach($iparams as $key => $value) {
if (strpos($key, "oauth") !== false) {
$oauth_header []= $key ."=".$value;
}
}
$str = print_r($iparams, true);
file_put_contents('data1-1.txt', $str);
$oauth_header = "OAuth ". implode(",", $oauth_header);
$headers["Authorization"] = $oauth_header;
}
function oauth_sig($method, $uri, $params) {
$parts []= $method;
$parts []= rawurlencode($uri);
$iparams = array();
ksort($params);
foreach($params as $key => $data) {
if(is_array($data)) {
$count = 0;
foreach($data as $val) {
$n = $key . "[". $count . "]";
$iparams []= $n . "=" . rawurlencode($val);
//$iparams []= $n . "=" . $val;
$count++;
}
} else {
$iparams[]= rawurlencode($key) . "=" .rawurlencode($data);
}
}
//debug($iparams,"iparams");
$str = print_r($iparams, true);
file_put_contents('data-1.txt', $str);
//$size = filesize('data.txt');
$parts []= rawurlencode(implode("&", $iparams));
//debug($parts,"parts");
//die();
$sig = implode("&", $parts);
return base64_encode(hash_hmac('sha1', $sig, CONSUMER_SECRET."&". OAUTH_SECRET, true));
}
these 2 functions above comes from an online functional example, they have always worked fine.
this is the function I use to call the APIs and the oAuth:
function posta_array($files,$queue,$tags,$caption,$link,$blog){
$datArr = array();
$photoset_layout = "";
foreach ($files as $sing_file){
$dataArr [] = file_get_contents($sing_file);
$photoset_layout .= "1";
}
$headers = array("Host" => "http://api.tumblr.com/", "Content-type" => "application/x-www-form-urlencoded", "Expect" => "");
$params = array(
"data" => $dataArr,
"type" => "photo",
"state" => $queue,
"tags"=>$tags,
"caption"=>$caption,
"photoset_layout" => $photoset_layout,
"link"=>str_replace("_","",$link)
);
debug($headers,"head");
oauth_gen("POST", "http://api.tumblr.com/v2/blog/$blog/post", $params, $headers);
debug($headers,"head 2");
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Tumblr v1.0");
curl_setopt($ch, CURLOPT_URL, "http://api.tumblr.com/v2/blog/$blog/post");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Authorization: " . $headers['Authorization'],
"Content-type: " . $headers["Content-type"],
"Expect: ")
);
$params = http_build_query($params);
$str = print_r($params, true);
file_put_contents('data_curl1.txt', $str);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
debug($response,"response");
return $response;
}
this is the function with some problems, I try to explain:
I called the oauth_gen passing the parameters array to it, the oauth_gen creates the oauth header that I later used here: "Authorization: " . $headers['Authorization'],.
As I stated, everything is working smoothly, until I have tried to post a gif photoset of 6 files for a total of 6Mb (tumblr permit 2Mb each file and 10Mb total).
PHP runs out of memory and return an error, here it starts my debugging, after a while I contacted the tumblr api helpdesk, and they answer in this way:
You shouldn't need to include the files in the parameters used for
generating the oauth signature. For an example of how this is done,
checkout one of our official API clients.
This changes everything. Untill now, I passed the entire parameters array to the oauth_gen, which, calling the oauth_sig, will rawencode everything into the array (binary strings of gif files inlcuded), with a result of a binary file of about 1Mb becomes at least 3Mb of rawurlencoded string.
and that's why I had memory issues. Nice, so, as the helpdesk say, I've changed the call to the oauth_gen in this way:
$new_array = array();
oauth_gen("POST", "http://api.tumblr.com/v2/blog/$blog/post", $new_array, $headers);
seams legit to me, I passed a new array to the function, the function then generate the oAuth, the headers are passed back and I can use them into the posting call, the result was:
{"meta":{"status":401,"msg":"Unauthorized"},"response":[]}
asking more to tumblr api helpdesk leads only to more links to their documentation and their "tumblr php client" which I can't use, so it isn't a option.
Does anyone has experience with oAuth and can explain me what I'm doing wrong? as far as I understand, the trick is into the encrypted data the oauth_sig create, but I can't figure out how to proceed.
I really want to understand the oauth, but more I read about it and more the tumblr helpdsek seams right to me, but... the solution doesn't work, and works only if I let the oauth function to encrypt the entire data array (with the images and everything) but I can understand that this is wrong... help me.
UPDATE 1
I've tried a new thing today, first I created the empty array, then passed by reference to the oauth_genand only after generating the signature, I've added to the same array all the other fields about the post itself, but the result is the same.
UPDATE 2
reading here: http://oauth.net/core/1.0a/#signing_process
seems that the parameters of the request must all be used for the signature, but this is not totally clear (if someone could explain it better, I really appreciate).
this is weird, because if it's true, it go against the words of the Tumblr help desk, while if it's not true, there is a little confusion in the whole process.
by the way, at this time, I'm stile struck in the same point.

After digging couple of hours into the issue, debugging, reviewing tumblr api and api client, registering a test account and trying to post some images. The good news is finally I come up with a solution. It is not using a native CURL only, you need guzzle and an OAuth library to sign the requests.
Tumblr guys are correct about signing the request. You don't need to pass image data to sign the request. If you check their official library you can see; https://github.com/tumblr/tumblr.php/blob/master/lib/Tumblr/API/RequestHandler.php#L85
I tried to fix the issue with native CURL library but unfortunately I was not successful, either I was signing the request in a wrong way or missing something in the request header, data etc. I don't know actually, Tumblr api is really bad at informing you what you are doing wrong.
So I cheated a little bit and start to read Tumblr api client code, and I come up with a solution.
Here we go, first you need two packages.
$ composer require "eher/oauth:1.0.*"
$ composer require "guzzle/guzzle:>=3.1.0,<4"
And then the PHP code, just define your keys, tokens, secrets etc. Then it should be good to go.
Since the signing request does not include picture data, it is not exceeding memory limit. After signing the request actually we are not getting the contents of the files into our post data array. We are using addPostFiles method of guzzle, which takes care of file addition to POST request, does the dirty work for you. And here is the result for me;
string(70) "{"meta":{"status":201,"msg":"Created"},"response":{"id":143679527674}}"
And here is the url;
http://blog-transparentcoffeebouquet.tumblr.com/
<?php
ini_set('memory_limit', '64M');
define("CONSUMER_KEY", "");
define("CONSUMER_SECRET", "");
define("OAUTH_TOKEN", "");
define("OAUTH_SECRET", "");
function request($options,$blog) {
// Take off the data param, we'll add it back after signing
$files = isset($options['data']) ? $options['data'] : false;
unset($options['data']);
$url = "https://api.tumblr.com/v2/blog/$blog/post";
$client = new \Guzzle\Http\Client(null, array(
'redirect.disable' => true
));
$consumer = new \Eher\OAuth\Consumer(CONSUMER_KEY, CONSUMER_SECRET);
$token = new \Eher\OAuth\Token(OAUTH_TOKEN, OAUTH_SECRET);
$oauth = \Eher\OAuth\Request::from_consumer_and_token(
$consumer,
$token,
"POST",
$url,
$options
);
$oauth->sign_request(new \Eher\OAuth\HmacSha1(), $consumer, $token);
$authHeader = $oauth->to_header();
$pieces = explode(' ', $authHeader, 2);
$authString = $pieces[1];
// POST requests get the params in the body, with the files added
// and as multipart if appropriate
/** #var \Guzzle\Http\Message\RequestInterface $request */
$request = $client->post($url, null, $options);
$request->addHeader('Authorization', $authString);
if ($files) {
if (is_array($files)) {
$collection = array();
foreach ($files as $idx => $f) {
$collection["data[$idx]"] = $f;
}
$request->addPostFiles($collection);
} else {
$request->addPostFiles(array('data' => $files));
}
}
$request->setHeader('User-Agent', 'tumblr.php/0.1.2');
// Guzzle throws errors, but we collapse them and just grab the
// response, since we deal with this at the \Tumblr\Client level
try {
$response = $request->send();
} catch (\Guzzle\Http\Exception\BadResponseException $e) {
$response = $request->getResponse();
}
// Construct the object that the Client expects to see, and return it
$obj = new \stdClass;
$obj->status = $response->getStatusCode();
$obj->body = $response->getBody();
$obj->headers = $response->getHeaders()->toArray();
return $obj;
}
$files = [
"/photo/1.jpg",
"/photo/2.jpg",
"/photo/3.png",
"/photo/4.jpg",
"/photo/1.jpg",
"/photo/2.jpg",
"/photo/3.png",
"/photo/4.jpg",
"/photo/1.jpg",
"/photo/2.jpg",
];
$params = array(
"type" => "photo",
"state" => "published",
"tags"=> [],
"caption"=>"caption",
"link"=>str_replace("_","","http://stackoverflow.com/questions/36747697/oauth-signature-creation-issue-with-php-posting-photoset-to-tumblr"),
"data" => $files,
);
$response = request($params, "blog-transparentcoffeebouquet.tumblr.com");
var_dump($response->body->__toString());

Related

Pass whole incoming data to curl - Laravel

I wanted to pass the whole incoming data (that is, $request) to the curl not wanted to post to a particular field in the endpoint as subjectId=>1 as am running this curl request for different endPoint everytime. The below curl request will work if CURLOPT_URL => $url . $subjectId, was given. As my input changes for every end point, i've to pass everything that comes in the input to the curl , i can't pass it as an arary $subjectId. Is there any way to do this?
Currently, dd($Response); returns null
Am giving a postman input like this:
{
"subjectId":"1"
}
Curl
public function getContentqApiPost(Request $request)
{
$token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ey";
$headers = [
"Accept: application/json",
"Authorization: Bearer " . $token
];
$url="http://127.0.0.1:9000/api/courses/course-per-subject";
$subjectId = "?subjectId=$request->subjectId";
$ch = curl_init();
$curlConfig = array(
// CURLOPT_URL => $url . $subjectId,
CURLOPT_URL => $url . $request,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt_array($ch, $curlConfig);
$result = trim(curl_exec($ch));
$Response = json_decode($result, true);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
echo $error_msg;
}
curl_close($ch);
return $Response;
}
If you would like to pass all params of $request to curl:
$queryParams = '';
$delimeter = '?';
foreach($request->all() as $k => $v){
$queryParams .= "$delimeter$k=$v";
$delimeter = '&';
}
Also You can only pass the params you want:
foreach($request->only(['subjectId']) as $k => $v){
// code here
}
Finally you have:
CURLOPT_URL => $url . $queryParams,
Answer
Assuming you want to pass the entire GET query string as-is:
$query_string = str_replace($request->url(), "", $request->fullUrl());
$url = "http://localhost:9000/api/courses/course-per-subject" . $query_string;
This works because $request->url() returns the URL without the query string parameters, while $request->fullUrl() returns the URL with all the query string parameters, so we can use str_replace with an empty replacement to remove the non-query part. Note that $query_string will already start with a ? so there is no need to add that yourself.
Other suggestions
Unless your Laravel API is a 1:1 copy of the backend API, I strongly suggest writing a class that interfaces with the backend API, then provide it to your Laravel controllers using dependency injection. E.g.
class CourseCatalogApi {
public function getSubjectsInCourse(String $course){
... // your curl code here
}
}
Finally, since you are already using Laravel, there is no need to write such low level code using curl to make HTTP requests. Consider using guzzlehttp, which is already a dependency of Laravel.

Posting to Tumblr with php & Tumblr API

I am trying to post messages automatically to my Tumblr Blog (which will run daily via Cron)
I am using the Official Tumblr PHP library here:
https://github.com/tumblr/tumblr.php
And using the Authentication method detailed here :
https://github.com/tumblr/tumblr.php/wiki/Authentication
(or parts of this, as I don't need user input!)
I have the below code
require_once('vendor/autoload.php');
// some variables that will be pretttty useful
$consumerKey = 'MY-CONSUMER-KEY';
$consumerSecret = 'MY-CONSUMER-SECRET';
$client = new Tumblr\API\Client($consumerKey, $consumerSecret);
$requestHandler = $client->getRequestHandler();
$blogName = 'MY-BLOG-NAME';
$requestHandler->setBaseUrl('https://www.tumblr.com/');
// start the old gal up
$resp = $requestHandler->request('POST', 'oauth/request_token', array());
// get the oauth_token
$out = $result = $resp->body;
$data = array();
parse_str($out, $data);
// set the token
$client->setToken($data['oauth_token'], $data['oauth_token_secret']);
// change the baseURL so that we can use the desired Methods
$client->getRequestHandler()->setBaseUrl('http://api.tumblr.com');
// build the $postData into an array
$postData = array('title' => 'test title', 'body' => 'test body');
// call the creatPost function to post the $postData
$client->createPost($blogName, $postData);
However, this gives me the following error:
Fatal error: Uncaught Tumblr\API\RequestException: [401]: Not
Authorized thrown in
/home///*/vendor/tumblr/tumblr/lib/Tumblr/API/Client.php
on line 426
I can retrieve blog posts and other data fine with (example):
echo '<pre>';
print_r( $client->getBlogPosts($blogName, $options = null) );
echo '</pre>';
So it seems it is just making a post that I cant manage.
In all honesty, I don't really understand the OAuth Authentication, so am using code that more worthy coders have kindly provided free :-)
I assume I am OK to have edited out parts of the https://github.com/tumblr/tumblr.php/wiki/Authentication as I don't need user input as this is just going to be code ran directly from my server (via Cron)
I have spent days looking around the internet for some answers (have gotten a little further), but am totally stuck on this one...
Any advice is much appreciated!
It looks like the parts that you removed in the code pertained to a portion of the OAuth process that was necessary for the desired action.
// exchange the verifier for the keys
You might try running the Authentication Example itself and removing the parts of the code that you've removed until it no longer works. This will narrow down what's causing the issue. I'm not very familiar with OAuth personally, but this looks as though it would be apart of the problem as one of the main portions you took out was surrounding the OAuth process exchanging the verifier for the OAuth keys.
function upload_content(){
// Authorization info
$tumblr_email = 'email-address#host.com';
$tumblr_password = 'secret';
// Data for new record
$post_type = 'text';
$post_title = 'Host';
$post_body = 'This is the body of the host.';
// Prepare POST request
$request_data = http_build_query(
array(
'email' => $tumblr_email,
'password' => $tumblr_password,
'type' => $post_type,
'title' => $post_title,
'body' => $post_body,
'generator' => 'API example'
)
);
// Send the POST request (with cURL)
$c = curl_init('api.tumblr.com/v2/blog/gurjotsinghmaan.tumblr.com/post');
//api.tumblr.com/v2/blog/{base-hostname}/post
//http://www.tumblr.com/api/write
//http://api.tumblr.com/v2/blog/{base-hostname}/posts/text?api_key={}
curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, $request_data);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($c);
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
// Check for success
if ($status == 201) {
echo "Success! The new post ID is $result.\n";
} else if ($status == 403) {
echo 'Bad email or password';
} else {
echo "Error: $result\n";
}
}
https://howtodofor.com/how-to-delete-tumblr-account/

Google Services OAuth requests returns HTTP 400 Bad Request Error

I'm trying to build a basic app where I can modify my own google calendar using Google's RESTful api, but I'm having trouble getting the oAuth token. I've chosen to do it using the Services Application oAuth flow - I don't want to have to constantly re-agree to letting my own app use my calendar, but if there's a better way to do this please let me know.
Every time I make the http request I get a Bad Request error. Any ideas/help?
Here's the code:
<?php
$payload = array(
"iss"=>"services client email",
"scope"=>"https://www.googleapis.com/auth/calendar",
"aud"=>"https://accounts.google.com/o/oauth2/token",
"iat"=>date("U"),
"exp"=>date("U")+3600
);
$key = "Simple API key";
$jwt = encode_header($payload,$key);
print_r(request_g_token($jwt));
function request_g_token($jwt)
{
$data = array(
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt
);
$data = http_build_query($data);
$url = "https://accounts.google.com/o/oauth2/token";
//echo $data;
$opts = array('http' =>
array(
'protocol_version' => '1.1',
'method' => 'POST',
'header' => "Host: accounts.google.com\r\n" .
"Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $data
)
);
$context = stream_context_create($opts);
return (file_get_contents($url, false, $context));
}
function urlsafeb64encode($input){
return str_replace('=','',strtr(base64_encode($input),'+/','-_'));
}
function encode_header($payload, $key, $algo = 'RS256'){
$header = array('typ' => 'JWT', 'alg' => $algo);
$segments = array();
$segments[] = urlsafeb64encode(json_encode($header));
$segments[] = urlsafeb64encode(json_encode($payload));
$signing_input = implode('.',$segments);
$sig = sign_encode($signing_input,$key);
$segments[]=urlsafeb64encode($sig);
return implode('.',$segments);
}
function sign_encode($msg, $key){
return hash_hmac('sha256', $msg, $key, true);
}
?>
Any help would be greatly appreciated
UPDATE
So I went through the service process again and realized I need to use a private key, which I'm now doing. My major question is whether or not to include the "private-key.p12" part of what I downloaded from google or not. I'm still receiving a Bad Request error unfortunately...
UPDATE 2
Realized I needed to pull the key from the pk12 file, and I did so with this code:
function getKey($file){
$p12cert = array();
$fd = fopen($file, 'r');
$p12buf = fread($fd,filesize($file));
fclose($fd);
if ( openssl_pkcs12_read($p12buf, $p12cert, 'notasecret') )
{
//worked
$temp = $p12cert['pkey'];
$temp = str_replace("-----BEGIN PRIVATE KEY-----","",$temp);
$temp = str_replace("-----END PRIVATE KEY-----","",$temp);
return $temp;
}
else
{
//failed
return "failed";
}
}
However, it's still giving me a bad request error and I think it's to do with the fact that the key comes back in multiple lines. Any ideas?
For anyone experiencing this issue, I've basically come to the conclusion that google hasn't interfaced calendar with their service accounts yet, and am using a refresh token to achieve similar results without having to log in all the time.

Retrieve Amazon MWS Response using php5.2 apis

I have some trouble to get a simple xml answer from Amazon, it reports me always:
Sender
InvalidParameterValue
Either Action or Operation query parameter must be present.
And if I ask their Support, they can't help me they dont see the missing Parameter...
Their suggestion is follow their Examples, but my Webhost only supports php 5.2, so the autoloader doesn't work.
<?php
#header("Content-Type:text/xml");
$sellerID = 'SELLEDERID';
$aws = 'AWSKEY';
$secret = 'SECRET';
$action = 'GetReportList';
$timestamp = gmdate("Y-m-d\TH:i:s\Z");
$signature = $action . $timestamp;
$sig = base64_encode(hash_hmac("sha256", $signature, $secret, true));
$service = 'https://mws.amazonservices.com/?';
$url = 'AWSAccessKeyId='.$aws;
$url .= '&Action='.$action;
$url .= '&Merchant='.$sellerid;
$url .= '&SignatureVersion=2';
$url .= '&Timestamp=2013-01-10T12:22:48Z';
$url .= '&Version=2009-01-01';
$url .= '&Signature='.$sig;
$url .= '&SignatureMethod=HmacSHA256';
$awsURL = $service.urlencode($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $awsURL,
CURLOPT_USERAGENT => 'Request'
));
$resp = curl_exec($curl);
curl_close($curl);
echo "<pre>";
var_dump($resp);
var_dump($awsURL);
echo "</pre>";
?>
The "we see no error in your request" probably referred to the request you put into Scratchpad, and not to the request you made through php, because your signature calculation is way off.
See this StackOverflow question or the MWS Developers Guide (page 12, "If you create your own client library") on how to calculate the sig.
The actual error message seems weird. I expect it to change once you've got your signature right. Please also note that quite a few MWS API calls require a HTTP POST, so if you intend to reuse that code in other places you're probably better off changing your code accordingly.

writing cURL like function in a rails app

I'm trying to convert this PHP cURL function to work with my rails app. The piece of code is from an SMS payment gateway that needs to verify the POST paramters. Since I'm a big PHP noob I have no idea how to handle this problem.
$verify_url = 'http://smsgatewayadress';
$fields = '';
$d = array(
'merchant_ID' => $_POST['merchant_ID'],
'local_ID' => $_POST['local_ID'],
'total' => $_POST['total'],
'ipn_verify' => $_POST['ipn_verify'],
'timeout' => 10,
);
foreach ($d as $k => $v)
{
$fields .= $k . "=" . urlencode($v) . "&";
}
$fields = substr($fields, 0, strlen($fields)-1);
$ch = curl_init($verify_url); //this initiates a HTTP connection to $verify_url, the connection headers will be stored in $ch
curl_setopt($ch, CURLOPT_POST, 1); //sets the delivery method as POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); //The data that is being sent via POST. From what I can see the cURL lib sends them as a string that is built in the foreach loop above
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //This verifies if the target url sends a redirect header and if it does cURL follows that link
curl_setopt($ch, CURLOPT_HEADER, 0); //This ignores the headers from the answer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //This specifies that the curl_exec function below must return the result to the accesed URL
$result = curl_exec($ch); //It ransfers the data via POST to the URL, it gets read and returns the result
if ($result == true)
{
//confirmed
$can_download = true;
}
else
{
//failed
$can_download = false;
}
}
if (strpos($_SERVER['REQUEST_URI'], 'ipn.php'))
echo $can_download ? '1' : '0'; //we tell the sms sever that we processed the request
I've googled a cURL lib counterpart in Rails and found a ton of options but none that I could understand and use in the same way this script does.
If anyone could give me a hand with converting this script from php to ruby it would be greatly appreciated.
The most direct approach might be to use the Ruby curb library, which is the most straightforward wrapper for cURL. A lot of the options in Curl::Easy map directly to what you have here. A basis might be:
url = "http://smsgatewayadress/"
Curl::Easy.http_post(url,
Curl::PostField.content('merchant_ID', params[:merchant_ID]),
# ...
)

Categories