Search code examples
facebookfacebook-php-sdkads

Retrieve Lead Ads Facebook API


I have problems retrieving Lead Ads.

I have the Ad-ID and the Page-ID. I haven't created them, but was added as a developer.

I was trying to use the PHP SDK and this https://developers.facebook.com/docs/marketing-api/guides/lead-ads/v2.9

Nothing is working. I cannot find a nice tutorial about that. I just want to retrieve the leading Ads!

Anyone?


Solution

  • Assuming you have already installed FB API SDK and configured your FB app, you can use this to get all results from all LeadAds of your $page_id

    use FacebookAds\Api;
    use FacebookAds\Object\Page;
    use FacebookAds\Object\Ad;
    
    $access_token = 'YOUR TOKEN';
    $app_id = 'YOUR APP ID';
    $app_secret = 'YOUR APP SECRET';
    
    $page_id = 'YOUR PAGE ID';
    
    Api::init($app_id, $app_secret, $access_token);
    
    $ads = getAllLeadsAds($page_id);
    
    $result = array();
    
    foreach ($ads->data as $item) {
    
        $leads = getLeadAdInfo($item->id);
        $i = 0;
        foreach ($leads->data as $value) {
            $result[$i]['ad_id'] = $item->id;
            $result[$i]['lead_id'] = $value->id;
            $result[$i]['form'] = $value->field_data;
            $i++;
        }
    }
    
    print_r($result);
    
    function getAllLeadsAds($page)
    {
        $page = new Page($page);
        return $page->getLeadgenForms()->getResponse()->getBody();
    }
    
    function getLeadAdInfo($ad)
    {
        $ad = new Ad($ad);
        return $ad->getLeads()->getResponse()->getBody();
    }