PHP SDK Facebook图形API使用CRON作业发送App-to-User Notifications

时间:2017-10-12 13:04:19

标签: facebook-graph-api notifications cron facebook-php-sdk

尝试向应用用户发送预定通知。

用户指定存储在MySQL数据库中并使用cron作业的提醒时间。 我想每天发送3次通知;根据用户首选时间(使用当地时间)。

我将cron设置为每30分钟运行一次。

<?php
function runCurl($path)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $path);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $output = curl_exec($ch);
    return $output;
    curl_close($ch);
}
function getAppUsers()
{
}
function build_batch_request()
{
}
$graph_url    = "https://graph.facebook.com/oauth/access_token?client_id=xxx&client_secret=xxx&grant_type=client_credentials&redirect_uri=https://www.example.com/app/";
$result       = runCurl($graph_url);
$access_token = json_decode($result)->access_token;
$graph_url    = "https://graph.facebook.com/me/notifications?access_token=$access_token&template=Test Message";
$result       = runCurl($graph_url);
print_r($result); // for debug only
?>

我收到来自Facebook图表API的 出错 的错误。

更新:问题已澄清。

2 个答案:

答案 0 :(得分:1)

从您问题中的链接:

  

应用可以通过发送HTTP POST请求来生成通知   / user_id / notifications图表API,带有 app access_token

您只需要一个App Access令牌:

答案 1 :(得分:0)

我发现我的代码错误:

  • 消息模板需要是URL编码:
  • 此外,我需要确保获取应用访问令牌。
  • 我需要调试并找出数据库是否返回值

这是经过测试和运行的代码: 我包括整个cron代码;请随时编辑以进行优化并添加您的输入。

<?php



 if(isset($_GET["key"]) || !empty($_GET["key"]) )
            {

    //  will be used later when creating a cron job; to prevent direct access to file
    if($_GET["key"]=='YOUR_KEY_HERE')
        {
                            require_once 'Facebook/autoload.php';


                            define('APPID', 'YOUR_APP_ID_HERE');
                            define('APPSECRET', 'YOUR_APP_SECRET_HERE');
                            define('CANVASURL', 'YOUR_CANVAS_URL_HERE');


                            // function to run CURL
                            function runCurl($path)
                            {
                                    $ch = curl_init();
                                    curl_setopt($ch, CURLOPT_URL, $path);
                                    curl_setopt($ch, CURLOPT_HEADER, 0);
                                    curl_setopt($ch, CURLOPT_POST, 1);
                                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                                    $output = curl_exec($ch);
                                    return $output;
                                    curl_close($ch);
                            }

                            // function to send batch notification to app user
                            function notify()
                            {
                                    $fb = new Facebook\Facebook(
                                    ['app_id' => 'APPID',
                                    'app_secret' => 'APPSECRET',
                                    'default_graph_version' => 'v2.10']);





                                    $gmt_time = gmdate("H:i:s", time());


                                    include_once 'db.php';
                                    // include your database configuration
                                    // recommending using PDO
                                    $db=connect();

                                    $get_users_list="select fb_userid, morning, afternoon, night ,utc_time from alarm where time_format(morning, '%H:%i') = time_format(UTC_TIME, '%H:%i') OR time_format(afternoon, '%H:%i') = time_format(UTC_TIME, '%H:%i') OR time_format(night, '%H:%i') = time_format(UTC_TIME, '%H:%i')";
                                    // getting a list of users that expecting a reminder notification;
                                    // as the server's is using UTC, we convert saved local time into UTC time
                                    // I can directly save in UTC when user input reminder time; but this is intended
                                    // echo $get_users_list; //DEBUG


                                    $result= $db->getDataListFromQuery($get_users_list);
                                    //var_dump('Query Result= '. $result[0]); // DEBUG
                                    if($result[0]>0)
                                    {
                                    // check if $result return data and not empty
                                            $graph_url= "https://graph.facebook.com/oauth/access_token?client_id=". APPID . "&client_secret=" . APPSECRET . "&grant_type=client_credentials&redirect_uri=" . CANVASURL;

                                            echo $graph_url;


                                            $curlResult = runCurl($graph_url);
                                            $access_token = json_decode($curlResult)->access_token;
                                            var_dump($access_token); //DEBUG


                                    $fb->setDefaultAccessToken($access_token);
                                    $fb_usersList= []; // an arry to hold the users' IDs to wich notification will go.
                                    $tmpbatch = []; // an array to hold all requests in batch


                            foreach ($result as $row) {
                                         $fbUserID = $row['fb_userid'];
                                         $morning_alarm = $row['morning'];
                                         $afternoon_alarm = $row['afternoon'];
                                         $night_alarm = $row['night'];


                                         $morning_med = $row['morningmed'];
                                         $afternoon_med = $row['afternoonmed'];
                                         $night_med= $row['nightmed'];

                                         $now_utc= $row['utc_time'];


$now_utc = date('H:i', strtotime($now_utc));     // remove seconds from UTC TIME
$morning_alarm = date('H:i', strtotime($morning_alarm ));
$afternoon_alarm = date('H:i', strtotime($afternoon_alarm ));
$night_alarm=  date('H:i', strtotime($night_alarm));

if($morning_alarm ==$now_utc)
{
$template="Good Morning! Please remember to take your medicine: ($morning_med)";
}

if($afternoon_alarm==$now_utc)
{
$template="Good Afternoon! Please remember to take your medicine: ($afternoon_med)";
}

if($night_alarm==$now_utc)
{
$template="Good Evening! Please remember to take your medicine: ($night_med)";
}


$template=urlencode($template) . "&href=page.php";  // this will redirect users to page.php once they click on noticiation
//echo $template; //DEBUG






                                        $batch[]=$fb->request('POST', "/".$fbUserID."/notifications?template=$template");

                            }


                            try {
                              $responses = $fb->sendBatchRequest($batch);
                            } catch(Facebook\Exceptions\FacebookResponseException $e) {
                              // When Graph returns an error
                              echo 'Graph returned an error: ' . $e->getMessage();
                              exit;
                            } catch(Facebook\Exceptions\FacebookSDKException $e) {
                              // When validation fails or other local issues
                              echo 'Facebook SDK returned an error: ' . $e->getMessage();
                              exit;
                            }

                            foreach ($responses as $key => $response) {
                              if ($response->isError()) {
                                $e = $response->getThrownException();
                                echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
                                echo '<p>Graph Said: ' . "\n\n";
                                var_dump($e->getResponse());
                              } else {
                                echo "<p> HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
                                echo "Response: " . $response->getBody() . "</p>\n\n";
                                echo "<hr />\n\n";
                              }
                            }
                            }

                            }

                             notify();
                             exit;
    }
}
exit;
?>

请参阅此答案以了解how to setup a cron task in linux server

我用过这个:

curl --silent https://www.example.com/cron.php?key=somekey

感谢所有提示;赞赏。