Friday, February 8, 2019

phpMyPassion

How To Integrate Facebook PHP SDK With Laravel 5.4


In this article I am explaining a simple process to setup Facebook Marketing SDK by PHP Artisan Command with laravel 5.4. You can get campaigns or your ad account data either setting up a cron using created command or running command on terminal.

First, edit composer.json in the project's root folder to include the Facebook SDK:



{    "require": {
        "facebook/php-business-sdk": "3.1.*"    }
}



Next run composer update at shell prompt to pull in the sdk to the vendor folder.


php composer.phar install --no-dev

If you do not have composer.phar in your Laravel project just copy that file to your project from Facebook Business SDK for PHP

Now we would like to use the Facebook SDK within our app as a command. But before doing that, let us setup our app_id, app_secret and default_graph_version which are parameters required while making requests to Facebook API. You can obtained app_id and app_secret from your Facebook App Settings.

Once we have these credentials from Facebook, we would now edit .env file in the project's root folder. Add them to the end:




FB_ADS_APP_ID="XXXXXXXXX"
FB_ADS_APP_SECRET="XXXXXXXXXXXXX"
FB_DEFAULT_GRAPH_VERSION=v3.2
FB_ACCESS_TOKEN="XXXXXXXXXXX"

Replace the xxx.. with the values provided to you. Note that the variable names are just my own creation. You can name them whatever you'd like. We would now have to use these variables to setup a separate config file. We need to do this so that we can use Laravel's config() helper function to retrieve the values wherever we want within the app. So let's create facebook-ads.php in the config folder and add the following:



return [
    'app_id' => env('FB_ADS_APP_ID', null),
    'app_secret' => env('FB_ADS_APP_SECRET', null),
    'default_graph_version' =>
env('FB_DEFAULT_GRAPH_VERSION', 'v2.8'),];
];



Now we have to create a class FacebookAdsService.php with below command..


php artisan make:console FacebookAdsService



<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class FacebookAdsService extends Command
{   
   /**
    * The name and signature of the console command.
    */
   protected $signature = 'facebook_sdk:service';
    /** 
     *The console command description.
     * @var string 
     */ 
   protected $description = 'Facebook ads api for campaign 
                            service, adset etc';    /** 
     * Create a new command instance.
     * @return void
     */    
   public function __construct(){
        parent::__construct();    
   }
   /** 
    * Execute the console command.
    * @return mixed 
    */    
   public function handle()    {
      //Your Code Goes Hare
    }
}


You have to write your all code to get facebook campaign & their reporting in the handle() function.

Now to run this command on our terminal we have to register it in Kernal.php with path "/app/Console/kernel.php".

So add "Command\FacebookAdsService::class" in the $commands array as below -



protected $commands = [    
   Commands\FacebookAdsService::class
];


Now we have all setup to get campaign or adset reporting from facebook marketing api.

Now just add some classes at the top of our FacebookAdsService class that we gonna use to get campaign data.




use FacebookAds\Object\AdAccount;
use FacebookAds\Api;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;


Now write your code to get facebook campaign data in its handle() function as below -

We have to instantiate Api object first to make an facebook api call.

To instantiate an Api object you will need a valid access token:



$app_id = env('FB_ADS_APP_ID');
$app_secret = env('FB_ADS_APP_SECRET');
$access_token =  env('FB_ACCESS_TOKEN');
Api::init($app_id, $app_secret, $access_token);
$api = Api::instance();



Get adAccount details from object -




$account_id = 'act_XXXXXXXX';
$account = new AdAccount($account_id);
$account->read();



Get All Campaigns -




$fields = array(  'name',  'objective',  'start_time',);
$params = array(  
      'effective_status' => array('ACTIVE','PAUSED'),
       );
$r = json_encode($account->getCampaigns(
     $fields,  
     $params
     )->getResponse()->getContent(), JSON_PRETTY_PRINT);



Get All AdSet -




$fields = array(  
  AdSetFields::ID,
  AdSetFields::NAME,
  AdSetFields::STATUS,
  AdSetFields::START_TIME,
  AdSetFields::END_TIME
); $r = json_encode($account->getAdSets( $fields )->getResponse()->getContent(), JSON_PRETTY_PRINT);




Get Ad Insight -


You can change fields and parameters according to your need.
Check All Ads Insights Parameters and Fields



$fields = array(  
     'adset_id',  
     'adset_name',  
     'impressions',  
     'clicks',  
     'ctr',  
     'spend');
$params = array(  
     'time_increment' => '1',  
     'date_preset' =>  'lifetime',  
     'breakdowns' => array( 
         'hourly_stats_aggregated_by_advertiser_time_zone',
     ),
     'sort' => array(
        'date_start_ascending'
      ),
);

$cmp_id = XXXXXXXXX;

$data = json_encode((new AdSet($cmp_id))->getInsights(
     $fields,
     $params
     )->getResponse()->getContent(), JSON_PRETTY_PRINT);


Run your command on terminal -


php artisan facebook_sdk:service

You can see your output on the terminal.

If you found any difficulty in setting up Facebook Sdk with laravel, you can intimate me by comment.  


About Author -

Hi, I am Anil.

Welcome to my eponymous blog! I am passionate about web programming. Here you will find a huge information on web development, web design, PHP, Python, Digital Marketing and Latest technology.

Subscribe to this Blog via Email :

2 comments

Write comments
Unknown
AUTHOR
September 18, 2019 at 3:48 AM delete

First, Thank alot for this blog. As of now this is working when the app and ad_id are with same fb profile. How to get ad account details for any other fb profile users using my app? Thanks.

Reply
avatar
phpMyPassion
AUTHOR
September 20, 2019 at 2:11 AM delete

Its not possible to get all ad account of other users till the time he or she doesn't give you permission to access their ad account. Thanks.

Reply
avatar

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