开发者

twitter status update thru api with oauth authentication in php

I was googling around for some time and didn't googled anything...

How to, using php, update twitter status thru twitter API with OAuth?

Than开发者_开发百科ks!


There are some php classes already written for Twitter API. Just pick one and use it. Twitter developer site lists a bunch of classes right on their site: http://dev.twitter.com/pages/libraries#php

Or you can use pecl oauth library instead.

I personally prefer using pecl lib, here is a link to useful article:

http://toys.lerdorf.com/archives/50-Using-pecloauth-to-post-to-Twitter.html


Here is php code for twitter status update:

$body = array(
    'status'=>'YOURMESSAGE'
);
$url = "https://api.twitter.com/1.1/statuses/update.json";
$oauth_access_token = "YOURVALUE";
$oauth_access_token_secret = "YOURVALUE";
$consumer_key = "YOURVALUE";
$consumer_secret = "YOURVALUE";

$oauth = array( 'oauth_consumer_key' => $consumer_key,
    'oauth_nonce' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_token' => $oauth_access_token,
    'oauth_timestamp' => time(),
    'oauth_version' => '1.0');

$base_info = buildBaseString($url, 'POST', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
    CURLOPT_POSTFIELDS => $body,
    CURLOPT_HEADER => false,
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false);

$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);

$result_data = json_decode($json);

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜