PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 27, 2022

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

 February 27, 2022     cron, facebook-graph-api, facebook-php-sdk, notifications     No comments   

Issue

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.


Solution

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

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.



Answered By - wpcoder
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing