2012-01-30 1 views
1

첫 번째 페이스 북 앱 프로젝트에 완전히 좌절했습니다. 간단한 작업 인 것처럼 큰 문제가 있습니다.Facebook : 페이지에 페이지 올리기 (액세스 토큰/PHP)

페이스 북 페이지 (내 프로필 아님)에 뭔가 똑똑하게 게시 할 내 서버 (쉽게)에 크론 작업을 설정하고 페이지로 게시해야합니다. 나는 구석에 몸을 담글었고 지금은 완전히 혼란 스럽다. 아무도 도와 줄 수 있니? ". OAuthException : 오류 검증하는 응용 프로그램"->이 가져옵니다

첫번째 PHP가

내가 거의 모든 오류 메시지를 통해 봤는데 지금 에 부착하고 여기에

내가 지금 가지고있는 무엇 내 페이지 액세스를위한 새 액세스 토큰. 다음 페이지를 호출하고 새 액세스 토큰을받을 때이 부분은 정상적으로 작동하는 것 같습니다.

<?php 
require_once 'facebook.php'; 

$app_id = "1234...."; 
$app_secret = "5678...."; 
$my_url = "http://.../next.php"; 

$facebook = new Facebook(array(
'appId' => $app_id, 
'secret' => $app_secret, 
'cookie' => true 
)); 

// known valid access token stored in a database 
$access_token = "abc...."; 

$code = $_REQUEST["code"]; 

// If we get a code, it means that we have re-authed the user 
//and can get a valid access_token. 
if (isset($code)) { 
    $token_url="https://graph.facebook.com/oauth/access_token? 
client_id=" 
     . $app_id . "&redirect_uri=" . urlencode($my_url) 
     . "&client_secret=" . $app_secret 
     . "&code=" . $code . "&display=popup"; 
    $response = file_get_contents($token_url); 
    $params = null; 
    parse_str($response, $params); 
    $access_token = $params['access_token']; 

} 

// Attempt to query the graph: 
$graph_url = "https://graph.facebook.com/me?" 
    . "access_token=" . $access_token; 
$response = curl_get_file_contents($graph_url); 
$decoded_response = json_decode($response); 

//Check for errors 
if ($decoded_response->error) { 
    // check to see if this is an oAuth error: 
    if ($decoded_response->error->type== "OAuthException") { 
     // Retrieving a valid access token. 
     $dialog_url= "https://www.facebook.com/dialog/oauth?" 
     . "client_id=" . $app_id 
     . "&redirect_uri=" . urlencode($my_url); 
     echo("<script> top.location.href='" . $dialog_url 
     . "'</script>"); 
    } else { 
     echo "other error has happened"; 
    } 
} else { 

    // success 
    echo("success" . $decoded_response->name); 

} 

function curl_get_file_contents($URL) { 
    $c = curl_init(); 
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($c, CURLOPT_URL, $URL); 
    $contents = curl_exec($c); 
    $err = curl_getinfo($c,CURLINFO_HTTP_CODE); 
    curl_close($c); 
    if ($contents) return $contents; 
    else return FALSE; 
} 

?> 

다음 php -> 액세스 토큰을 읽고 벽에 게시하십시오. 내 쿼리 문자열에서 액세스 토큰을 얻을 수 있지만 다음 오류 메시지가 나타납니다. 내 아이디, 비밀 페이지 ID는 내가 그렇게 할 수있는 간단한 방법이 있는지 해요 .... 및 방법은 실제로 작동하도록

<?php 
require_once 'facebook.php'; 

$app_id = "1234...."; 
$app_secret = "5678...."; 
$page_id = "0909...."; 

$facebook = new Facebook(array(
'appId' => $app_id, 
'secret' => $app_secret, 
'cookie' => true 
)); 

$access_token = $_GET['code']; 
echo($access_token); 

try { 
    $attachment = array(
       'access_token' => $access_token, 
       'message'=> "Hello World" 
     ); 

    $result = $facebook->api('/'.$page_id.'/feed','POST', 
$attachment); 
    var_dump($result); 

} catch(Exception $e) { 
    echo $e; 
} 

?> 

... 위해 모두! 도움을 주시면 감사하겠습니다.

나는이 스크립트 Update facebook page status from that page itself 을 따라이 https://developers.facebook.com/blog/post/500

감사합니다.

+0

내가 어디 http://stackoverflow.com/questions/4309154/update-facebook- 같은 페이지 액세스 토큰을 추출하는에 관해서 (안 PHP 자신을 dev에) 코드에 불분명 해요 page-status-that-page-itself-graph-api-php는 않습니다. – DMCS

+0

첫 번째 스크립트에서 액세스 토큰을 얻고 있습니다. 링크 된 예제에서 얻은 액세스 토큰을 사용할 때 토큰은 2 시간 동안 제한되기 때문입니다. 첫 번째 스크립트는 이전 액세스 토큰을 확인합니다 -> 이전 버전임을 인식하고 쿼리 문자열에 새 스크립트를 반환합니다 ... – Peter1178373

답변

1

코드에서 사용자가 필요로하는 PAGE 액세스 토큰을 얻지 못하는 것 같습니다. 대신 USER 액세스 토큰을 사용하고 있습니다. 따라서 API가 그것을 좋아하지 않는 이유는 무엇입니까? USER (사용자) 하나에서 페이지 액세스 토큰을 얻는 방법에 대한 자세한 내용은 시행 착오를 몇 시간 후 https://developers.facebook.com/docs/authentication/

+0

답변 해 주셔서 감사합니다. 액세스 토큰 개념은 나를 정말로 어리 석게 만든다. 어쨌든, 나는 그 주위에 내 머리를 얻을 수 없다 ... :/어쨌든, 내가 다시 그것을 확인하고 곧 (잘하면) 작업 코드를 게시 할 것입니다 ... – Peter1178373

+0

네, 그 주위에 머리를 감싸는 데 시간이 걸릴 것입니다. 그것은 내가 그것을 사용할 수있는 지점에 도달하기까지 문자 그대로 3 일의 개발 일이 필요했습니다. 해피 코딩. 내 대답이 너를 도왔 으면 좋겠어. – DMCS

+0

입력 해 주셔서 감사합니다. DMCS. 나는 그것이 완벽하지는 않지만 작동하도록했습니다 (아래 답변 참조). – Peter1178373

-1

페이지 로그인 섹션을 참조하십시오 여기에 지금까지 작동 내 솔루션입니다.

<?php 

require_once 'facebook.php'; 

//------ vars 
$app_id = "123..."; 
$app_secret = "abc..."; 
$page_id = "999..."; 
$my_url = "http://exactly the same as defined /"; 

//------ fb object 
$facebook = new Facebook(array(
'appId' => $app_id, 
'secret' => $app_secret, 
'cookie' => true 
)); 

//------ verification CODE 
// this is not pretty -> the code should be received with a another graph query... 
// but I couldn't get this to work. Thus I'm using my last known Verification Code 
$code = "ABC123..."; 

//------ get USER access token 
if (isset($code)) { 
    $token_url="https://graph.facebook.com/oauth/access_token?client_id=" . $app_id 
     . "&client_secret=" . $app_secret 
     . "&code=" . $code 
     . "&redirect_uri=" . $my_url; 

    $response = file_get_contents($token_url); 
    $params = null; 
    parse_str($response, $params); 
    $user_access_token = $params['access_token']; 

} else { 
    echo("No code"); 
} 

//------ get PAGE access token 
$attachment_1 = array(
    'access_token' => $user_access_token 
); 

$result = $facebook->api("/me/accounts", $attachment_1); 
    foreach($result["data"] as $page) { 
     if($page["id"] == $page_id) { 
      $page_access_token = $page["access_token"]; 
      break; 
     } 
    } 

//------ write to page wall 
try { 
    $attachment = array(
       'access_token' => $page_access_token, 
       'message'=> 'hello world!' 
     ); 

    $result = $facebook->api('/me/feed','POST', $attachment); 
    var_dump($result); 

} catch(Exception $e) { 
    echo $e; 
} 

?> 
+0

야, 멋지지 않아. DMCS가 정확한 답을 주었고, 당신은 그/그녀로부터 그것을 훔쳤습니다. 당신 대답에 -1. – CoderFromOuterSpace

+1

미안하지만, 분명히 꽤 stackoverflow 등급 및 수용 작동 이해하지 않습니다. 여기에는 전체 솔루션이 포함되어 있기 때문에이 답을 체크 표시로 표시했습니다. 분명히 DMCS는 이것에 큰 역할을했습니다. 어떻게해야합니까? 또는 더 나은 아직, 어떻게 그것을 바르게 만들 수 있습니까? – Peter1178373

+0

알겠습니다. 이 회색 체크 표시는 처음에는 알아 내기가 어렵습니다. – CoderFromOuterSpace

6
// firstly include the fb sdk 

$facebook = new Facebook(array(
       'appId' => 'your app id', 
       'secret' => 'your app secret',`enter code here` 
       'cookie' => true, 

    )); 


$session = $facebook->getUser(); 
    $loginUrl = $facebook->getLoginUrl(
        array(
         'scope' => 'user_status,publish_stream,email,user_location,user_birthday,friends_birthday,manage_pages', 
         'redirect_uri' => 'http://www.example.com/' 
        ) 
       ); 

    $logoutUrl = $facebook->getLogoutUrl(
        array(
         // any url u want to redirsct onto 
         'redirect_uri' => 'http://www.example.com/' 

        ) 
       ); 

// when redirected from facebook get the code 
    $code = $_GET['code']; 

// 

             $my_url  = 'http://www.example.com/'; 

             $app_id  = 'your app id '; 
             $app_secret = 'your app secret '; 
             // here we have the access token so we will play with it 
             if (isset($code)) { 
               $token_url="https://graph.facebook.com/oauth/access_token?client_id=" 
                . $app_id . "&redirect_uri=" . urlencode($my_url) 
                . "&client_secret=" . $app_secret 
                . "&code=" . $code ; 
               $response = file_get_contents($token_url); 
               $params = null; 
               parse_str($response, $params); 
               $user_access_token = $params['access_token']; 
              } 

// here we got the access token of user over here in $user_access_token 
// now we will get for our page 
//------ get PAGE access token 
             $attachment_1 = array(
              'access_token' => $user_access_token 
             ); 
             $page_id = 'your page id '; 
             $result = $facebook->api("/me/accounts", $attachment_1); 
              foreach($result["data"] as $page) { 
               if($page["id"] == $page_id) { 
                $page_access_token = $page["access_token"]; 
                break; 
               } 
              } 

             //   write to page wall 
             try { 
              $attachment = array(
                 'access_token' => $page_access_token, 
                 'message'=> 'hello world posting like admin!', 
                 'page_id'=> $page_id 
               ); 

              $result = $facebook->api('/'.$page_id.'/feed','POST',$attachment); 
              //$result = $facebook->api('/me/feed','POST', $attachment); 
              var_dump($result); 

             } catch(Exception $e) { 
              echo $e; 
             } 
+0

감사합니다. 코드와 주석은 SDK를 올바르게 사용하는 좋은 예입니다. 좋아하는 답변을하려면 옵션이 필요합니다. –