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

PHP SDK Facebook graph API send App-to-User Notifications using CRON job

正在尝试向应用程序用户发送预定通知。

用户指定存储在 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.

中收到错误提示 出了点问题

更新:问题已澄清。

来自您问题中的link:

Apps can generate notifications by issuing a HTTP POST request to the /user_id/notifications Graph API, with an app access_token.

您只需要一个应用访问令牌:

我发现我的代码错误:

  • 消息模板需要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

感谢所有提示;赞赏。