Facebook广告Sdk不允许通过API发布广告。子代码:1487930

时间:2016-07-22 16:08:34

标签: facebook facebook-graph-api facebook-php-sdk facebook-ads-api

我已经阅读了很多关于facebook广告和内容的内容,使用GUI它可以做我正在做的事情,并且出于某些原因,它不会在sdk上发生。

我在Facebook广告sdk子代码 1487930 上得到了这个suberror代码。

消息说:

  

您必须选择要推广的对象,用户消息说明:您的广告系列必须>包括一个广告集,其中包含与您的目标相关的所选对象> > (例如:页面,URL,事件)。请更新您的广告集以继续。

响应不会返回任何字段,并且在创建广告素材时会发生错误:$creative->create();

我设置了这样的广告:

    use Facebook;
    use FacebookAds\Api;
    use FacebookAds\Object;
    use Facebook\Exceptions;

        $inventory = new Models\AdvertisingInventory();
        $item = $inventory->getListing($id)->getAttributes();
        $item['properties'] = json_decode($item['properties'], true);

        /**
         * Step 1 Instantiate an API
         *
         * @link https://developers.facebook.com/docs/marketing-api/sdks#init-sdk
         */

        try {
            Api::init($this->app_id, $this->app_secret, $this->access_token);
        } catch (\Exception $e) {
            return $this->AdvertisingRenderErrorMessage($e);
        }

        /**
         * Step 2 Query to create campaign
         * @var $campaign
         * @link https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group
         *
         * TODO: Implement ad image widget sizing: https://www.facebook.com/business/help/103816146375741
         */
        try {

            $account = new Object\AdAccount($this->current_facebook_ads_account);

            $campaign = new Object\Campaign(null, $this->current_facebook_ads_account); // Getting AdAccount instance

            $ad_campaigns = $account->getCampaigns($campaign::getFields())->getArrayCopy(); // Checks of there are any campaigns already created

            $current_campaign = null;

            if (!empty($ad_campaigns)) {
                foreach ($ad_campaigns as $ad_campaign) { // loops through campaigns
                    $campaign_data = $ad_campaign->exportAllData();
                    if ($campaign_data['name'] == 'Sell old inventory') { // If campaign name matches the name given to new campaign, created campaign is then used
                        $current_campaign = $ad_campaign;
                    }
                }
            }

            if (!is_null($current_campaign)) { // Checks if campaign is already assigned if yes, then its used.
                $campaign = $current_campaign;
            } else { // else new one is created
                $campaign->setData(array(
                    Object\Fields\CampaignFields::NAME => 'Sell old inventory',
                    Object\Fields\CampaignFields::OBJECTIVE => Object\Values\CampaignObjectiveValues::LINK_CLICKS,
                ));

                $campaign->validate()->create(array(
                    Object\Campaign::STATUS_PARAM_NAME => Object\Campaign::STATUS_PAUSED
                ));
            }

            //$campaignData = $campaign->getData();

            echo 'Campaign ID: ' . $campaign->id . " <br>\n";

        } catch (\Exception $e) {
            return $this->AdvertisingRenderErrorMessage($e);
        }

        /**
         * Step 3 Search for targeting topic
         * @var $targeting
         * @link https://developers.facebook.com/docs/marketing-api/targeting-specs/v2.7
         */
        try {
            $results = Object\TargetingSearch::search(
                Object\Search\TargetingSearchTypes::INTEREST,
                null,
                'Automobiles');

            $target = (count($results)) ? $results->current() : null;

            //if (!is_null($target)) {

            echo "Using target: " . $target->name . "<br/>";

            $targeting = new Object\Targeting();
            $targeting->{Object\Fields\TargetingFields::GEO_LOCATIONS} = array(
                'countries' => array('NZ')
            );
            $targeting->{Object\Fields\TargetingFields::INTERESTS} = array(
                array(
                    'id' => $target->id,
                    'name' => $target->name,
                ),
            );
            //}
        } catch (\Exception $e) {
            return $this->AdvertisingRenderErrorMessage($e);
        }

        /**
         * Step 4 Create an AdSet
         * @var $adset
         * @link https://developers.facebook.com/docs/marketing-api/reference/ad-campaign
         */
        try {

            $adset = new Object\AdSet(null, $this->current_facebook_ads_account);
            //$fields = $adset::getFields();

            $available_adsets = $campaign->getAdSets(array(Object\Fields\AdSetFields::NAME,Object\Fields\AdSetFields::ID));

            $current_adset = null;

            if (!empty($available_adsets)) {
                foreach ($available_adsets as $ad_set) { // loops through adsets
                    if ($adset->name == $item['title']) { // If adset name matches the name given to new campaign, created campaign is then used
                        $current_adset = $ad_set;
                    }
                }
            }

            if (!is_null($current_adset)) {
                $adset = $current_adset;
                /*$adset->read(array(
                    Object\Fields\AdSetFields::PROMOTED_OBJECT,
                    Object\Fields\AdSetFields::NAME
                ));
                echo $adset->name."<br>";
                echo $adset->promoted_object."<br>";*/
            } else {

                $start_time = (new \DateTime("+1 week"))->format(\DateTime::ISO8601);
                $end_time = (new \DateTime("+2 week"))->format(\DateTime::ISO8601);


                $adset->setData(array(
                    Object\Fields\AdSetFields::NAME => $item['title'],
                    Object\Fields\AdSetFields::OPTIMIZATION_GOAL => Object\Values\AdSetOptimizationGoalValues::LINK_CLICKS,
                    Object\Fields\AdSetFields::BILLING_EVENT => Object\Values\AdSetBillingEventValues::LINK_CLICKS,
                    Object\Fields\AdSetFields::BID_AMOUNT => 100,
                    Object\Fields\AdSetFields::DAILY_BUDGET => 500,
                    Object\Fields\AdSetFields::CAMPAIGN_ID => $campaign->id,
                    Object\Fields\AdSetFields::TARGETING => $targeting,
                    Object\Fields\AdSetFields::START_TIME => $start_time,
                    Object\Fields\AdSetFields::END_TIME => $end_time,
                    Object\Fields\AdSetFields::PROMOTED_OBJECT => (object) array(
                        Object\Fields\AdPromotedObjectFields::PAGE_ID => '178698438995498',
                    )
                ));
                $adset->create(array(
                    Object\AdSet::STATUS_PARAM_NAME => Object\AdSet::STATUS_PAUSED,
                ));
            }
            echo 'Adset ID: ' . $adset->id . " <br>\n";
        } catch (\Exception $e) {
            return $this->AdvertisingRenderErrorMessage($e);
        }


        //New method
        /**
         * Step 5 Create an AdImage
         * @var $image
         * @link https://developers.facebook.com/docs/marketing-api/reference/ad-image
         */
        try {
            $image = new Object\AdImage(null, $this->current_facebook_ads_account); // Invokes images preparation for Facebook ad instance
            $target_path = __DIR__ . '/assets/temp/'; // path where images will be streamed to

            if (!file_exists($target_path)) {
                mkdir($target_path, 0755); // creating path if one doesn't exist
            }

            $files_in_dir = array_diff(scandir($target_path), array('..', '.')); // checking for existing files in target directory
            $size = getimagesize($item['properties']['images_large'][0]); // getting image details
            $extension = image_type_to_extension($size[2]); // getting image extension from type
            $target_file_name = preg_replace(['/\./', '/\\s/', '/\\t/'], "_", strtolower($item['title'])) . $extension; // creating proper file name
            $target_file = $target_path . $target_file_name; // setting full target directory

            if (array_search($target_file_name, $files_in_dir) === false) { // checking if target file already exists

                $image_file = file_get_contents($item['properties']['images_large'][0]);

                file_put_contents($target_file, $image_file);
            }

            $image->{Object\Fields\AdImageFields::FILENAME} = $target_file; // Using target file as ad image

            $image->create();

            echo 'Image Hash: ' . $image->hash . " <br>\n";
        } catch (\Exception $e) {
            return $this->AdvertisingRenderErrorMessage($e);
        }

        /**
         * Step 6 Create an AdCreative
         */
        try {

            $creative = new Object\AdCreative(null, $this->current_facebook_ads_account);

            $available_creatives = $adset->getAdCreatives($creative::getFields());

            $current_creative = null;

            if (!empty($available_creatives)) {
                foreach ($available_creatives as $creative) { // loops through adsets
                    if ($creative->name == 'Creative of '.$item['title']) { // If adset name matches the name given to new campaign, created campaign is then used
                        $current_creative = $creative;
                    }
                }
            }

            if (!is_null($current_creative)) {
                $creative = $current_creative;
            } else {

                $creative = new Object\AdCreative(null, $this->current_facebook_ads_account);
                $creative->setData(array(
                    Object\Fields\AdCreativeFields::NAME => 'Creative of '.$item['title'],
                    Object\Fields\AdCreativeFields::TITLE => $item['title'],
                    Object\Fields\AdCreativeFields::BODY => $item['properties']['description'],
                    Object\Fields\AdCreativeFields::IMAGE_HASH => $image->hash,
                    Object\Fields\AdCreativeFields::LINK_URL => ipConfig()->get('globalPortalUrl'),
                    Object\Fields\AdCreativeFields::OBJECT_URL => ipConfig()->get('globalPortalUrl'),
                ));
                **$creative->create();**
            }
            echo 'Creative ID: ' . $creative->id . " <br>\n";
        } catch (\Exception $e) {
            return $this->AdvertisingRenderErrorMessage($e);
        }


        /**
         * Step 7 Create an Ad
         *
         * Then, use the image hash returned from above. Finally, create your ad along with ad creative.
         * Please note that the ad creative is not created independently, rather its data structure
         * is appended to the ad group
         *
         * @link https://developers.facebook.com/docs/marketing-api/reference/adgroup
         */
        try {

            $ad = new Object\Ad(null, $this->current_facebook_ads_account);

            $last_ad = $adset->getAds($ad::getFields())->end()->exportData();

            //var_dump($last_ad); exit();

            $ad->setData(array(
                Object\Fields\AdFields::NAME => $item['title'].' #1',
                Object\Fields\AdFields::ADSET_ID => $adset->id,
                Object\Fields\AdFields::CREATIVE => array('creative_id' => $creative->id),
            ));
            $ad->create(array(
                Object\Ad::STATUS_PARAM_NAME => Object\Ad::STATUS_PAUSED,
            ));
            echo 'Ad ID:' . $ad->id . " <br>\n";

        } catch (\Exception $e) {
            return $this->AdvertisingRenderErrorMessage($e);

        }

我已将该页面分配到我的商家帐户以及该查询所通过的应用,用户也是该商家帐户,应用和页面的所有者。

如果提供了网页ID,还需要什么? 广告系列的目标是:

Object\Fields\CampaignFields::OBJECTIVE => Object\Values\CampaignObjectiveValues::LINK_CLICKS

我使用有效的 page_id 。我错过了一些额外的数据(FYI尝试了这个没有(对象)typehint):

Object\Fields\AdSetFields::PROMOTED_OBJECT => (object) array(
    Object\Fields\AdPromotedObjectFields::PAGE_ID => '178698438995498',
)

或者应用,网页和商家帐户设置存在问题?

请有人接听我的电话。试过几乎所有事都无法通过这一点。任何其他提升的对象都不适用于广告系列目标。

P.S。名声超过1500的人请创建ne facebook-php-ads-sdk标签。

3 个答案:

答案 0 :(得分:1)

我认为LINK_CLICKS目标不需要提升对象。你有没有尝试过设置它?

广告集

Facebook docs创建部分,字段promoted_object

  

某些广告系列目标需要

并且LINK_CLICKS目标没有列在那里。

或者,您可以通过FB界面(广告管理器或电源编辑器)创建包含所需参数的广告,然后通过API读取其值,以查看填充了哪些字段以及使用了哪些值。

答案 1 :(得分:1)

我遇到此错误,因为我在创建Adcreative时使用了错误的参数名称。我使用page_id代替object_id

希望它可以帮助别人。

答案 2 :(得分:0)

您需要确保您的广告系列目标符合您的最佳化目标。尝试广告系列目标时,我遇到了同样的问题:LINK_CLICKS和AdsetOptimizationGoal:REACH。有道理,这行不通。

这是我正在工作的代码:

广告系列创建:

$fields = [];
$params = [
        'name' => 'My campaign_3',
        'objective' => 'LINK_CLICKS',
        'status' => 'PAUSED',
    ];

    $cmpId = null;
    try {
        $cmpId = $campaign = (new AdAccount('act_' . $this->adAccountId))->createCampaign(
            $fields,
            $params
        );
    } catch (Exception $e) {
        dump('Exception with message: ' . $e->getMessage());
        dump($e->getResponse());
    }

创建广告:

$adset = new AdSet(null, 'act_301136867381876');
$adset->setData(array(
        AdSetFields::NAME => 'My Ad Set',
        AdSetFields::OPTIMIZATION_GOAL => AdSetOptimizationGoalValues::LINK_CLICKS,
        AdSetFields::BILLING_EVENT => AdSetBillingEventValues::IMPRESSIONS,
        AdSetFields::BID_AMOUNT => 10,
        AdSetFields::DAILY_BUDGET => 100,
        AdSetFields::CAMPAIGN_ID => $cmpId,
        AdSetFields::TARGETING => $targeting,
        AdSetFields::START_TIME => $start_time->format(DateTime::ISO8601),
        AdSetFields::END_TIME => $end_time->format(DateTime::ISO8601),
        AdSetFields::DESTINATION_TYPE => 'WEBSITE'
    ));