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

Friday, February 4, 2022

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

 February 04, 2022     authorization, facebook, facebook-graph-api, facebook-php-sdk, php     No comments   

Issue

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.



Answered By - MadBoomy
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

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