2012-02-28 4 views
0

나는 twitter api에 매우 익숙하다. 오늘은 내 인생에서 twitter api에 처음 가입했다. 내 목표는 내 웹 사이트의 사진을 트위터에 게시하는 것입니다. 인터넷에서 현재 라이브러리를 다운로드 받았으며, 다음과 같은 두 개의 파일과 예제를 제공합니다. 내가이Oauth, API, JSON 및 PHP를 사용하여 트위터에 그림을 업로드하는 방법

이 두 파일을 포함하고이 코드 photo_tweet.php 여기 내 코드

<?php 
require 'tmhOAuth.php'; 
require 'tmhUtilities.php'; 

$tmhOAuth = new tmhOAuth(array(
    'consumer_key' => 'ZlhOWeCWG2MS5Wxxxxxx', 
    'consumer_secret' => 'DIPjoKcIWjpGWmw5jGJSKGAOLxxxxxx', 
    'user_token'  => 'xxxxx-OGtPyRSUOUaR6XQRLAFVuv14xxxxxx', 
    'user_secret'  => 'xxxxxoimsrNFhlz7mPa9h5pyVSjxxxxxxx', 
)); 

// we're using a hardcoded image path here. You can easily replace this with 
// an uploaded image - see images.php in the examples folder for how to do this 
// 'image = "@{$_FILES['image']['tmp_name']};type={$_FILES['image']['type']};filename={$_FILES['image']['name']}", 

// this is the jpeg file to upload. It should be in the same directory as this file. 
$image = 'a.jpg'; 

$code = $tmhOAuth->request(
    'POST', 
    'https://upload.twitter.com/1/statuses/update_with_media.json', 
    array(
    'media[]' => "@{$image};type=image/jpeg;filename={$image}", 
    'status' => 'Picture time', 
), 
    true, // use auth 
    true // multipart 
); 

if ($code == 200) { 
    tmhUtilities::pr(json_decode($tmhOAuth->response['response'])); 
} else { 
    tmhUtilities::pr($tmhOAuth->response['response']); 
} 

?> 

a.jpg 내 서버에있는 것입니다 사진

와 트윗을한다는 것을 의미한다.

여기 내 트위터 설정입니다!

요청 유형 : GET 요청 URI : * https://api.twitter.com/1/

나는이 모든 코드를 업로드하고 난 $ 코드를 에코 때, 빈 애추를 반환 내 코드에 액세스 할 때; 0을 반환합니다.

모든 것을 관찰하고 경험했습니다. 나는 너의 친절한 도움이 필요하다. 나는 당신에게 아주 고마워 할 것입니다.

Note : 이벤트 내 소비자 키와 소비자 비밀을 제거했을 때이 코드는 오류를 나타내지 않습니다. 그냥 빈 화면. 나는이 문제의 경우하지만 오류가 여기에


에 오류를 표시 할 경우에만 그것이 나

$consumerKey = $consumer_key; 
$consumerSecret = $consumer_secret; 
$OAuthToken = $user_token; 
$OAuthSecret = $user_secret; 

include "OAuth.php"; 
include "twitteroauth.php"; 

$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $OAuthToken, $OAuthSecret); 

$image = 'a.jpg'; 

$optsArray['status'] = 'Hi'; 



if (isset($_GET['msg'])) { 
    $tweetmsg = $_GET['msg']; 
    $tweet->post('statuses/update',$optsArray); 

    if($tweet) 
    echo "Your message has been sent to Twitter."; 
    else 
    echo "Your message has not been sent to Twitter."; 

} else { 
    echo "Your message has not been sent to Twitter."; 
} 

을 위해 일하지만 난

을 사용하는 경우에만 상태를 게시 상태 코드입니다

update_with_media.json

$ optsArray [ '미디어 [] @'] = "@ $ {} 이미지 ";

가 작동하지 않습니다이 문제를이 문서를 체크 아웃 할 수 있습니다

+1

간단한 메시지를 게시하려면 Twitter를 사용해 보셨습니까? 먼저 코드/api 키/토큰을 테스트하는 간단한 메시지를 게시하는 것이 좋습니다 – Arfeen

+0

테스트 할 다른 간단한 코드를 사용하지만 빈 화면도 제공합니다. 트위터 설정에서 내 키와 토큰을 올바르게 복사했습니다. –

답변

1

을 파악하는 데 도움이 바랍니다. 단계별로 안내하고 많은 예제를 제공합니다.

다음 메소드가 API에서 제공됩니다. 위에서 주어진

METHOD: uploadAndPost (http://twitpic.com/api/uploadAndPost) 
METHOD: upload (http://twitpic.com/api/upload) 
Error codes 
    1001 – Invalid twitter username or password 
    1002 – Image not found 
    1003 – Invalid image type 
    1004 – Image larger than 4MB 

PHP

를 사용 twitpic API에 twitpic 로고 포스트 사진은 twitpic의 API 페이지에서 API의 설명이다. 그러나 당신은 그 복잡한 세부 사항에 들어갈 필요가 없습니다. 대신 twitpic에 그림을 게시하고 동일한 계정에서 twitter 상태를 업데이트 할 수있는 클래스를 사용할 수 있습니다. 이것은 사용하기 쉬운 간단 &입니다. 아래 코드를 확인하십시오.

<?php 
class twitpic 
{ 
    /* 
    * variable declarations 
    */ 
    var $post_url='http://twitpic.com/api/upload'; 
    var $post_tweet_url='http://twitpic.com/api/uploadAndPost'; 
    var $url=''; 
    var $post_data=''; 
    var $result=''; 
    var $tweet=''; 
    var $return=''; 

/* 
* @param1 is the array of data which is to be uploaded 
* @param2 if passed true will display result in the XML format, default is false 
* @param3 if passed true will update status twitter,default is false 
*/ 

    function __construct($data,$return=false,$tweet=false) 
    { 
    $this->post_data=$data; 
    if(empty($this->post_data) || !is_array($this->post_data)) //validates the data 
     $this->throw_error(0); 
    $this->display=$return; 
    $this->tweet=$tweet; 

    } 

    function post() 
    { 
    $this->url=($this->tweet)?$this->post_tweet_url:$this->post_url; //assigns URL for curl request based on the nature of request by user 
    $this->makeCurl(); 
    } 
    private function makeCurl() 
    { 
    $curl = curl_init(); 
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2); 
    curl_setopt($curl, CURLOPT_HEADER, false); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1); 
    curl_setopt($curl, CURLOPT_URL, $this->url); 
    curl_setopt($curl, CURLOPT_POST, 3); 
    curl_setopt($curl, CURLOPT_POSTFIELDS, $this->post_data); 
    $this->result = curl_exec($curl); 
    curl_close($curl); 
    if($this->display) 
    { 
     header ("content-type: text/xml"); 
     echo $this->result ; 
    } 

    } 
    private function throw_error($code) //handles few errors, you can add more 

    { 
    switch($code) 
    { 
     case 0: 
     echo 'Think, you forgot to pass the data'; 
     break; 
     default: 
     echo 'Something just broke !!'; 
     break; 
    } 
    exit; 
    } 
} //class ends here 

?> 

위의 PHP 클래스는 트위터에 twitpic 및 사후 상태에 사진을 업로드 할 수있는 모든 트릭을 수행합니다. 이 클래스는 HTML 양식을 사용하거나 PHP 스크립트를 사용하여 자동으로 이미지를 업로드하고 트윗을 게시 할 수 있습니다. 을 입력하여 다음 HTML 양식과 PHP 스크립트를 함께 사용하여 사진을 업로드 할 수 있습니다.

// This block of code should be written above the HTML and it will exit after the picture has been uploaded. If //you have turned display on (by passing 3rd param as true) then it will display the success message. 
if($_POST) 
{ 

    $file=$_FILES['media']; 
    $postfields = array(); 

    $postfields['username'] = $_POST['username']; 

    $postfields['password'] = $_POST['password']; 
    $postfields['message'] = $_POST['message']; 
    $postfields['media'] = "@$file[tmp_name]"; 

    $t=new twitpic($postfields,true,true); 
    $t->post(); 
    exit; 
} 

<style type="text/javascript"> 
    *{font-family:verdana;} 
    span{font-size:12px;color:#393939;} 
    h3{font-size:14px;color:#5AAAF7;} 
</style> 
<body> 

    <h3>Upload your pic to twitpic, and post status on twitter</h3> 
    <form method="post" enctype="multipart/form-data" action="<?= $_SERVER[PHP_SELF] ?>" > 
    <p><span style="height:40px;font-weight:bold;margin-right:56px;">Twitter Username :</span><input type="text" name="username" /></p> 
    <p><span style="height:40px;font-weight:bold;margin-right:61px;">Twitter Password:</span><input type="password" name="password" /></p> 

    <p><span style="vertical-align:text-top;height:40px;font-weight:bold;margin-right:28px;">Message to be posted :</span> <textarea cols="35" rows="2" name="message"></textarea></p> 
    <p><span style="vertical-align:text-top;height:40px;font-weight:bold;">Choose an image to upload: </span><input type="file" name="media" /></p> 
    <p style="width:250px;text-align:right;margin-top:50px;"><input type="submit" value="Upload&nbsp;&raquo;" /> </p> 
    </form> 
    <sup>Script powered by <a href="http://www.digimantra.com/">www.digimantra.com</a></sup> 
</body> 

You can skip posting update to twitter by passing the third argument as false or just by skipping it. If you want to upload image programmatically, without the user input or the form then you can do it using the following code. Make sure the image path is correctly mention, else it will throw an error. 

<?php 
$file='file_to_be_uploaded.gif'; 
$postfields = array(); 

$postfields['username'] = 'twitter_username'; 

$postfields['password'] = 'twitter_password'; 
$postfields['message'] = 'Message to be posted' ; 
$postfields['media'] = "@$file"; //Be sure to prefix @, else it wont upload 

$t=new twitpic($postfields,true,true); 
$t->post(); 
?> 

위의 클래스는 curl php를 사용하여 이진 데이터 보내기에서 설명한대로 이미지를 이진 형식으로 게시합니다. 필요에 따라 수업을 변경할 수 있으며 원하는 방식으로 수업을 향상시킬 수도 있습니다. 희망이 게시물은 당신이 뭔가를 배울 수있었습니다.

+1

친절한 응답을 보내 주셔서 감사합니다. 위의 코드는 완벽하게 작동합니다. 하지만 사용자 이름과 암호를 입력해야합니다. Oauth를 사용하고 싶습니다. 예를 들어 사용자가 내 웹 사이트에 올 경우 사진이 마음에 들면 내 웹 사이트에서 사용자 이름과 비밀번호를주지 않고이 사진을 트위터에 공유 할 수 있습니다. twitter API 사용 Oauth, –

+0

이벤트 내 고객 키 및 고객 비밀 및 기타 세부 정보를 제거한 후에이 코드는 오류를 표시하지 않습니다. 그냥 빈 화면. 어떤 문제가 발생해도 오류가 나타나기를 원합니다. 오류가 없습니다. –

+0

작동하지 않습니다. 오류 로그인 페이지에서 로그인 트위터와 동일한 사용자 이름과 암호를 복사하면 정상적으로 작동합니다. :( – SJSSoft

관련 문제