0

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.

SanThee
  • 2,301
  • 3
  • 23
  • 35
  • Thank you for sharing your research. Try editing the question more into a question (i.e. drop the downvoted and "sorry" parts), and make the question itself a bit clearer. – ishegg Mar 03 '18 at 13:04
  • people most likely downvote your question because it does not include what you have tried so far. in other words, there is no code. – andyrandy Mar 03 '18 at 18:52
  • Well, I can't post my non working code if in the end my code worked and I knew that when I was posting the question. – SanThee Mar 03 '18 at 20:06

1 Answers1

1

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.

SanThee
  • 2,301
  • 3
  • 23
  • 35