使用PHP上传图片到Twitter

6

如何使用consumer_keyconsumer_secret在不登录的情况下,通过PHP将图像上传到Twitter Wall

请帮忙,谢谢。


如果这个问题对你有帮助,不仅可以回答,还可以点赞哦。 - Tony Stark
4个回答

9

我已经得到了答案,下载Twitter API的PHP版本并创建一个函数。

function image_upload(){    

    define( 'YOUR_CONSUMER_KEY' , 'your twitter app consumer key');
    define( 'YOUR_CONSUMER_SECRET' , 'your twitter app consumer key secret');

    require ('twitt/tmhOAuth.php');
    require ('twitt/tmhUtilities.php');

    $tmhOAuth = new tmhOAuth(array(
             'consumer_key'    => "YOUR_CONSUMER_KEY",
             'consumer_secret' => "YOUR_CONSUMER_SECRET",
             'user_token'      => "YOUR_OAUTH_TOKEN",
             'user_secret'     => "YOUR_OAUTH_TOKEN_SECRET",
    ));

    $image = 'image.jpg';

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

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

1
对于 Twitter 集成,您需要四个东西:YOUR_CONSUMER_KEY、YOUR_CONSUMER_SECRET、YOUR_OAUTH_TOKEN 和 YOUR_OAUTH_TOKEN_SECRET。 - Tony Stark
twitt/tmhUtilities.php在哪里? - Hirdesh Vishwdewa
1
返回错误代码410,这意味着此代码使用已弃用的API v1,请改用v1.1。 - Hirdesh Vishwdewa
请考虑更新代码,因为它已经无法工作了。 - user5730329
注意:update_with_media API 调用已经被弃用! - Loko
显示剩余4条评论

3

您需要使用OAuth授权您的应用程序的用户,然后使用API发布推文。根据POST statuses/updatePOST statuses/update_with_media, 但我曾经在发布图像时遇到问题(大约一年前,他们可能已经修复了这个问题)。


2
你可以使用 Oauth 来授权你的应用程序。 我发现这篇指南很有帮助,因为它展示了如何连接API以及如何在Twitter上发布内容。 使用update_with_media应该可以让你发布带有图片的内容。

1

update_with_media已经被弃用,您应该考虑使用以下方法:https://dev.twitter.com/rest/public/uploading-media

使用优秀的hybridauth库并更新Twitter.php setUserStatus函数,您可以实现您想要的效果:

/**
* update user status
* https://dev.twitter.com/rest/public/uploading-media-multiple-photos
*/ 
function setUserStatus( $status )
{
    if(is_array($status))
    {
        $message = $status["message"];
        $image_path = $status["image_path"];
    }
    else
    {
        $message = $status;
        $image_path = null;
    }

    $media_id = null;

    # https://dev.twitter.com/rest/reference/get/help/configuration
    $twitter_photo_size_limit = 3145728;

    if($image_path!==null)
    {
        if(file_exists($image_path))
        {
            if(filesize($image_path) < $twitter_photo_size_limit)
            {
                # Backup base_url
                $original_base_url = $this->api->api_base_url;

                # Need to change base_url for uploading media
                $this->api->api_base_url = "https://upload.twitter.com/1.1/";

                # Call Twitter API media/upload.json
                $parameters = array('media' => base64_encode(file_get_contents($image_path)) );
                $response  = $this->api->post( 'media/upload.json', $parameters ); 
                error_log("Twitter upload response : ".print_r($response, true));

                # Restore base_url
                $this->api->api_base_url = $original_base_url;

                # Retrieve media_id from response
                if(isset($response->media_id))
                {
                    $media_id = $response->media_id;
                    error_log("Twitter media_id : ".$media_id);
                }

            }
            else
            {
                error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
            }
        }
        else
        {
            error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
        }
    }

    if($media_id!==null)
    {
        $parameters = array( 'status' => $message, 'media_ids' => $media_id );
    }
    else
    {
        $parameters = array( 'status' => $message); 
    }
    $response  = $this->api->post( 'statuses/update.json', $parameters );

    // check the last HTTP status code returned
    if ( $this->api->http_code != 200 ){
        throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
    }
}

只需要这样使用:

$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );

$twitter_status = array(
    "message" => "Hi there! this is just a random update to test some stuff",
    "image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );

或者对于完整的推文文本:
$res = $adapter->setUserStatus( "Just text" );

就像我这样的人一样,不小心遇到这个问题的,媒体功能已经在一年前合并了。;-) https://github.com/hybridauth/hybridauth/blob/master/hybridauth/Hybrid/Providers/Twitter.php#L191 - Can Rau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接