« « New Toys! | Shapeoko CNC Build Progress » »

Sending Notifications From a Facebook App in PHP

Nov 29, 2012 by     3 Comments    Posted under: Facebook, PHP

I spent a lot of time today trying to figure out how to send a notification from my Facebook app, but couldn’t find a lot of useful documentation. Their official documentation is here: https://developers.facebook.com/docs/app-notifications/ but isn’t as detailed as it could be. Here’s how I finally got it working. Hopefully this saves someone some time.

First, you have to make sure your app is set as an “App on Facebook” in your app settings. I had mine set as a Page Tab, but I had to check both options to get the notifications to work.

Here’s the PHP code to send a notification:

$app_id = {your app id};
$app_secret = {your app secret};
$user_id = {user id to send to};
$token_url = “https://graph.facebook.com/oauth/access_token?” .
“client_id=” . $app_id .
“&client_secret=” . $app_secret .
“&grant_type=client_credentials”;

$app_access_token = file_get_contents($token_url);

$postdata = http_build_query(
array(
‘href’ => ‘index.php’,
‘template’ => ‘Your notification message’,
‘ref’ => ‘ref’
)
);

$opts = array(‘http’ =>
array(
‘method’  => ‘POST’,
‘header’  => ‘Content-type: application/x-www-form-urlencoded’,
‘content’ => $postdata
)
);

$context  = stream_context_create($opts);
$result = file_get_contents(‘https://graph.facebook.com/’. $user_id . ‘/notifications?’ . $app_access_token, false, $context);

echo $result;

That’s all you need to send a notification. The annoying thing is that your notification will link back to your Facebook app, not your Page Tab (if you are using one), but that’s easy to fix by redirecting the app page back to the Page Tab.

3 Comments + Add Comment

  • Hye, may I know how to use this script? I already have apps.

    Tq

  • thank u very much 🙂 you helped me a lot

  • hello friend, I’m months researching about it …
    here gave error

    Warning: file_get_contents (https: //graph.facebook.com / …………) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP / 1.1 403 Forbidden in …………….. / test.php on line 30

    could help me?

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>