使用PHP SDK在Facebook上发布图像

时间:2015-01-26 19:35:43

标签: php facebook social-networking

我正在尝试使用PHP SDK在Facebook上发布图像,但我无法获得会话连接。我正在使用PHP 5.5.20以及Facebook提供的最新官方SDK。现在我只做了一个测试代码,看看如何使用这个SDK但它总是在没有设置会话令牌的情况下请求登录,或者它返回错误:“请求错误:无法连接到主机”。哪里错了?

<?php
session_start();
require_once 'Frameworks/Facebook/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookRedirectLoginHelper;

$api_key = '[APP_KEY]';
$api_secret = '[SECRET_KEY]';
$redirect_login_url = 'http://sketchy.ga/test.php';

FacebookSession::setDefaultApplication($api_key, $api_secret);
$helper = new FacebookRedirectLoginHelper($redirect_login_url);
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
    $session = new FacebookSession( $_SESSION['fb_token'] );
    try {
        if ( !$session->validate() ) $session = null;
    } catch ( Exception $e ) {
        $session = null;
        echo 'No session: '.$e->getMessage();
    }
}  elseif ( empty( $session ) ) {
    try {
        $session = $helper->getSessionFromRedirect();
    } catch( FacebookRequestException $e ) {
        echo 'Facebook (session) request error: '.$e->getMessage();
    } catch( Exception $e ) {
        echo 'Other (session) request error: '.$e->getMessage();
    }
}

if ( isset( $session ) ) {
    $_SESSION['fb_token'] = $session->getToken();
    $session = new FacebookSession( $session->getToken() );
    try {
        $request = new FacebookRequest(
            $session, 
            'POST', 
            '/me/feed', 
            array(
                'message' => 'Hello world!!'
            )
        );
        $response = $request->execute();
        $graphObject = $response->getGraphObject();
        echo '<pre>' . print_r( $graphObject, 1 ) . '</pre>';
        $msgid = $graphObject->getProperty('id');
    } catch ( FacebookRequestException $e ) {
        echo 'Facebook (post) request error: '.$e->getMessage();
    }
    if ( isset ( $msgid ) ) {
        $parts = explode('_', $msgid);
        try {
            $request2 = new FacebookRequest(
                $session,
                'GET',
                '/'.$parts[1]
            );
            $response2 = $request2->execute();
            $graphObject2 = $response2->getGraphObject();
            echo '<pre>' . print_r( $graphObject2, 1 ) . '</pre>';
        } catch ( FacebookRequestException $e ) {
            echo 'Facebook (get) request error: '.$e->getMessage();
        }
    }
} else {
    echo 'No session, please <a href="'. $helper->getLoginUrl( array( 'publish_actions' ) ).'">login</a>.';
}
?>

0 个答案:

没有答案