Facebook的PHP帖子与粉丝页cronjob? [英] Facebook PHP post to fan page with cronjob?

查看:92
本文介绍了Facebook的PHP帖子与粉丝页cronjob?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码发布到我的Facebook粉丝页面,它是工作正常。现在我想使用cronjob为了发布到Facebook。我知道我必须使用作为访问令牌,但我不知道如何设置它。我试图使用 echo 我自己的访问令牌和页面的访问令牌,并在后api使用它,但没有工作,我得到这个错误:

 未捕获OAuthException:必须使用活动访问令牌来查询有关当前用户的信息。 

这是我尝试的代码:

  require_once('scripts / facebook.php'); 
$ config = array('appId'=>'xxx','secret'=>'xxx');

$ params = array('scope'=>'user_likes,publish_actions,email,offline_access,publish_stream,manage_pages');
$ facebook = new Facebook($ config);
$ user = $ facebook-> getUser();
if($ facebook-> getUser()){
try {

$ user_profile = $ facebook-> api('/ me');
$ access_token = $ facebook-> getAccessToken();
// echo1.。$ access_token;

} catch(FacebookApiException $ e){
$ login_url = $ facebook-> getLoginUrl($ params);
error_log($ e-> getType());
error_log($ e-> getMessage());
}
} else {
$ login_url = $ facebook-> getLoginUrl($ params);

}

$ page_id =xxxxxxxxxxxxx;
$ page_access_token =;
$ result = $ facebook-> api(/ me / accounts);
foreach($ result [data] as $ page){
if($ page [id] == $ page_id){
$ page_access_token = $ page [access_token ];
// echo'< br>';
// echo2.。$ page_access_token;
break
}
}


$ args = array(
'access_token'=>'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'message'=> ; stripslashes($ image_caption)。$ animaged_gif,
'name'=> stripslashes($ image_caption)。$ animaged_gif,
'link'=>http://www.example.com/ images.php?i =。$ image_name,
'picture'=>http://www.example.com/thumbnails/\".$image_name.\".png,
'actions '=> array(
'name'=>'见Pic',
'link'=>http://www.example.com/images.php?i=。 $ image_name


);
$ post = $ facebook-> api(/ $ page_id / feed,post,$ args);

正如你可以看到,我试图使用实际的访问令牌,自己的访问令牌。但是没有工作。我也使用了页面的访问令牌,但这也没有工作。你能告诉我在这里丢失什么或什么是正确的方法这样做?
经过一些进一步的搜索,我发现了 setAccessToken $ page_info = $ fb-> api(/\".$ sInfo ['pageId']。?fields = access_token); 但是关于如何使用它们的资源非常有限。我甚至不确定这些是否会适合这个问题。所有我需要知道的是我需要使用哪个访问令牌和什么是适当的代码来设置它?

解决方案


  1. 取得简短的存取时间。

  2. 延伸。
  3. 获取长期访问的页面。 (无关紧要,这里我们每次都会获取新的访问权限,不太复杂,可靠。)



获得短期访问令牌并扩展它:



fetchtoken.php

 <?php 

//阅读更多:https://developers.facebook.com/docs/howtos/login/server-side-login/
session_start();
$ app_id =xxxxxxxxxxxxxx;
$ app_secret =xxxxxxxxxxxxxxxx;
$ my_url =www.stackoverflow.com/; // redirect url

$ code = $ _REQUEST [code];

if(empty($ code)){
//重定向到登录对话框
$ _SESSION ['state'] = md5(uniqid(rand(),TRUE) ; // CSRF protection
$ dialog_url =https://www.facebook.com/dialog/oauth?client_id=
。 $ app_id。 & redirect_uri =。 urlencode($ my_url)。 & state =
。 $ _SESSION ['state']。 & scope = publish_stream,read_friendlists,email;


echo(< script> top.location.href ='。$ dialog_url。'< / script>);
}
if($ _ SESSION ['state']&&($ _SESSION ['state'] === $ _REQUEST ['state'])){
$ 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);
$ longtoken = $ params ['access_token'];


//保存到数据库
}
?>

所以你现在有一个长时间的accesstoken准备好你的数据库,一个文本文件或其他。 p>

cronjob.php

 < ;? 
require_once('scripts / facebook.php');
//从文件中拉取访问令牌/ db
$ access_token =从文件或db访问令牌;
$ facebook-> setAccessToken($ access_token); //设置我们的访问令牌作为访问令牌,当我们使用SDK调用的东西,我们现在将要做的。

$ config = array('appId'=>'xxx','secret'=>'xxx');

$ params = array('scope'=>'user_likes,publish_actions,email,publish_stream,manage_pages');
$ facebook = new Facebook($ config);
$ user = $ facebook-> getUser();
if($ facebook-> getUser()){
try {

$ user_profile = $ facebook-> api('/ me');
} catch(FacebookApiException $ e){
$ login_url = $ facebook-> getLoginUrl($ params);
error_log($ e-> getType());
error_log($ e-> getMessage());
}
}
else {
$ login_url = $ facebook-> getLoginUrl($ params);
}

$ page_id =xxxxxxxxxxxxx;
$ page_access_token =;
$ result = $ facebook-> api(/ me / accounts);
foreach($ result [data] as $ page){
if($ page [id] == $ page_id){
$ page_access_token = $ page [access_token ];
/ / echo'< br>';
// echo2.。$ page_access_token;
break;
}
}

$ args = array(
'access_token'=> $ page_access_token,
'message'=> stripslashes )。$ animaged_gif,
'name'=> stripslashes($ image_caption)。$ animaged_gif,
'link'=>http://www.example.com/images.php?i =。$ image_name,
'picture'=>http://www.example.com/thumbnails/\".$image_name.\".png,
'actions'=> array (
'name'=>'见Pic',
'link'=>http://www.example.com/images.php?i=\".$image_name

);
$ post = $ facebook-> api(/ $ page_id / feed,post,$ args);
?>

确保您不会再次访问access_token(用户访问令牌/ $ access_token) $ args

code>这是页面访问令牌应由$ page_access_token变量插入,而不是手动插入。



offline_access 在范围内没有什么比在权限对话框上显示他们的数据可以随时访问,可以无需该通知就可以完成。



只要在开始时访问fetch.php一次,并且每60天手动一次,就应该可以正常工作。



让我知道。


I am using the following code to post to my facebook fan page and it is working fine. Now I want to use cronjob in order to post to Facebook. I know I have to use as access token but I am not sure how to set it up. I tried to use echo my own access token and the page's access token and use it in the post api but that did not work I got this error:

Uncaught OAuthException: An active access token must be used to query information about the current user.

Here is my code that I tried:

require_once('scripts/facebook.php');
    $config = array('appId' => 'xxx','secret' => 'xxx');

    $params = array('scope'=>'user_likes,publish_actions,email,offline_access,publish_stream,manage_pages');
    $facebook = new Facebook($config);
    $user = $facebook->getUser();
    if($facebook->getUser()) {
    try {

        $user_profile = $facebook->api('/me');
        $access_token = $facebook->getAccessToken();
        //echo "1. ".$access_token;

      } catch(FacebookApiException $e) {
                        $login_url = $facebook->getLoginUrl($params);
                        error_log($e->getType());
                        error_log($e->getMessage());
      }   
    } else {
        $login_url = $facebook->getLoginUrl($params);

    }    

$page_id = "xxxxxxxxxxxxx";
            $page_access_token = "";
            $result = $facebook->api("/me/accounts");
            foreach($result["data"] as $page) {
                if($page["id"] == $page_id) {
                $page_access_token = $page["access_token"];
                //echo '<br>';
                //echo "2. ".$page_access_token;
                break;
                    }
                }


        $args = array(
            'access_token'  => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            'message'       => stripslashes($image_caption).$animaged_gif,
            'name' => stripslashes($image_caption).$animaged_gif,
            'link' => "http://www.example.com/images.php?i=".$image_name,
            'picture' => "http://www.example.com/thumbnails/".$image_name.".png",
            'actions' => array(
            'name' => 'See Pic',
            'link' => "http://www.example.com/images.php?i=".$image_name
            )

        );
       $post = $facebook->api("/$page_id/feed","post",$args);

As you can see that I tried to use the actual access token that I got when I echo out my own access token. But that did not work. I also used the page's access token, but that also did not work. Can you please tell what I am missing here or what is the proper way to do this ? After some further search I did, I came across setAccessToken and $page_info = $fb->api("/".$sInfo['pageId']."?fields=access_token"); but there is very limited resources on how to use them. I am not even sure if those will be appropriate to this problem. All I need to know is which access token I need to use and what is the appropriate code to set it up ?

解决方案

This is how you can do it :

  1. Get a short lived accesstoken.
  2. Extend it.
  3. Get a long lived page accesstoken. (Doesn't matter, here we are going to fetch new accesstoken every time. Less complicated, and reliable.)

Thought I would go with an algo, instead I am adding all the possible codes and documentations since this may help someone else too.

Getting short lived access token and extending it:

fetchtoken.php

<?php

//read more : https://developers.facebook.com/docs/howtos/login/server-side-login/
session_start();
$app_id = "xxxxxxxxxxxxxx";
$app_secret = "xxxxxxxxxxxxxxxx";
$my_url = "www.stackoverflow.com/";  // redirect url

$code = $_REQUEST["code"];

if(empty($code)) {
    // Redirect to Login Dialog
    $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
    $dialog_url = "https://www.facebook.com/dialog/oauth?client_id=" 
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . $_SESSION['state'] . "&scope=publish_stream,read_friendlists,email";


    echo("<script> top.location.href='" . $dialog_url . "'</script>");
}
if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state'])) {
    $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);
     $longtoken=$params['access_token'];


//save it to database   
} 
?>

So you now have a long lived accesstoken ready in your database, a text file or whatever.

cronjob.php

<?
require_once('scripts/facebook.php');
// Pull access token from the file/db
$access_token = "access token from file or db";
$facebook->setAccessToken($access_token); // sets our access token as the access token when we call something using the SDK, which we are going to do now.

$config = array('appId' => 'xxx','secret' => 'xxx');

$params = array('scope'=>'user_likes,publish_actions,email,publish_stream,manage_pages');
$facebook = new Facebook($config);
$user = $facebook->getUser();
if($facebook->getUser()) {
    try {

        $user_profile = $facebook->api('/me');
    } catch(FacebookApiException $e) {
        $login_url = $facebook->getLoginUrl($params);
        error_log($e->getType());
        error_log($e->getMessage());
    }   
}
else {
    $login_url = $facebook->getLoginUrl($params);
}    

$page_id = "xxxxxxxxxxxxx";
$page_access_token = "";
$result = $facebook->api("/me/accounts");
foreach($result["data"] as $page) {
    if($page["id"] == $page_id) {
        $page_access_token = $page["access_token"];
        //echo '<br>';
        //echo "2. ".$page_access_token;
        break;
    }
}

$args = array(
    'access_token'  => $page_access_token,
    'message'       => stripslashes($image_caption).$animaged_gif,
    'name' => stripslashes($image_caption).$animaged_gif,
    'link' => "http://www.example.com/images.php?i=".$image_name,
    'picture' => "http://www.example.com/thumbnails/".$image_name.".png",
    'actions' => array(
            'name' => 'See Pic',
             'link' => "http://www.example.com/images.php?i=".$image_name
    )
);
$post = $facebook->api("/$page_id/feed","post",$args);
?>

Make sure you don't grab access_token(user access token / $access_token) again in the script.

Also, the access_token in $args which is the page access token should be inserted by the $page_access_token variable, and not manually.

Having offline_access in the scope does nothing than showing them on the permission dialogue box that their data can be accessed any time which can be done without that notification anyway.

This should work as long as you visit the fetch.php once at the start, and once every 60 days manually.

Let me know.

这篇关于Facebook的PHP帖子与粉丝页cronjob?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆