Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Facebook API using insights php sdk

I'm struggling pulling data with the GRAPH API in php. I am not understanding the docs that well on Facebook Developers. I also cannot find any examples to help either. I would like to have my API give me the following (between the first of the month and last day of the month):

  • New Likes
  • Visits
  • Organic Reach (monthly totals)
  • Organic Reach (for each day in the month)
  • Paid Reach (monthly totals)
  • Paid Reach (for each day in the month)
  • Cost to date
  • Engagement
  • Organic Impressions
  • Paid Impressions

I have gotten as far as being able to pull data, but when I test to use the insights portions it doesn't give me data. For example I have this:

// Sets the default fallback access token so we don't have to pass it to each request
$fb->setDefaultAccessToken('{access-token}');

try {
  $response = $fb->get('/{page-id}/insights/page_impressions?since=1443650400&until=1446246000', $accessToken);
  $graphEdge = $response->getGraphEdge();
} 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: ' . $e->getMessage();
  exit;
}

And it returns this:

Facebook\GraphNodes\GraphEdge Object
(
    [request:protected] => Facebook\FacebookRequest Object
        (
            [app:protected] => Facebook\FacebookApp Object
                (
                    [id:protected] => *******************
                    [secret:protected] => ********************
                )

            [accessToken:protected] => *******************
            [method:protected] => GET
            [endpoint:protected] => /{page-id}/insights/page_impressions?since=1443650400&until=1446246000
            [headers:protected] => Array
                (
                    [Content-Type] => application/x-www-form-urlencoded
                )

            [params:protected] => Array
                (
                )

            [files:protected] => Array
                (
                )

            [eTag:protected] => 
            [graphVersion:protected] => v2.5
        )

    [metaData:protected] => Array
        (
            [paging] => Array
                (
                    [previous] => https://graph.facebook.com/v2.5/{page-id}/insights/page_impressions?access_token=*******************&appsecret_proof=*******************&since=1440968400&until=1443564000
                    [next] => https://graph.facebook.com/v2.5/{page-id}/insights/page_impressions?access_token=*******************&appsecret_proof=*******************&since=1446159600&until=1448755200
                )

        )

    [parentEdgeEndpoint:protected] => 
    [subclassName:protected] => 
    [items:protected] => Array
        (
        )

)

I don't see any information in there that I can use and that is just for the page_impressions. I have even changed the dates to start at July 31st before and end on October 31st and still got nothing. My two questions are: 1. What did I do wrong? 2. How to make multiple calls to get all of the data in the list above?

Thank you in advanced!

like image 888
kingcobra1986 Avatar asked Nov 20 '15 22:11

kingcobra1986


1 Answers

  1. What did I do wrong?

Since the response didn't throw error, please make sure you meets these requirements:

  1. For Insights metrics that were not publicly available (page_impressions, page_stories, etc.), your access token must have read_insights permission.
  2. Insights are only generated for a Facebook Page that has more than 30 people that like it. (Your Facebook Page must have > 30 followers)

For point 1, Facebook Graph Api will not throw error if you don't have the permission, it just won't give you the data (because it's not public). For this, you must apply a submission for read_insight permission for your Facebook App and get reviewed by the Facebook team for approval.

Or (the-not-recommended-way) check: How to get a never expiring Facebook Page Access Token

This is how to show your metrics data using Graph Api Explorer:

  1. Login to Graph Api Explorer
  2. Click 'Get Token' and then 'Get User Access Token'

    enter image description here

  3. Click 'Extended Permissions' tab and check read_insights and click Get Access Token.

    enter image description here

  4. Grant yourself the permissions you requested.

  5. Now enter a test query into the Graph API query field and click submit:

    enter image description here

There you will see your metrics' datas. If it's not generating any data, then it's because point 2. (must have > 30 Likes)

  1. How to make multiple calls to get all of the data in the list above?

Facebook allows batch request, example using php-sdk:

$fb = new Facebook\Facebook([
  'app_id' => '{app-id}',
  'app_secret' => '{app-secret}',
  'default_graph_version' => 'v2.5',
  ]);

$fb->setDefaultAccessToken('user-access-token');

// Example : Get page impression
$requestPageImpression = $fb->request('GET', '/{page-id}/insights/page_impressions?since=1443650400&until=1446246000"');

// Example : Get Organic page impressions
$requestPageImpressionOrganic = $fb->request('GET', '{page-id}/insights/page_impressions_organic');

// Add more variable and API req, according to your list
// $requestPageStories = $fb->request('GET','....');
// etc...

$batch = [
    'page-impression' => $requestPageImpression,
    'page-impression-organic' => $requestPageImpressionOrganic, 
    // add more for your list
    ];

echo '<h1>Make a batch request</h1>' . "\n\n";

try {
  $responses = $fb->sendBatchRequest($batch);
} 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: ' . $e->getMessage();
  exit;
}

foreach ($responses as $key => $response) {
  if ($response->isError()) {
    $e = $response->getThrownException();
    echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
    echo '<p>Graph Said: ' . "\n\n";
    var_dump($e->getResponse());
  } else {
    echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
    echo "Response: " . $response->getBody() . "</p>\n\n";
    echo "<hr />\n\n";
  }
}
like image 137
cwps Avatar answered Oct 23 '22 19:10

cwps