Facebook Marketing API example - Get account details (PHP)

Posted By: Matpal Media - 6:03 PM
Facebook marketing API can be used to get data for your ad account and other information related to your ads such as analytics, insights etc. Following example tells you how to get ad account related to your facebook account.

Download PHP SDK for Facebook marketing API from here



Step 1 - Create a config file



<?php
//config.php
define('APP_ID','YOUR_APP_ID');
define('APP_SECRET','YOUR_APP_SECRET');
define('APP_CALLBACK','http://localhost/fbv2/callback.php');
define('SDK_VERSION','v2.9');
define('API_HOST','https://graph.facebook.com/');
?>


Step 2 - Login


<?php
//login.php
require_once 'Facebook/autoload.php'; //From Facebook SDK
require_once 'config.php';

$fb = new Facebook\Facebook(['app_id' => APP_ID,  'app_secret' => APP_SECRET,
'default_graph_version' => SDK_VERSION]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['email','ads_read','ads_management','read_insights',
'read_audience_network_insights']; // Optional permissions
$loginUrl = $helper->getLoginUrl(APP_CALLBACK, $permissions);

?>


Step 3- Callback.php


<?php
session_start();
require_once 'Facebook/autoload.php';
require_once 'config.php';

$fb = new Facebook\Facebook(['app_id' => APP_ID,'app_secret' => APP_SECRET,
'default_graph_version' => SDK_VERSION]);

$helper = $fb->getRedirectLoginHelper();
  $_SESSION['FBRLH_state']=$_GET['state'];


try 
{
  $accessToken = $helper->getAccessToken();
} 
catch(Facebook\Exceptions\FacebookResponseException $e) {
  
  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;
}

if (! isset($accessToken)) {
  if ($helper->getError()) {
    header('HTTP/1.0 401 Unauthorized');
    echo "Error: " . $helper->getError() . "\n";
    echo "Error Code: " . $helper->getErrorCode() . "\n";
    echo "Error Reason: " . $helper->getErrorReason() . "\n";
    echo "Error Description: " . $helper->getErrorDescription() . "\n";
  } else {
    header('HTTP/1.0 400 Bad Request');
    echo 'Bad request';
  }
  exit;
}

// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());

$oAuth2Client = $fb->getOAuth2Client();

$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);

$tokenMetadata->validateAppId(APP_ID); // Replace {app-id} with your app id

$tokenMetadata->validateExpiration();

if (! $accessToken->isLongLived()) 
{
  try {
    $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
  } catch (Facebook\Exceptions\FacebookSDKException $e) {
    echo "<p>Error getting long-lived access token:".$helper->getMessage()."</p>\n\n";
    exit;
  }

  echo '<h3>Long-lived</h3>';
  var_dump($accessToken->getValue());
}

$_SESSION['fb_access_token'] = (string) $accessToken;



//User Details


$me=API_HOST."/me";
$params=array("access_token"=>$_SESSION['fb_access_token'] ,"fields"=>"id,name");

$returnMe=(String) httpGet($me,$params);
$returnMe=json_decode($returnMe);

$_SESSION['username'] = $returnMe->name;
$_SESSION['userid'] = $returnMe->id;

header("Location:details.php");
?>




Final step , create detail.php for the details


<?php
session_start();
require_once "config.php";
$user=$_SESSION['username'];

$url="https://graph.facebook.com/v2.9/me/adaccounts";

$params=array("access_token"=>$_SESSION['fb_access_token'],
"fields"=>"name,id,status,account_id,summary,total_count");

$json=(String) httpGet($url,$params);
$respo=json_decode($json);

function httpGet($url,$params)
{
   $postData = '';
   //create name value pairs seperated by &
   foreach($params as $k => $v) 
   { 
      $postData .= $k . '='.$v.'&'; 
   }
   $postData = rtrim($postData, '&');
 
 
   $curl = curl_init();
   curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, false);
  
    curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => $url."?".$postData,
    CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));

$resp = curl_exec($curl);
curl_close($curl);
 
 return $resp;
 
}


?>

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.