FaceBookAPIで、広告キャンペーンを作成


概要

FaceBookAPIを使用して広告キャンペーンを作成する際のコードにちょっとハマったので備忘録的に書き留めておきます。

キャンペーン作成コード

Laravel用に書いてます。

  public function createCampain(Request $request)
    {
        $url = 'https://graph.facebook.com/v9.0/act_' . '広告アカウントID' . '/campaigns';

        $data = [
            'name'                  => 'キャンペーン名',
            'objective'             => 'LINK_CLICKS',
            'status'                => 'PAUSED',
            'special_ad_categories' => '[]',
            'access_token'          => 'アクセストークン',
        ];

        $data = http_build_query($data, "", "&");

        $header = [
            "Content-Type: application/x-www-form-urlencoded",
            "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
        ];

        $options = [
            'http' => [
                    'method'  => 'POST',
                    'header'  => implode("\r\n", $header), 
                    'content' => $data
                ]
        ];

        $json   = file_get_contents($url, false, stream_context_create($options));
        $json   = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
        $result = json_decode($json, true);
    }

ちなみにキャンペーン取得コード

    public function getCampain(Request $request)
    {
        $url = 'https://graph.facebook.com/v9.0/act_' . '広告アカウントID' . '/campaigns';

        $data = http_build_query(
            [
                'fields'            => "name",
                'access_token'      => "アクセストークン",
            ]
        );

        $header = [
            "Content-Type: application/x-www-form-urlencoded",
            "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
        ];

        $options = [
            'http' => [
                    'method' => 'GET',
                    'header' => implode("\r\n", $header), 
                ]
        ];

        $json   = file_get_contents($url . '?' . $data, false, stream_context_create($options));
        $json   = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
        $result = json_decode($json, true);
    }

あとがき

広告や広告セットもURLの最後を/campaigns→/adsに変えるくらいで動くと思います。