导入Facebook和Google Plus照片

时间:2014-05-13 07:58:55

标签: php facebook api facebook-graph-api google-plus

我创建了一个api来从facebook和google +导入照片。但是我在显示照片列表时遇到了问题。你能解决这个问题吗?

我的代码如下:

文件名:index.php(Google)

<?php
    include_once "google-plus-access.php";
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Google+ API To Fetch Photos</title>
        <link rel='stylesheet' href='style.css' />
    </head>
    <body>
        <div id="bar">
            <div class="top-area" >
                <div class="login" >
                    <?php if(isset($me) && isset($activities)) { ?>
                    <a href="?logout" ><h5>Logout</h5></a>
                    <?php } else { ?>
                    <a href="<?php echo($authUrl); ?>" ><h5>Login</h5></a>
                    <?php } ?>
                </div>
            </div>
        </div>
        <?php if(isset($me) && isset($activities)) {?>
        <div class="big-container" >
            <div class="profile" >
                <div class="profile-pic" ><a href="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>" ><img src="<?php echo(substr($me['image']['url'],0,stripos($me['image']['url'],'?sz='))); ?>?sz=200" /></a>
                </div>
            <div class="profile-info" >
                <div class="name" ><a href="<?php echo($me['url']) ; ?>" ><?php if(isset($me['displayName'])) echo(strtoupper($me['displayName'])); else echo "Not set or private"; ?></a></div>
                <div class="details" >
                    <ul>
                        <li><b>GENDER :  </b><?php if(isset($me['gender'])) echo($me['gender']); else echo "Not set or private"; ?></li>
                    <li><b>ORGANISATION :  </b><?php if(isset($me['organizations']['0']['name'])) echo($me['organizations']['0']['name']); else echo "Not set or private"; ?></li>
                        <li><b>PLACE :  </b><?php if(isset($me['placesLived']['0']['value'])) echo($me['placesLived']['0']['value']); else echo "Not set or private"; ?></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <?php foreach($activities['items'] as $activity): ?>
    <div class="activity" >
        <div class="title" ><a href="<?php echo($activity['object']['url']) ; ?>" ><?php echo($activity['object']['content']); ?></a></div>
        <p>Published at <?php echo($activity['published']); ?></p>
        <p>
            <?php echo($activity['object']['replies']['totalItems']); ?> Replies .
            <?php echo($activity['object']['plusoners']['totalItems']); ?> Plusoners .
            <?php echo($activity['object']['resharers']['totalItems']); ?> Reshares
        </p>
    </div>
    <?php endforeach ?>
    <br><br>
    <div class="photos">
        <?php
            if(isset($me['url']))
            {
                $photos = "https://plus.google.com/photos/";//.$me['id']."/albums";
                echo $photos;
            }
        ?>
    </div>
    <?php } else {?>
    <div class="login-box">
        <div id="connect-button"><a href="<?php echo($authUrl); ?>" ><img src="connect-button.png" alt="Connect to your Google+ Account"/></a>
            <div>This API is purely read-only. It will <b>NOT</b> post anything to your profile.
            </div>
        </div>
    </div>
    <?php } ?>
    </body>
</html>

文件名:google-plus-access.php

<?php
    require_once 'google-api-php-client/src/apiClient.php';
    require_once 'google-api-php-client/src/contrib/apiPlusService.php';

    session_start();
    $client = new apiClient();
    $client->setApplicationName("picpixa");
    //*********** Replace with Your API Credentials **************
    $client->setClientId('***********************');
    $client->setClientSecret('************************');
    $client->setRedirectUri('http://localhost/MyApi/Google-Plus/');
    $client->setDeveloperKey('*********************************');
    //************************************************************
    $client->setScopes(array('https://www.googleapis.com/auth/plus.me','https://www.googleapis.com/auth/photos'));
    $plus = new apiPlusService($client);
    if (isset($_REQUEST['logout'])) {
        unset($_SESSION['access_token']);
    }
    if (isset($_GET['code'])) {
        $client->authenticate();
        $_SESSION['access_token'] = $client->getAccessToken();
        header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
    }
    if (isset($_SESSION['access_token'])) {
        $client->setAccessToken($_SESSION['access_token']);
    }
    if ($client->getAccessToken()) {
        $me = $plus->people->get('me');
        $optParams = array('maxResults' => 100);
        $activities = $plus->activities->listActivities('me', 'public', $optParams);
        $_SESSION['access_token'] = $client->getAccessToken();
    } else {
        $authUrl = $client->createAuthUrl();
    }
?>

文件名:index.php(Facebook)

<?php
    include_once "fbmain.php";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
            <title>Fetch Image From Facebook</title>
            <script type="text/javascript">
                function streamPublish(name, description, hrefTitle, hrefLink, userPrompt) {
                    FB.ui({method: 'feed',
                        message: userPrompt,
                        link: hrefLink,
                        caption: hrefTitle,
                        picture: 'http://thinkdiff.net/ithinkdiff.png'
                    });
                    //http://developers.facebook.com/docs/reference/dialogs/feed/
                }
                function publishStream() {
                    streamPublish("Stream Publish", 'Checkout personalized products at www.picpixa.com. I found some of them are just awesome!', 'Checkout www.picpixa.com', 'http://www.picpixa.com', "Personalized Products");
                }
                function newInvite() {
                    var receiverUserIds = FB.ui({
                        method: 'apprequests',
                        message: 'Come on checkout Personalized Products. visit http://www.picpixa.com',
                    },
                    function(receiverUserIds) {
                        console.log("IDS : " + receiverUserIds.request_ids);
                    });
                    //http://developers.facebook.com/docs/reference/dialogs/requests/
                }
            </script>
        </head>
        <body>
            <style type="text/css">
                .box{
                    margin: 5px;
                    border: 1px solid #60729b;
                    padding: 5px;
                    width: 500px;
                    height: 200px;
                    overflow:auto;
                    background-color: #e6ebf8;
                }
            </style>
            <div id="fb-root"></div>
            <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
            <script type="text/javascript">
                FB.init({
                    appId: '<?= $fbconfig['appid'] ?>',
                    status: true, // check login status
                    cookie: true, // enable cookies to allow the server to access the session
                    xfbml: true // parse XFBML
                });
            </script>
            <?php if (!$user) { ?>
                You have to login using Facebook Login Button to see api calling result.
                <a href="<?= $loginUrl ?>"><img src="Images/login.png"></a>
            <?php } else { ?>
                <a href="<?= $logoutUrl ?>"><img src="Images/logout.png"></a>
            <?php } ?>

            <!-- all time check if user session is valid or not -->
            <?php if ($user) { ?>
                <table border="0" cellspacing="3" cellpadding="3">
                    <tr>
                        <td>
                            <!-- Data retrived from user profile are shown here -->
                            <div class="box">
                                <b>User Photos using Graph API</b>
                                <?php d($user_photos); ?>
                            </div>
                        </td>
                    </tr>
                </table>
        <?php }?>
    </body>
</html>

文件名:fbmain.php

<?php
    $fbconfig['appid'] = "Your App Id";
    $fbconfig['secret'] = "Your App Secret";
    $fbconfig['baseurl'] = "localhost/MyApi/Facebook/index.php";

    //
    if (isset($_GET['request_ids'])) {
        //user comes from invitation
        //track them if you need
    }

    try {
        include_once "facebook.php";
    } catch (Exception $o) {
        error_log($o);
    }

    // Create our Application instance.
    $facebook = new Facebook(array(
        'appId' => $fbconfig['appid'],
        'secret' => $fbconfig['secret'],
        'cookie' => false,
            ));

    //Facebook Authentication part
    $user = $facebook->getUser();
    // We may or may not have this data based
    // on whether the user is logged in.
    // If we have a $user id here, it means we know
    // the user is logged into
    // Facebook, but we don’t know if the access token is valid. An access
    // token is invalid if the user logged out of Facebook.


    $loginUrl = $facebook->getLoginUrl(
            array(
                'scope' => 'user_photos',
                'redirect_uri' => $fbconfig['baseurl']
            )
    );

    $logoutUrl = $facebook->getLogoutUrl();

    if ($user) {
        try {
            // Proceed knowing you have a logged in user who's authenticated.
            $user_profile = $facebook->api('/me');
        } catch (FacebookApiException $e) {
            //you should use error_log($e); instead of printing the info on browser
            d($e); // d is a debug function defined at the end of this file
            $user = null;
        }
    }


    //if user is logged in and session is valid.
    if ($user) {
        //Retriving photos of user using graph api

        try {
            $user_photos = $facebook->api("/$user/photos");
        } catch (Exception $o) {
           d($o);
        }
    }
    function d($d) {
        echo 'This function is called <br><br><pre>';
        print_r($d);
        echo '</pre>';
    }
?>

1 个答案:

答案 0 :(得分:1)

我不确定您在Google+方面的期望。显然,您为照片所做的一切都是根据Google ID打印网址。 (假设被注释掉的部分。)

使用Google+ API无法获取用户的照片。您需要考虑使用Picasa Web Albums Data API,但这是使用Google的旧版GData协议。有一些资源可能有所帮助,例如,PHP library使用较旧版本的协议,而更现代的example code snippet可能会指导您这样做。

您应该对https://code.google.com/p/google-plus-platform/issues/detail?id=670加注星标,表示您希望在Google +中为照片添加更现代的API。