Search code examples
phpfacebookfacebook-graph-apiauthorizationfacebook-php-sdk

I want to post a notification with the facebook php sdk, how do I do this?


I have a facebook app and I want to send a notification.

I have the id of the user but can't seem to get a valid access token...

I couldn't find examples that worked online and the facebook api documentation doesn't give examples.

My question boils down to this:

How do I get an access token to do this and which (working) code can I use to perform this action?

S.


Solution

  • You need an app access token, luckily there is a page where you can get it.

    -> keep it secret i.e. don't check in in source control, it is directly linked with your app secret...

    This is code that works at the time of writing:

    replace {test-user-id} in the sample with the user id (for instance of a test user)

    <?php
    
    session_start();
    
    require_once __DIR__ . '/../vendor/autoload.php'; // change path as needed
    
    $fb = new Facebook\Facebook([
      'app_id' => '',
      'app_secret' => '',
      'default_graph_version' => 'v2.9',
      ]);
    
    $token = ''; //see rest of answer
    
    $message = 'You have people waiting to play with you, play now!';
    
    $request = $fb->request('post', '/{test-user-id}/notifications?access_token='.$token.'&template='.$message.'&href=test.html');
    
    // Send the request to Graph
    try {
      $response = $fb->getClient()->sendRequest($request);
    } 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 neverthelss: ' . $e->getMessage();
      exit;
    }
    
    $graphNode = $response->getGraphNode();
    
    echo 'success: ' . $graphNode['success'] . ' error: ' . $graphNode['error'];
    
    ?>
    

    The $token is obtained from this tool (credits to this question and answer).

    The page outputs succes: 1 error: (and sends the message as a notification to the test user account).

    If you click the notification you get directed to test.html relative to your app root on your server.

    I hope it is useful to others.

    Cheers,

    S.