Skip to main content

PHP-Beispiele

Übersicht

Die Codebeispiele in diesem Abschnitt verwenden alle die folgenden Klassen.

Die Klasse Request verwendet cURL, um die Anfragen an die API zu stellen.

Die Klasse Response enthält die API-Antwort und die zurückgegebenen Statuscode-Informationen.


class Request {

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

/**
* @var integer
*/
protected $_method;

/**
* @var string
*/
protected $_url;

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

/**
* @var string|array
*/
protected $_params;

/**
* @var object Response
*/
protected $_reponse;

/**
* Constructor
*
* @param string $url
* @param string $method
* @param array $params
*/
public function __construct($url, $method, $params = array()) {

$this->_url = $url;

// Set the method
$this->_method = $method;

// Set the params
$this->_params = $params;
}

/**
* Determine the Request method
*
* @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;
}
}

/**
* Add authorization header
*
* @param string $type
* @param string $token
*/
public function setAuthorizationHeader($type, $token) {

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

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

/**
* Add body to request
*/
private function addBody() {

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

if(is_array($this->_params)) {
// JSON Encode the array
$this->_params = json_encode($this->_params);
}

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

// Add a content-length header
$this->_headers[] = 'Content-length: ' . strlen($this->_params);
}
}

/**
* Add a query string to the request
*/
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) {
// Pattern match params against the url
foreach($this->_params as $param => $value) {
$this->_url = preg_replace('/{' . $param . '}/', $value, $this->_url);
}
}
}
}

/**
* Send the request
*/
public function send() {

// Initialise cUrl request
$this->_request = curl_init();

// Return the response as a string
curl_setopt($this->_request, CURLOPT_RETURNTRANSFER, 1);

// Add a query string
$this->addQueryString();

// Set the URL
curl_setopt($this->_request, CURLOPT_URL, $this->_url);

// Set request method
$this->setMethod();

// Add a body
$this->addBody();

if(empty($this->_headers) == false) {
// Set the headers
curl_setopt($this->_request, CURLOPT_HTTPHEADER, $this->_headers);
}

// Disable SSL checks
curl_setopt($this->_request, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->_request, CURLOPT_SSL_VERIFYHOST, false);

// Send the request and store the body
$this->_response = new Response(curl_exec($this->_request));

// Set the status code
$this->_response->setStatusCode(curl_getinfo($this->_request, CURLINFO_HTTP_CODE));

// Close the connection
curl_close($this->_request);
}

/**
* Get the response
*
* @return object
*/
public function getResponse() {

return $this->_response;
}
}

class Response {

/**
* @var array
*/
protected $_reason_phrases = array(
//Informational 1xx
100 => "Continue",
101 => "Switching Protocols",

// Successful 2xx
200 => "OK",
201 => "Created",
202 => "Accepted",
203 => "Non-Authoritative Information",
204 => "No Content",
205 => "Reset Content",
206 => "Partial Content",

// Redirection 3xx
300 => "Multiple Choices",
301 => "Moved Permanently",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
305 => "Use Proxy",
306 => "(Unused)",
307 => "Temporary Redirect",

// Client Error 4xx
400 => "Bad Request",
401 => "Unauthorized",
402 => "Payment Required",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
406 => "Not Acceptable",
407 => "Proxy Authentication Required",
408 => "Request Timeout",
409 => "Conflict",
410 => "Gone",
411 => "Length Required",
412 => "Precondition Failed",
413 => "Request Entity Too Large",
414 => "Request-URI Too Long",
415 => "Unsupported Media Type",
416 => "Requested Range Not Satisfiable",
417 => "Expectation Failed",

// Server Error 5xx
500 => "Internal Server Error",
501 => "Not Implemented",
502 => "Bad Gateway",
503 => "Service Unavailable",
504 => "Gateway Timeout",
505 => "HTTP Version Not Supported"
);

/**
* @var integer
*/
protected $_status_code;

/**
* @var string
*/
protected $_body;

/**
* Constructor
*
* @param string $body
*/
public function __construct($body) {

$this->_body = $body;
}

/**
* Constructor
*
* @param string $status_code
*/
public function setStatusCode($status_code) {

$this->_status_code = $status_code;
}

/**
* Get status code
*
* @return integer
*/
public function getStatusCode() {

return $this->_status_code;
}

/**
* Get body
*
* @return string
*/
public function getBody() {

return $this->_body;
}

/**
* Get body JSON Decoded
*
* @return object|null
*/
public function getBodyDecoded() {

return json_decode($this->_body);
}

/**
* Get reason phrase
*
* @return string|boolean
*/
public function getReasonPhrase() {

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

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

return false;
}
}
}

Anmeldung

Es gibt zwei Möglichkeiten, den Weg login anzufordern:

  • mit Benutzernamen und Passwort
  • mit Api-Token (Zugriffstoken)

Beispiel einer Anmeldung mit den Parametern Benutzername und Passwort.


<?php

// Include Request and Response classes

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

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

// Create a new Request object
$request = new Request($url, 'POST', $params);

// Send the request
$request->send();

// Get the Response object
$response = $request->getResponse();

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

// Retrieve the session token details
$token = $response->getBodyDecoded();

print_r($token);
}
else {

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

Beispiel für die Anmeldung mit API-Token (Zugangs-Token)


<?php

// Include Request and Response classes

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

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

// Create a new Request object
$request = new Request($url, 'POST', $params);

// Send the request
$request->send();

// Get the Response object
$response = $request->getResponse();

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

// Retrieve the session token details
$token = $response->getBodyDecoded();

print_r($token);
}
else {

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

Authentifizierung

Bei jeder Anforderung von benutzerbezogenen Inhalten muss ein Authorization-Header gesetzt werden, dessen Wert den Token-Typ und das Sitzungs-Token enthält, die aus der API-Anmeldeanforderung stammen.

Eine gültige /login-Anfrage an die API gibt die folgende json-Nutzlast zurück.


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

Das Session-Token sollte in allen nachfolgenden benutzerbezogenen Inhaltsanforderungen an die API enthalten sein.

Der Typ ist dem Token voranzustellen, getrennt durch ein einzelnes Leerzeichen.


Bearer 4e63518d383d8fcaefb516fe708b893727463031

Die expires_in ist die Zeit in Sekunden, für die das Token gültig sein wird. Wenn diese Zeit abläuft, muss ein neues Token über die /login-Anfrage erlangt werden.

Beispiel für das Abrufen und Festlegen eines Autorisierungs-Headers mit Benutzername und Passwort


<?php

// Include Request and Response classes

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

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

// Create a new Request object
$request = new Request($url, 'POST', $params);

// Send the request
$request->send();

// Get the Response object
$response = $request->getResponse();

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

// Retrieve the session token details
$token = $response->getBodyDecoded();

// Get Campaigns
$url = 'https://api.example.com/v2/campaigns';

// Create a new Request object
$request = new Request($url, 'GET');

// Set the Authorization Header
$request->setAuthorizationHeader($token->type, $token->token);

// Send the request
$request->send();

// Get the Response object
$response = $request->getResponse();

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

// Retrieve the campaigns
$campaigns = $response->getBodyDecoded();

foreach($campaigns->result as $campaign) {
// Display the campaign names
echo $campaign->name . PHP_EOL;
}
}
else {
// Campaigns request error
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
}
else {
// Invalid Login
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
?>

Beispiel für das Abrufen und Festlegen des Autorisierungs-Headers mit API-Token


<?php

// Include Request and Response classes

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

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

...

?>

Sammlungen

Es folgt ein Beispiel für eine Anfrage zum Abrufen der Sammlung Browsers.


<?php

// Include Request and Response classes

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

// Create a new Request object
$request = new Request($url, 'GET');

// Set the Authorization Header retrieved from earlier Login request
$request->setAuthorizationHeader($token->type, $token->token);

// Send the request
$request->send();

// Get the Response object
$response = $request->getResponse();

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

$browsers = $response->getBodyDecoded();

foreach($browsers as $browser) {

echo $browser->id . ': ' . $browser->name . PHP_EOL;
}
}
else {
// Collection not found
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
?>

Statistik

Es folgt ein Beispiel für eine Anfrage eines Inserenten an statistics/a/date.

Falls der Wert additional_group_by definiert ist, wird die Anfrage nach dem Hauptroutenfeld und dem/den zusätzlichen Feld/ern gruppiert.

Beispiel für Statistiken pro Datum, gefiltert nach der Kampagnen-ID 1234.


<?php

// Include Request and Response classes

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

// Specify the campaign id
$params = array(
'campaignid' => 1234
);

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

// Set the Authorization Header, retrieved from earlier Login request
$request->setAuthorizationHeader($token->type, $token->token);

// Send the request
$request->send();

// Get the response object
$response = $request->getResponse();

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

$statistics = $response->getBodyDecoded();

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

echo $statistic->ddate . ': ' . $statistic->value . PHP_EOL;
}
}
else {
// Campaign statistics not found
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
?>

Beispiel einer Statistik pro Datum mit zusätzlicher Gruppierung nach Kampagnen.


<?php

// Include Request and Response classes

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

// Specify the campaign id
$params = array(
'additional_group_by' => 'campaign'
);

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

// Set the Authorization Header, retrieved from earlier Login request
$request->setAuthorizationHeader($token->type, $token->token);

// Send the request
$request->send();

// Get the response object
$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 {
// Campaign statistics not found
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
?>

beitrag /statistik/a/global


Get global advertiser statistics

Beispiel 1 der Gesamtstatistik

Beispiel für eine globale Statistikabfrage.

Only the group_by parameter is mandatory. The default values for the other parameters can be found Here.

Bitte beachten Sie, dass die globalen Statistikrouten (statistics/a/global, statistics/p/global) ein anderes Parameterformat haben.


<?php

// Include Request and Response classes

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

// Specify the group_by
$params = [
"group_by" => ["date"]
];

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

// Set the Authorization Header, retrieved from earlier Login request
$request->setAuthorizationHeader($token->type, $token->token);

// Send the request
$request->send();

// Get the response object
$response = $request->getResponse();

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

$statistics = $response->getBodyDecoded();

foreach($statistics->result as $statistic) {
echo 'Date: ' . $statistic->group_by->date->date . ' - Impressions: ' . $statistic->impressions .' - Cost: ' . $statistic->cost . PHP_EOL;
}
}
else {
// Campaign statistics not found
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
?>

Beispiel 2 der Gesamtstatistik

Abrufen von Statistiken pro Datum einschließlich Gesamtsummen.


<?php

// Include Request and Response classes

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

// Specify the campaign id
$params = [
"filter" => [
"date_from" => "2019-01-10",
"date_to" => "2019-01-31",
],
"totals" => 1,
"group_by" => ["date"]
];

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

// Set the Authorization Header, retrieved from earlier Login request
$request->setAuthorizationHeader($token->type, $token->token);

// Send the request
$request->send();

// Get the response object
$response = $request->getResponse();

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

$statistics = $response->getBodyDecoded();

foreach($statistics->result as $statistic) {
echo 'Date: ' . $statistic->group_by->date->date . ' - Impressions: ' . $statistic->impressions .' - Cost: ' . $statistic->cost . PHP_EOL;
}

echo 'Total cost:' . $statistics->result_total->cost . PHP_EOL;
}
else {
// Campaign statistics not found
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
?>

Beispiel 3 der Gesamtstatistik

Erhalten Sie Statistiken pro Kampagne und Land, gefiltert nach einem bestimmten Datum und geordnet nach Impressionen.


<?php

// Include Request and Response classes

$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);

// Set the Authorization Header, retrieved from earlier Login request
$request->setAuthorizationHeader($token->type, $token->token);

// Send the request
$request->send();

// Get the response object
$response = $request->getResponse();

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

$statistics = $response->getBodyDecoded();

foreach($statistics->result as $statistic) {
echo 'Country: ' . $statistic->group_by->country_iso->country_iso . ' - Campaign ID: ' . $statistic->group_by->campaign_id->id .' - Cost: ' . $statistic->cost . PHP_EOL;
}
}
else {
// Campaign statistics not found
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
?>

Beispiel 4 der Gesamtstatistik

Holen Sie sich Verlagsstatistiken pro Zone und Land, gefiltert nach bestimmten Betriebssystemen.


<?php

// Include Request and Response classes

$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);

// Set the Authorization Header, retrieved from earlier Login request
$request->setAuthorizationHeader($token->type, $token->token);

// Send the request
$request->send();

// Get the response object
$response = $request->getResponse();

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

$statistics = $response->getBodyDecoded();

foreach($statistics->result as $statistic) {
echo ' Zone ID:' . $statistic->group_by->zone_id->id . ' - Country: ' . $statistic->group_by->country_iso->country_iso .' - Revenue: ' . $statistic->revenue . PHP_EOL;
}
}
else {
// Campaign statistics not found
echo $response->getStatusCode() . PHP_EOL;
echo $response->getReasonPhrase() . PHP_EOL;
echo $response->getBody();
}
?>