I'm trying to post a message with an image to Twitter through PHP and cURL. It's working for the message but I don't know how to add the image to it.
From the documentation:
Unlike POST statuses/update, this method
expects raw multipart data. Your POST request's Content-Type should be
set to multipart/form-data with the media[] parameter
This is the PHP:
<?php
class Tweet {
public $url = 'https://api.twitter.com/1.1/statuses/update_with_media.json';
function the_nonce(){
$nonce = base64_encode(uniqid());
$nonce = preg_replace('~[\W]~','',$nonce);
return $nonce;
}
function get_DST($status){
$url = $this->url;
$consumer_key = "[removed]";
$nonce = $this->the_nonce();
$sig_method = 'HMAC-SHA1';
$timestamp = time();
$version = "1.0";
$token = "[removed]";
$access_secret = "[removed]";
$consumer_secret = "[removed]";
$param_string = 'oauth_consumer_key='.$consumer_key.
'&oauth_nonce='.$nonce.
'&oauth_signature_method='.$sig_method.
'&oauth_timestamp='.$timestamp.
'&oauth_token='.$token.
'&oauth_version='.$version.
'&status='.rawurlencode($status);
$sig_base_string = 'POST&'.rawurlencode($url).'&'.rawurlencode($param_string);
$sig_key = rawurlencode($consumer_secret).'&'.rawurlencode($access_secret);
$tweet_sig = base64_encode(hash_hmac('sha1', $sig_base_string, $sig_key, true));
$DST = 'OAuth oauth_consumer_key="'.rawurlencode($consumer_key).'",'.
'oauth_nonce="'.rawurlencode($nonce).'",'.
'oauth_signature="'.rawurlencode($tweet_sig).'",'.
'oauth_signature_method="HMAC-SHA1",'.
'oauth_timestamp="'.rawurlencode($timestamp).'",'.
'oauth_token="'.rawurlencode($token).'",'.
'oauth_version="1.0"';
return $DST;
}
function set($status){
$url = $this->url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: ' . $this->get_DST($status)));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'status='.rawurlencode($status));
curl_setopt($ch, CURLOPT_URL, $url);
$result = json_decode(curl_exec($ch));
$resultString = print_r($result,true);;
curl_close($ch);
}
$status->set("hello");
?>
How to add the media[] part to it?
not sure if Matt Harris' library would do for you, but the code is rather simple
require_once ('your_app_tokens.php');
require_once ('tmhOAuth.php');
$connection = new tmhOAuth(array(
'consumer_key' => $consumer_key,
'consumer_secret' => $consumer_secret,
'user_token' => $user_token, //stored in session or whatever else
'user_secret' => $User_secret
));
$message ="test";
$image = "image.jpg"; // must be in the same directory
$extension = "jpg";
$post = $connection->request(
'POST',
'https://api.twitter.com/1.1/statuses/update_with_media.json',
array(
'media[]' => "#{$image};type=image/{$extension};filename={$image}",
'status' => $message
),
true,
true
);
$code = $connection->response;
//if the code is 200 it's all fine
i've created a script that allows you to post a tweet with image. I'm using the php fonction that used an url to upload the image to your server. After that, it upload from your server to the twitter one. You got an image ID that you can use to send a tweet with a picture.
Here is my github projet. Everything is inside, easy to used and install.
https://github.com/florianchapon/twitter-poster
Related
What is wrong?
This is all my code, I think that it should be fine, but I don't know why... with postman I haven't errors and I receive the tokens while with Curl I receive this error. I'm working in local with Mamp pro.
The error received is:
My Code To generete the Signature and get the Token:
$url = "https://account.api.here.com/oauth2/token";
$data = array(
"grant_type" => "client_credentials"
);
$oauthNonce = mt_rand();
$oauthTimestamp = time();
$oauthCustomereKey = "******";
$oauthSignatureMethod = "HMAC-SHA256";
$httpMethod = "POST";
$oauthVersion = "1.0";
$keySecret = "*****";
$baseString = $httpMethod."&". urlencode($url);
$paramString =
"grant_type=client_credentials&".
"oauth_consumer_key=". urlencode($oauthCustomereKey).
"&oauth_nonce=". urlencode($oauthNonce).
"&oauth_signature_method=". urlencode($oauthSignatureMethod).
"&oauth_timestamp=". urlencode($oauthTimestamp).
"&oauth_version=". urlencode($oauthVersion)
;
$baseString = $baseString . "&" . urlencode($paramString);
var_dump($baseString);
$signingKey= urlencode($keySecret) . "&";
$signature = urlencode(
base64_encode(
hash_hmac(
'sha256',
$baseString,
$signingKey,
true
)
)
);
$params = [
"oauth_consumer_key" => $oauthCustomereKey,
"oauth_nonce" => $oauthNonce,
"oauth_signature_method" => $oauthSignatureMethod,
"oauth_timestamp" => $oauthTimestamp,
"oauth_version" => $oauthVersion,
"oauth_signature" => $signature
];
// $lol = 'oauth_consumer_key="' . $oauthCustomereKey . '",oauth_signature_method="'.$oauthSignatureMethod . '",oauth_timestamp="'.$oauthTimestamp.'",oauth_nonce="'.$oauthNonce.'",oauth_version="'.$oauthVersion.'",oauth_signature="'.$signature.'"';
/* This will give you the proper encoded string to include in your Authorization header */
$params = http_build_query($params, null, ',', PHP_QUERY_RFC3986);
$authorization = "Authorization: OAuth " . $params;
var_dump($authorization);
if(!$curl = curl_init()){
exit;
}
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-Type : application/x-www-form-urlencoded",
$authorization));
$token = curl_exec($curl);
curl_close($curl);
return $token;
Result basestring (dump on line 87):
string(253) "POST&https%3A%2F%2Faccount.api.here.com%2Foauth2%2Ftoken&grant_type%3Dclient_credentials%26oauth_consumer_key%3D********%26oauth_nonce%3D1468397107%26oauth_signature_method%3DHMAC-SHA256%26oauth_timestamp%3D1605523226%26oauth_version%3D1.0"
And on the doc here we have this example... it look the same:
POST
&https%3A%2F%2Faccount.api.here.com%2Foauth2%2Ftoken
&grant_type=client_credentials%26oauth_consumer_key%3Daccess-key-id-1234%26oauth_nonce%3DLIIpk4%26
oauth_signature_method%3DHMAC-SHA256%26oauth_timestamp%3D1456945283%26oauth_version%3D1.0
FIXED
Finally... after 2 days...
There are 2 errors on the code above:
The parameter $data to CURLOPT_POSTFIELDS
Oauth 1.0 wants the double quotes.
So change:
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
With
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
This is strange for me, because with curl I use http_build_query with GET request and not POST, where we can use $data directly like array.
And delete:
$params = http_build_query($params, null, ',', PHP_QUERY_RFC3986);
And write the query with your beautifuls hand because $params doesn't have double quote.
I get JSON from the Soundcloud API by using code in section【A】.
But I want to get it without using $type, like in code【B】.
In other words, I want to get that information by only giving $target.
What should I do?
$r = soundcloud_responce();
var_dump( $r );
function soundcloud_responce(){
$client_id = 'xxx';
$type = 'tracks';
$q = 'words';
// code【A】
// If I have $type, So this process ok.
$url = "https://api.soundcloud.com/";
$url .= $type;
$url .= "?client_id=$client_id";
$url .= "&q=$q";
// code【B】
// I want to do same process with $target but without $type
$target = "https://soundcloud.com/accountname/trackname";
$target = str_replace('https://soundcloud.com/', '', $target);
$url = "https://api.soundcloud.com/";
$url .= $target;
$url .= "?client_id=$client_id";
// curl
$ch = curl_init();
$headers = [
'Accept: application/json',
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
$json = json_decode($res);
curl_close($ch);
return $json;
}
(Add 2020-02-21-09:38 #Tokyo)
I tried this code【C】but this also failed.
// code【C】
// I tried with oembed but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = 'http://soundcloud.com/oembed?format=json&url='.$target;
(Add 2020-02-21-10:12 #Tokyo)
I tried this code【D】but this also failed.
// code【D】
// I tried with resolve but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = "https://api.soundcloud.com/resolve?url=$target&client_id=$client_id";
I tried this code【E】this is successful!
Thank you for giving me good advice, #showdev.
// code【E】
// this is successful!
$target = "https://soundcloud.com/accountname/trackname";
$target = urlencode($target);
$url = "https://api.soundcloud.com/resolve.json?url=$target&client_id=$client_id";
I'm using PHP to config a webhook for a BOT.
I'd like to send picture from another server.
I've tried this way
function bot1($chatID,$sentText) {
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$this->sendPhoto($botUrl,$chatID,$img);
}
function sendPhoto($botUrl,$chatID, $img){
$this->sendMessage($botUrl,$chatID,'This is the pic'.$chatID);
$this->sendPost($botUrl,"sendPhoto",$chatID,"photo",$img);
}
function sendMessage($botUrl,$chatID, $text){
$inserimento = file_get_contents($botUrl."/sendMessage?chat_id=".$chatID."&text=".$text."&reply_markup=".json_encode(array("hide_keyboard"=>true)));
}
function sendPost($botUrl,$function,$chatID,$type,$doc){
$response = $botUrl. "/".$function;
$post_fields = array('chat_id' => $chatID,
$type => new CURLFile(realpath($doc))
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
}
But I receive only the message.
What is the problem?
I've tried to change in http but the problem persists
Well, I've done a workaround because my cUrl version seems to have a bug in uploading file.
Now I use Zend FW
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$realpath = realpath($doc);
$url = $botUrl . "/sendPhoto?chat_id=" . $chatID;
$client = new Zend_Http_Client();
$client->setUri($url);
$client->setFileUpload($realpath, "photo");
$client->setMethod('POST');
$response = $client->request();
You have to send a file, not a URL.
So:
function bot1( $chatID,$sentText )
{
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$data = file_get_contents( $img ); # <---
$filePath = "/Your/Local/FilePath/Here"; # <---
file_put_contents( $data, $filePath ); # <---
$this->sendPhoto( $botUrl, $chatID, $filePath ); # <---
}
This is as raw example, without checking success of file_get_contents().
In my bot I use this schema, and it works fine.
I have the script below written in Ruby. I was wondering is anyone can help me convert it to PHP. I know this is a big ask. I am looking to convert the ruby script to a PHP curl request.
See the link to the documentation https://www.sinch.com/docs/rest-apis/api-documentation/#applicationsignedrequest
The first code is the SAMPLE ruby script. While the second below it is what i have attempted to write in PHP on my own. Without success because i get "Invalid signature error".
require "base64"
require "openssl"
require "time"
require "net/http"
require "uri"
require "json"
to = "+4412345678"
message = "Test sms message"
key = "wwwwwwwwwxxxxxxxx" //Key as supplied by sinch.com
secret = "zzzzzzzyyyyyyyyy" // Secret as supplied by sinch.com
body = "{\"message\":\"" + message + "\"}"
timestamp = Time.now.iso8601
http_verb = "POST"
path = "/v1/sms/" + to
scheme = "Application"
content_type = "application/json"
digest = OpenSSL::Digest.new('sha256')
canonicalized_headers = "x-timestamp:" + timestamp
content_md5 = Base64.encode64(Digest::MD5.digest(body.encode("UTF-8"))).strip
string_to_sign = http_verb + "\n" + content_md5 + "\n" + content_type + "\n" + canonicalized_headers + "\n" + path
signature = Base64.encode64(OpenSSL::HMAC.digest(digest, Base64.decode64(secret), string_to_sign.encode("UTF-8"))).strip
authorization = "Application " + key + ":" + signature
uri = URI.parse("https://messagingApi.sinch.com" + path)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
headers = {"content-type" => "application/json", "x-timestamp" => timestamp, "authorization" => authorization}
request = Net::HTTP::Post.new(uri.request_uri)
request.initialize_http_header(headers)
request.body = body
puts JSON.parse(http.request(request).body)
Below is my script and i have no problem accepting an entirely new script. I am a super ruby rookie. Please help.
$to="+4412345678";
$text="Hello there test message";
$curl_post_data = array(
'Message' => $text
);
$curl_post_data=json_encode($curl_post_data);
$timestamp=date("c");
$key = "wwwwwwwwwwwxxxxxxxxxxx";
$secret = "zzzzzzzzzzzzyyyyyyyyyyy";
$http_verb="POST";
$path = "/v1/sms/".$to."";
$scheme = "Application ";
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:".$timestamp."";
$content_md5=base64_encode( md5($curl_post_data,true) );
$string_to_sign = array(
'http_verb' => $http_verb,
'content_md5' => $content_md5,
'content_type' => $content_type,
'canonicalized_headers' =>$canonicalized_headers
);
$signature = hash_hmac("sha256", $secret,json_encode($string_to_sign));
$authorization = "".$scheme."".$key.":".$signature."";
$service_url = 'https://messagingapi.sinch.com/v1/sms/'.$to.'';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8', 'x-timestamp: '.$timestamp.'','authorization: '.$authorization.''));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
var_dump($response);
?>
Any help will do please, Stackoverflow has been a useful resource whenever am stuck with something, i hope my question helps others too.
I got it to work, had to rewrite a few things. Anyway, here's a working code for anyone that might need it.
<?php
$to="+4412345678";
$text2="Test sms message from PHP";
$curl_post_data = array(
'message' => $text2
);
$timestamp=date("c");
$key = "wwwwwwwwwwwwwxxxxxxxxxxxxxxx";
$secret ="zzzzzzzzzzzzyyyyyyyyyyyyyy";
$http_verb="POST";
$path = "/v1/sms/".$to."";
$scheme = "Application";
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:".$timestamp."";
$content_md5=md5(json_encode($curl_post_data),true);
$string_to_sign ="".$http_verb."\n".$content_md5."\n".$content_type."\n".$canonicalized_headers."\n".$path."\n";
$signature = hash_hmac("sha256", base64_encode($secret),utf8_encode($string_to_sign) true);
$signature=base64_encode($signature);
$authorization = "".$scheme."".$key.":".$signature."";
$curl_post_data=json_encode($curl_post_data);
$service_url = 'https://messagingapi.sinch.com/v1/sms/'.$to.'';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8','x-timestamp:'.$timestamp.'','authorization:'.$authorization.''));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
var_dump($response);
?>
Completely working code. Also, thanks to 'Stephen' for basical porting from Ruby to PHP. It saves me a lot of time.
Some notes:
Key should be copied from apps menu of sinch account as is (without any conversion)
String to sign shouldn't contain new line at the end. Also, please check every changes by setting default values from commented code.
In the PHP hash_hmac function cody should be defined before secret (in Ruby arguments should be defined in other order)
If actual headers will contain charset definition - string_to_sign should contain it too. I have deleted them at all.
$key = 'key';
$secret = 'secret';
$message = 'your message';
$phone = '+000000000000';
$body = json_encode(array('message'=>$message));
$timestamp = date("c");
// {{{ test values for checking code (from docs)
/*
$phone="+46700000000";
$key = "5F5C418A0F914BBC8234A9BF5EDDAD97";
$secret ="JViE5vDor0Sw3WllZka15Q==";
$timestamp='2014-06-04T13:41:58Z';
$body = '{"message":"Hello world"}';
*/
// result:
// content-md5 should be 'jANzQ+rgAHyf1MWQFSwvYw=='
// signature should be 'qDXMwzfaxCRS849c/2R0hg0nphgdHciTo7OdM6MsdnM='
// }}}
$path = "/v1/sms/" . $phone;
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:" . $timestamp;
$content_md5 = base64_encode( md5( utf8_encode($body), true ));
$string_to_sign =
"POST\n".
$content_md5."\n".
$content_type."\n".
$canonicalized_headers."\n".
$path;
$signature = base64_encode(hash_hmac("sha256", utf8_encode($string_to_sign), base64_decode($secret), true));
$authorization = "Application " . $key . ":" . $signature;
$curl_post_data=json_encode($curl_post_data);
$service_url = 'https://messagingapi.sinch.com'.$path;
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'content-type: '.$content_type,
'x-timestamp:' . $timestamp,
'authorization:' . $authorization
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
// #todo: checking response / working with results
curl_close($curl);
I am trying to use an OAuth library - it works for yelp but not twitter.
Here is the code:
require_once ('lib/OAuth.php');
$unsigned_url = "https://api.twitter.com/1.1/search/tweets.json?q=test";
$consumer_key = "";
$consumer_secret = "";
$token = "";
$token_secret = "";
$token = new OAuthToken($token, $token_secret);
$consumer = new OAuthConsumer($consumer_key, $consumer_secret);
$signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $unsigned_url);
$oauthrequest->sign_request($signature_method, $consumer, $token);
$signed_url = $oauthrequest->to_url();
$ch = curl_init($signed_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
This is returning blank code - no errors out anything. Again, for twitter only, yelp works fine. Would appreciate help, thanks.