Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook PHP app, how to detect it's in Canvas or Page mode?

Tags:

php

facebook

In an iframe .php app, how to detect itself is in a Page mode or in the Canvas mode? Thanks!

like image 522
ohho Avatar asked Apr 15 '11 01:04

ohho


1 Answers

Reading the documentation:

  1. Facebook will always send a signed_request (for canvas and page urls)
  2. If it's a page, Facebook will add an extra parameter called page

so based on this, you could do something like:

<?php
if( isset($_REQUEST['signed_request']) ) {
    // We are in Canvas or Page now

    // Let's extract the data from the signed_request 
    // to check if we are inside a Facebook Page
    $app_secret = "APP_SECRET";
    $data = parse_signed_request($_REQUEST["signed_request"], $app_secret);

    if( isset($data["page"]) ) {
        echo "Page";
    } else {
        echo "Canvas";
    }
} else {
    echo "None, or something went wrong!";
}

function parse_signed_request($signed_request, $secret) {
    list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

    // decode the data
    $sig = base64_url_decode($encoded_sig);
    $data = json_decode(base64_url_decode($payload), true);

    if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
        error_log('Unknown algorithm. Expected HMAC-SHA256');
        return null;
    }

    // check sig
    $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
    if ($sig !== $expected_sig) {
        error_log('Bad Signed JSON signature!');
        return null;
    }

    return $data;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}

?>
like image 62
ifaour Avatar answered Oct 20 '22 00:10

ifaour