> For the complete documentation index, see [llms.txt](https://docs.exoclick.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.exoclick.com/api/ja/exoclick-paburikku-api/api-manual-php-examples.md).

# PHP の例

## 概要

このセクションのコードサンプルでは、以下のクラスをすべて使用します。

Requestクラスは **cURL** を使用してAPIへのリクエストを行います。

ResponseクラスにはAPIレスポンスと返されたステータスコード情報が含まれます。

<details>

<summary>RequestクラスとResponseクラス</summary>

```php
class Request {

        /**
         * @var resource
         */
        protected $_request;

        /**
         * @var 整数
         */
        protected $_method;

        /**
         * @var 文字列
         */
        protected $_url;

        /**
         * @var 配列
         */
        protected $_headers = array(
            'Content-type: application/json'
        );

        /**
         * @var 文字列|配列
         */
        protected $_params;

        /**
         * @var Responseオブジェクト
         */
        protected $_reponse;

        /**
         * コンストラクタ
         *
         * @param   string      $url
         * @param   string      $method
         * @param   array       $params
         */
        public function __construct($url, $method, $params = array()) {

            $this->_url = $url;

            // メソッドを設定
            $this->_method = $method;

            // パラメータを設定
            $this->_params = $params;
        }

        /**
         * Requestメソッドを決定
         *
         * @param   string  $method
         */
        private function setMethod() {

            switch($this->_method) {
                case 'GET':
                    break;
                case 'POST':
                    curl_setopt($this->_request, CURLOPT_POST, 1);
                    break;
                case 'PUT':
                    curl_setopt($this->_request, CURLOPT_CUSTOMREQUEST, 'PUT');
                    break;
                case 'DELETE':
                    curl_setopt($this->_request, CURLOPT_CUSTOMREQUEST, 'DELETE');
                    break;
            }
        }

        /**
         * 認証ヘッダーを追加
         *
         * @param   string  $type
         * @param   string  $token
         */
        public function setAuthorizationHeader($type, $token) {

            $authorization = $type . ' ' . $token;

            $this->_headers[] = 'Authorization: ' . $authorization;
        }

        /**
         * リクエストに本文を追加
         */
        private function addBody() {

            if($this->_method != 'GET' && empty($this->_params) == false) {

                if(is_array($this->_params)) {
                    // 配列をJSONエンコードする
                    $this->_params = json_encode($this->_params);
                }

                curl_setopt($this->_request, CURLOPT_POSTFIELDS, $this->_params);

                // Content-lengthヘッダーを追加
                $this->_headers[] = 'Content-length: ' . strlen($this->_params);
            }
        }

        /**
         * リクエストにクエリ文字列を追加
         */
        private function addQueryString() {

            if($this->_method == 'GET' && is_array($this->_params) && count($this->_params) > 0) {

                $query_string = '?';

                foreach($this->_params as $param => $value) {

                    $query_string = $query_string . $param . '=' . $value . '&';
                }

                trim($query_string, '&');

                $this->_url = $this->_url . $query_string;
            }
            else {

                if(is_array($this->_params) && count($this->_params) > 0 && strpos($this->_url, '{') !== false) {
                    // パラメータをURLに対してパターンマッチする
                    foreach($this->_params as $param => $value) {
                        $this->_url = preg_replace('/{' . $param . '}/', $value, $this->_url);
                    }
                }
            }
        }

        /**
         * リクエストを送信
         */
        public function send() {

            // cURLリクエストを初期化
            $this->_request = curl_init();

            // レスポンスを文字列として返す
            curl_setopt($this->_request, CURLOPT_RETURNTRANSFER, 1);

            // クエリ文字列を追加
            $this->addQueryString();

            // URLを設定
            curl_setopt($this->_request, CURLOPT_URL, $this->_url);

            // リクエストメソッドを設定
            $this->setMethod();

            // 本文を追加
            $this->addBody();

            if(empty($this->_headers) == false) {
                // ヘッダーを設定
                curl_setopt($this->_request, CURLOPT_HTTPHEADER, $this->_headers);
            }

            // SSLチェックを無効化
            curl_setopt($this->_request, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($this->_request, CURLOPT_SSL_VERIFYHOST, false);

            // リクエストを送信して本文を保存
            $this->_response = new Response(curl_exec($this->_request));

            // ステータスコードを設定
            $this->_response->setStatusCode(curl_getinfo($this->_request, CURLINFO_HTTP_CODE));

            // 接続を閉じる
            curl_close($this->_request);
        }

        /**
         * レスポンスを取得
         *
         * @return オブジェクト
         */
        public function getResponse() {

            return $this->_response;
        }
    }

    class Response {

        /**
         * @var 配列
         */
        protected $_reason_phrases = array(
            // 情報応答 1xx
            100 => "継続",
            101 => "プロトコルを切り替え",

            // 成功 2xx
            200 => "OK",
            201 => "作成されました",
            202 => "受理されました",
            203 => "権威のない情報",
            204 => "コンテンツなし",
            205 => "コンテンツをリセット",
            206 => "部分的なコンテンツ",

            // リダイレクト 3xx
            300 => "複数の選択肢",
            301 => "永続的に移動しました",
            302 => "見つかりました",
            303 => "他を参照",
            304 => "変更されていません",
            305 => "プロキシを使用",
            306 => "（未使用）",
            307 => "一時的なリダイレクト",

            // クライアントエラー 4xx
            400 => "不正なリクエスト",
            401 => "認証されていません",
            402 => "支払いが必要",
            403 => "禁止されています",
            404 => "見つかりません",
            405 => "メソッドは許可されていません",
            406 => "受け入れられません",
            407 => "プロキシ認証が必要",
            408 => "リクエストタイムアウト",
            409 => "競合",
            410 => "なくなりました",
            411 => "長さが必要",
            412 => "前提条件に失敗しました",
            413 => "リクエストエンティティが大きすぎます",
            414 => "Request-URIが長すぎます",
            415 => "サポートされていないメディアタイプ",
            416 => "要求した範囲は満たせません",
            417 => "期待に失敗しました",

            // サーバーエラー 5xx
            500 => "サーバー内部エラー",
            501 => "実装されていません",
            502 => "不正なゲートウェイ",
            503 => "サービス利用不可",
            504 => "ゲートウェイタイムアウト",
            505 => "HTTPバージョンはサポートされていません"
        );

        /**
         * @var 整数
         */
        protected $_status_code;

        /**
         * @var 文字列
         */
        protected $_body;

        /**
         * コンストラクタ
         *
         * @param   string      $body
         */
        public function __construct($body) {

            $this->_body = $body;
        }

        /**
         * コンストラクタ
         *
         * @param   string      $status_code
         */
        public function setStatusCode($status_code) {

            $this->_status_code = $status_code;
        }

        /**
         * ステータスコードを取得
         *
         * @return  整数
         */
        public function getStatusCode() {

            return $this->_status_code;
        }

        /**
         * 本文を取得
         *
         * @return  文字列
         */
        public function getBody() {

            return $this->_body;
        }

        /**
         * 本文をJSONデコードして取得
         *
         * @return  オブジェクト|null
         */
        public function getBodyDecoded() {

            return json_decode($this->_body);
        }

        /**
         * 理由フレーズを取得
         *
         * @return 文字列|真偽値
         */
        public function getReasonPhrase() {

            if(array_key_exists($this->_status_code, $this->_reason_phrases)) {

                return $this->_reason_phrases[$this->_status_code];
            }
            else {

                return false;
            }
        }
    }
```

</details>

## ログイン

以下の2つの方法で **ログイン** ルートを要求できます:

* ユーザー名とパスワードで
* APIトークン（アクセストークン）で

ユーザー名とパスワードのパラメータを使用したログインの例。

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/login';

    $params = array(
        'username'  => 'sample_username',
        'password'  => 'sample_password'
    );

    // 新しいRequestオブジェクトを作成
    $request = new Request($url, 'POST', $params);

    // リクエストを送信
    $request->send();

    // Responseオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        // セッショントークンの詳細を取得
        $token = $response->getBodyDecoded();

        print_r($token);
    }
    else {

        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody() . PHP_EOL;
    }
?>
```

### APIトークン（アクセストークン）を使用したログインの例

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/login';

    $params = array(
            'api_token'  => 'sample_token_2bb447abb71b69368901a....'
        );

    // 新しいRequestオブジェクトを作成
    $request = new Request($url, 'POST', $params);

    // リクエストを送信
    $request->send();

    // Responseオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        // セッショントークンの詳細を取得
        $token = $response->getBodyDecoded();

        print_r($token);
    }
    else {

        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody() . PHP_EOL;
    }
?>
```

## 認証

ユーザー関連コンテンツへの各リクエストでは、 **Authorization** ヘッダーを設定する必要があり、その値にはトークン種別とAPIのログインリクエストで受け取ったセッショントークンを含めます。

有効な **/login** APIへのリクエストは次のjsonペイロードを返します。

```json
{
  "token": "",
  "type": "",
  "expires_in": 0
}
```

その **セッショントークン** は、その後のすべてのユーザー関連コンテンツへのAPIリクエストに含める必要があります。

その **type** は、トークンの前に単一のスペースで区切って付ける必要があります。

```
Bearer 4e63518d383d8fcaefb516fe708b893727463031
```

その **expires\_in** は、トークンが有効である秒数です。この時間が切れると、/loginリクエストを通じて新しいトークンを取得する必要があります。

### ユーザー名とパスワードを使用した認証ヘッダーの取得と設定の例

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    // ログイン
    $url = 'https://api.example.com/v2/login';

    $params = array(
        'username'  => 'sample_username',
        'password'  => 'sample_password'
    );

    // 新しいRequestオブジェクトを作成
    $request = new Request($url, 'POST', $params);

    // リクエストを送信
    $request->send();

    // Responseオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        // セッショントークンの詳細を取得
        $token = $response->getBodyDecoded();

        // キャンペーンを取得
        $url = 'https://api.example.com/v2/campaigns';

        // 新しいRequestオブジェクトを作成
        $request = new Request($url, 'GET');

        // 認証ヘッダーを設定
        $request->setAuthorizationHeader($token->type, $token->token);

        // リクエストを送信
        $request->send();

        // Responseオブジェクトを取得
        $response = $request->getResponse();

        if($response->getStatusCode() == 200) {

            // キャンペーンを取得
            $campaigns = $response->getBodyDecoded();

            foreach($campaigns->result as $campaign) {
                // キャンペーン名を表示
                echo $campaign->name . PHP_EOL;
            }
        }
        else {
            // キャンペーンリクエストのエラー
            echo $response->getStatusCode() . PHP_EOL;
            echo $response->getReasonPhrase() . PHP_EOL;
            echo $response->getBody();
        }
    }
    else {
        // ログイン無効
        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody();
    }
?>
```

### APIトークンを使用した認証ヘッダーの取得と設定の例

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    // ログイン
    $url = 'https://api.example.com/v2/login';

    $params = array(
        'api_token'  => 'sample_token_2bb447abb71b69368901a....'
    );

    ...

?>
```

## コレクション

以下は、 **ブラウザ** コレクションを取得するリクエストの例です。

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/collections/browsers';

    // 新しいRequestオブジェクトを作成
    $request = new Request($url, 'GET');

    // 先ほどのログインリクエストで取得した認証ヘッダーを設定
    $request->setAuthorizationHeader($token->type, $token->token);

    // リクエストを送信
    $request->send();

    // Responseオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        $browsers = $response->getBodyDecoded();

        foreach($browsers as $browser) {

            echo $browser->id . ': ' . $browser->name . PHP_EOL;
        }
    }
    else {
        // コレクションが見つかりません
        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody();
    }
?>
```

## 統計

以下は、広告主が **statistics/a/date**.

場合 **additional\_group\_by** という値が定義されている場合、リクエストはメインのルートフィールドと追加のフィールドでグループ化されます。

### キャンペーンID 1234でフィルタした日付別統計の例。

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/statistics/a/date';

    // キャンペーンIDを指定
    $params = array(
       'campaignid'  => 1234
    );

    $request = new Request($url, 'GET', $params);

    // 先ほどのログインリクエストで取得した認証ヘッダーを設定
    $request->setAuthorizationHeader($token->type, $token->token);

    // リクエストを送信
    $request->send();

    // レスポンスオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        $statistics = $response->getBodyDecoded();

        foreach($statistics->result as $statistic) {

            echo $statistic->ddate . ': ' . $statistic->value . PHP_EOL;
        }
    }
    else {
        // キャンペーン統計が見つかりません
        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody();
    }
?>
```

### キャンペーンでの追加グループ化を含む日付別統計の例。

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/statistics/a/date';

    // キャンペーンIDを指定
    $params = array(
       'additional_group_by'  => 'campaign'
    );

    $request = new Request($url, 'GET', $params);

    // 先ほどのログインリクエストで取得した認証ヘッダーを設定
    $request->setAuthorizationHeader($token->type, $token->token);

    // リクエストを送信
    $request->send();

    // レスポンスオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        $statistics = $response->getBodyDecoded();

        foreach($statistics->result as $statistic) {
            echo $statistic->ddate . ' - ' . $statistic->idcampaign . ': ' . $statistic->value . PHP_EOL;
        }
    }
    else {
        // キャンペーン統計が見つかりません
        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody();
    }
?>
```

post /statistics/a/global

広告主のグローバル統計を取得

### グローバル統計の例1

グローバル統計リクエストの例。

必須なのは `group_by` パラメータのみです。その他のパラメータのデフォルト値は [こちら](https://api.exoclick.com/v2/docs/#!/47statistics/post_statistics_a_global).

グローバル統計ルート（`statistics/a/global`, `statistics/p/global`）については、パラメータ形式が異なりますのでご注意ください。

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/statistics/a/global';

    // group_byを指定
    $params = [
        "group_by" => ["date"]
    ];

    $request = new Request($url, 'POST', $params);

    // 先ほどのログインリクエストで取得した認証ヘッダーを設定
    $request->setAuthorizationHeader($token->type, $token->token);

    // リクエストを送信
    $request->send();

    // レスポンスオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        $statistics = $response->getBodyDecoded();

        foreach($statistics->result as $statistic) {
            echo '日付: ' . $statistic->group_by->date->date . ' -  インプレッション: ' . $statistic->impressions .' - コスト: ' .  $statistic->cost . PHP_EOL;
        }
    }
    else {
        // キャンペーン統計が見つかりません
        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody();
    }
?>
```

### グローバル統計の例2

合計値を含む日付別統計を取得します。

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/statistics/a/global';

    // キャンペーンIDを指定
    $params = [
        "filter" => [
            "date_from" => "2019-01-10",
            "date_to" => "2019-01-31",
        ],
        "totals" => 1,
        "group_by" => ["date"]
    ];

    $request = new Request($url, 'POST', $params);

    // 先ほどのログインリクエストで取得した認証ヘッダーを設定
    $request->setAuthorizationHeader($token->type, $token->token);

    // リクエストを送信
    $request->send();

    // レスポンスオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        $statistics = $response->getBodyDecoded();

        foreach($statistics->result as $statistic) {
            echo '日付: ' . $statistic->group_by->date->date . ' -  インプレッション: ' . $statistic->impressions .' - コスト: ' .  $statistic->cost . PHP_EOL;
        }

        echo '合計コスト:' . $statistics->result_total->cost . PHP_EOL;
    }
    else {
        // キャンペーン統計が見つかりません
        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody();
    }
?>
```

### グローバル統計の例3

指定日でフィルタし、インプレッション順に並べたキャンペーン別・国別統計を取得します。

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/statistics/a/global';

    $params = [
        "filter" => [
            "date_from" => "2019-01-30",
            "date_to" => "2019-01-30",
        ],
        "group_by" => ["country_iso", "campaign_id"],
        "order_by" => [
            ["field" => "impressions", "order" => "desc"]
        ]
    ];


    $request = new Request($url, 'POST', $params);

    // 先ほどのログインリクエストで取得した認証ヘッダーを設定
    $request->setAuthorizationHeader($token->type, $token->token);

    // リクエストを送信
    $request->send();

    // レスポンスオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        $statistics = $response->getBodyDecoded();

        foreach($statistics->result as $statistic) {
            echo '国: ' . $statistic->group_by->country_iso->country_iso . ' -  キャンペーンID: ' . $statistic->group_by->campaign_id->id .' - コスト: ' .  $statistic->cost . PHP_EOL;
        }
    }
    else {
        // キャンペーン統計が見つかりません
        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody();
    }
?>
```

### グローバル統計の例4

特定のオペレーティングシステムでフィルタした、ゾーン別・国別のパブリッシャー統計を取得します。

```php
<?php

    // RequestクラスとResponseクラスを読み込む

    $url = 'https://api.example.com/v2/statistics/p/global';

    $params = [
        "filter" => [
            "date_from" => "2019-01-30",
            "date_to" => "2019-01-30",
            "operating_system_id" => [11, 12]
        ],
        "group_by" => ["zone_id", "country_iso"]
    ];


    $request = new Request($url, 'POST', $params);

    // 先ほどのログインリクエストで取得した認証ヘッダーを設定
    $request->setAuthorizationHeader($token->type, $token->token);

    // リクエストを送信
    $request->send();

    // レスポンスオブジェクトを取得
    $response = $request->getResponse();

    if($response->getStatusCode() == 200) {

        $statistics = $response->getBodyDecoded();

        foreach($statistics->result as $statistic) {
            echo ' ゾーンID: ' . $statistic->group_by->zone_id->id . ' - 国: ' . $statistic->group_by->country_iso->country_iso .' - 収益: ' .  $statistic->revenue . PHP_EOL;
        }
    }
    else {
        // キャンペーン統計が見つかりません
        echo $response->getStatusCode() . PHP_EOL;
        echo $response->getReasonPhrase() . PHP_EOL;
        echo $response->getBody();
    }
?>
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.exoclick.com/api/ja/exoclick-paburikku-api/api-manual-php-examples.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
