skip to Main Content

Trying to send a scheduled notification to an app user.

The user specify a reminder time that is stored in a MySQL database and using a cron job.
I want to send notification 3 times a day; upon user prefered time (using local time).

I setup the cron to run once every 30 min.

<?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
?>

I am getting error that says that something went wrong from Facebook graph API.

Update: question clarified.

2

Answers


  1. Chosen as BEST ANSWER

    I found my code mistakes:

    • message template needs to be URL Encoded:
    • Also I needed to make sure I am getting the app access token.
    • I needed to debug and find out if database is returning values

    Here is a tested and working code: I am include the whole cron code; please feel free to edit for optimization and add your input.

    <?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 FacebookFacebook(
                                        ['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(FacebookExceptionsFacebookResponseException $e) {
                                  // When Graph returns an error
                                  echo 'Graph returned an error: ' . $e->getMessage();
                                  exit;
                                } catch(FacebookExceptionsFacebookSDKException $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() . "nn";
                                    echo '<p>Graph Said: ' . "nn";
                                    var_dump($e->getResponse());
                                  } else {
                                    echo "<p> HTTP status code: " . $response->getHttpStatusCode() . "<br />n";
                                    echo "Response: " . $response->getBody() . "</p>nn";
                                    echo "<hr />nn";
                                  }
                                }
                                }
    
                                }
    
                                 notify();
                                 exit;
        }
    }
    exit;
    ?>
    

    Please refer to this answer to learn how to setup a cron task in linux server.

    I used this one :

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

    Thanks for all hints; appreciated.


  2. From the link in your question:

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

    You just need an App Access Token:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search