Add a read-only Google AdSense analytics module for admins.

Connect AdSense over OAuth, sync entities and daily reports locally, and show placement performance in the admin panel without calling the Management API from public pages.
This commit is contained in:
2026-09-20 14:49:48 +02:00
parent 04a60a981e
commit ce0f278bac
30 changed files with 5098 additions and 12 deletions
@@ -0,0 +1,288 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense;
use App\Models\AdsenseConnection;
use App\Models\AdsenseDailyStat;
use App\Models\AdsenseEntity;
use App\Models\Country;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
final class AdsenseAnalyticsQueryService
{
/**
* @return array{from: Carbon, to: Carbon, previous_from: Carbon, previous_to: Carbon, period: string}
*/
public function resolveRange(?string $period, ?string $from, ?string $to): array
{
$period = $period ?: '30d';
$today = now()->startOfDay();
[$start, $end] = match ($period) {
'today' => [$today->copy(), $today->copy()],
'yesterday' => [$today->copy()->subDay(), $today->copy()->subDay()],
'7d' => [$today->copy()->subDays(6), $today->copy()],
'custom' => [
Carbon::parse($from ?: $today->copy()->subDays(29)->toDateString())->startOfDay(),
Carbon::parse($to ?: $today->toDateString())->startOfDay(),
],
default => [$today->copy()->subDays(29), $today->copy()],
};
if ($end->lt($start)) {
[$start, $end] = [$end, $start];
}
$days = $start->diffInDays($end) + 1;
$previousEnd = $start->copy()->subDay();
$previousStart = $previousEnd->copy()->subDays($days - 1);
return [
'from' => $start,
'to' => $end,
'previous_from' => $previousStart,
'previous_to' => $previousEnd,
'period' => $period === 'custom' ? 'custom' : (in_array($period, ['today', 'yesterday', '7d', '30d'], true) ? $period : '30d'),
];
}
/**
* @return array<string, mixed>
*/
public function dashboard(AdsenseConnection $connection, Carbon $from, Carbon $to, Carbon $previousFrom, Carbon $previousTo): array
{
$account = (string) $connection->account_resource_name;
$current = $this->totals($account, $from, $to);
$previous = $this->totals($account, $previousFrom, $previousTo);
$currency = $current['currency_code'] ?? $previous['currency_code'] ?? 'USD';
return [
'kpis' => [
$this->kpi('estimated_earnings', 'Estimated Earnings', $current['estimated_earnings'], $previous['estimated_earnings'], 'money', $currency),
$this->kpi('page_views', 'Page Views', $current['page_views'], $previous['page_views'], 'integer'),
$this->kpi('impressions', 'Ad Impressions', $current['impressions'], $previous['impressions'], 'integer'),
$this->kpi('clicks', 'Clicks', $current['clicks'], $previous['clicks'], 'integer'),
$this->kpi('page_views_ctr', 'Page CTR', $this->ratio($current['clicks'], $current['page_views']), $this->ratio($previous['clicks'], $previous['page_views']), 'percent'),
$this->kpi('page_views_rpm', 'Page RPM', $this->rpm($current['estimated_earnings'], $current['page_views']), $this->rpm($previous['estimated_earnings'], $previous['page_views']), 'money', $currency),
$this->kpi('ad_requests_coverage', 'Ad Request Coverage', $this->ratio($current['matched_ad_requests'], $current['ad_requests']), $this->ratio($previous['matched_ad_requests'], $previous['ad_requests']), 'percent'),
$this->kpi('cost_per_click', 'CPC', $this->cpc($current['estimated_earnings'], $current['clicks']), $this->cpc($previous['estimated_earnings'], $previous['clicks']), 'money', $currency),
],
'chart' => $this->chart($account, $from, $to),
'placements' => $this->dimensionTable($account, AdsenseDailyStat::DIMENSION_AD_UNIT, $from, $to, $currency),
'platforms' => $this->dimensionTable($account, AdsenseDailyStat::DIMENSION_PLATFORM, $from, $to, $currency),
'countries' => array_slice($this->dimensionTable($account, AdsenseDailyStat::DIMENSION_COUNTRY, $from, $to, $currency), 0, 20),
'currency_code' => $currency,
];
}
/**
* @return array<string, mixed>
*/
private function totals(string $account, Carbon $from, Carbon $to): array
{
$row = AdsenseDailyStat::query()
->where('account_resource_name', $account)
->where('dimension_type', AdsenseDailyStat::DIMENSION_TOTAL)
->whereDate('date', '>=', $from->toDateString())
->whereDate('date', '<=', $to->toDateString())
->selectRaw('
SUM(page_views) as page_views,
SUM(ad_requests) as ad_requests,
SUM(matched_ad_requests) as matched_ad_requests,
SUM(impressions) as impressions,
SUM(clicks) as clicks,
SUM(estimated_earnings) as estimated_earnings,
MAX(currency_code) as currency_code
')
->first();
return [
'page_views' => (int) ($row?->page_views ?? 0),
'ad_requests' => (int) ($row?->ad_requests ?? 0),
'matched_ad_requests' => (int) ($row?->matched_ad_requests ?? 0),
'impressions' => (int) ($row?->impressions ?? 0),
'clicks' => (int) ($row?->clicks ?? 0),
'estimated_earnings' => (string) ($row?->estimated_earnings ?? '0'),
'currency_code' => $row?->currency_code,
];
}
/**
* @return list<array<string, mixed>>
*/
private function chart(string $account, Carbon $from, Carbon $to): array
{
$rows = AdsenseDailyStat::query()
->where('account_resource_name', $account)
->where('dimension_type', AdsenseDailyStat::DIMENSION_TOTAL)
->whereDate('date', '>=', $from->toDateString())
->whereDate('date', '<=', $to->toDateString())
->orderBy('date')
->get();
return $rows->map(function (AdsenseDailyStat $row): array {
return [
'date' => optional($row->date)?->toDateString(),
'estimated_earnings' => (float) $row->estimated_earnings,
'page_views' => (int) $row->page_views,
'page_views_rpm' => (float) $row->page_views_rpm,
'clicks' => (int) $row->clicks,
];
})->values()->all();
}
/**
* @return list<array<string, mixed>>
*/
private function dimensionTable(string $account, string $dimensionType, Carbon $from, Carbon $to, ?string $currency): array
{
$rows = AdsenseDailyStat::query()
->where('account_resource_name', $account)
->where('dimension_type', $dimensionType)
->whereDate('date', '>=', $from->toDateString())
->whereDate('date', '<=', $to->toDateString())
->selectRaw('
dimension_key,
MAX(dimension_label) as dimension_label,
SUM(page_views) as page_views,
SUM(impressions) as impressions,
SUM(clicks) as clicks,
SUM(estimated_earnings) as estimated_earnings
')
->groupBy('dimension_key')
->orderByDesc('estimated_earnings')
->get();
$labels = $this->entityLabels($account, $dimensionType);
$countryNames = $dimensionType === AdsenseDailyStat::DIMENSION_COUNTRY ? $this->countryNames() : collect();
return $rows->map(function ($row) use ($labels, $countryNames, $currency, $dimensionType): array {
$key = (string) $row->dimension_key;
$label = (string) ($labels[$key] ?? $countryNames[$key] ?? $row->dimension_label ?? $key);
if ($dimensionType === AdsenseDailyStat::DIMENSION_PLATFORM) {
$label = $this->platformLabel($key, $label);
}
$pageViews = (int) $row->page_views;
$impressions = (int) $row->impressions;
$clicks = (int) $row->clicks;
$earnings = (string) ($row->estimated_earnings ?? '0');
return [
'key' => $key,
'label' => $label,
'page_views' => $pageViews,
'impressions' => $impressions,
'clicks' => $clicks,
'ctr' => $this->ratio($clicks, $pageViews),
'rpm' => $this->rpm($earnings, $pageViews),
'revenue' => $earnings,
'currency_code' => $currency,
];
})->values()->all();
}
/**
* @return array<string, string>
*/
private function entityLabels(string $account, string $dimensionType): array
{
if (! in_array($dimensionType, [AdsenseDailyStat::DIMENSION_AD_UNIT, AdsenseDailyStat::DIMENSION_CUSTOM_CHANNEL], true)) {
return [];
}
return AdsenseEntity::query()
->where('account_resource_name', $account)
->where('type', $dimensionType)
->pluck('display_name', 'reporting_dimension_id')
->all();
}
/**
* @return Collection<string, string>
*/
private function countryNames(): Collection
{
if (! Schema::hasTable('countries')) {
return collect();
}
return Country::query()
->get(['iso2', 'name', 'name_common'])
->mapWithKeys(function (Country $country): array {
$code = strtoupper((string) $country->iso2);
$name = (string) ($country->name_common ?: $country->name ?: $code);
return $code !== '' ? [$code => $name] : [];
});
}
private function platformLabel(string $key, string $fallback): string
{
return match (strtoupper($key)) {
'DESKTOP' => 'Desktop',
'HIGH_END_MOBILE', 'MOBILE' => 'Mobile',
'TABLET' => 'Tablet',
default => $fallback !== '' ? $fallback : $key,
};
}
/**
* @return array<string, mixed>
*/
private function kpi(string $key, string $label, mixed $current, mixed $previous, string $format, ?string $currency = null): array
{
return [
'key' => $key,
'label' => $label,
'value' => $current,
'previous' => $previous,
'change_percent' => $this->changePercent($current, $previous),
'format' => $format,
'currency_code' => $currency,
];
}
private function changePercent(mixed $current, mixed $previous): ?float
{
$current = (float) $current;
$previous = (float) $previous;
if ($previous == 0.0) {
return null;
}
return (($current - $previous) / $previous) * 100;
}
private function ratio(int $numerator, int $denominator): ?float
{
if ($denominator === 0) {
return null;
}
return $numerator / $denominator;
}
private function rpm(string|float|int|null $earnings, int $pageViews): ?float
{
if ($pageViews === 0) {
return null;
}
return ((float) $earnings / $pageViews) * 1000;
}
private function cpc(string|float|int|null $earnings, int $clicks): ?float
{
if ($clicks === 0) {
return null;
}
return (float) $earnings / $clicks;
}
}
+350
View File
@@ -0,0 +1,350 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense;
use App\Models\AdsenseConnection;
use App\Services\Adsense\Exceptions\AdsenseApiException;
use App\Services\Adsense\Exceptions\AdsenseAuthorizationException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
final class AdsenseApiClient
{
public function __construct(private readonly AdsenseOAuthService $oauth) {}
/**
* @return list<array<string, mixed>>
*/
public function listAccounts(AdsenseConnection $connection): array
{
return $this->paginate($connection, '/accounts', 'accounts');
}
/**
* @return list<array<string, mixed>>
*/
public function listAdClients(AdsenseConnection $connection, string $accountResourceName): array
{
return $this->paginate($connection, '/'.$this->trimPath($accountResourceName).'/adclients', 'adClients');
}
/**
* @return list<array<string, mixed>>
*/
public function listAdUnits(AdsenseConnection $connection, string $adClientResourceName): array
{
return $this->paginate($connection, '/'.$this->trimPath($adClientResourceName).'/adunits', 'adUnits');
}
/**
* @return list<array<string, mixed>>
*/
public function listCustomChannels(AdsenseConnection $connection, string $adClientResourceName): array
{
return $this->paginate($connection, '/'.$this->trimPath($adClientResourceName).'/customchannels', 'customChannels');
}
/**
* @param list<string> $dimensions
* @param list<string> $metrics
* @return array<string, mixed>
*/
public function generateReport(
AdsenseConnection $connection,
string $accountResourceName,
array $dimensions,
array $metrics,
Carbon $from,
Carbon $to,
string $report = '',
): array {
$path = '/'.$this->trimPath($accountResourceName).'/reports:generate';
$merged = [
'headers' => [],
'rows' => [],
];
$pageToken = null;
do {
$query = $this->reportQuery($dimensions, $metrics, $from, $to, $pageToken);
$json = $this->getJson($connection, $path, $query, $report);
if ($merged['headers'] === [] && isset($json['headers']) && is_array($json['headers'])) {
$merged['headers'] = $json['headers'];
}
$rows = $json['rows'] ?? [];
if (is_array($rows) && $rows !== []) {
$merged['rows'] = array_merge($merged['rows'], $rows);
}
foreach (['totals', 'averages', 'startDate', 'endDate', 'warnings'] as $metaKey) {
if (! isset($merged[$metaKey]) && isset($json[$metaKey])) {
$merged[$metaKey] = $json[$metaKey];
}
}
$pageToken = isset($json['nextPageToken']) && is_string($json['nextPageToken']) && $json['nextPageToken'] !== ''
? $json['nextPageToken']
: null;
} while ($pageToken !== null);
return $merged;
}
/**
* @param array<string, scalar|null> $query
* @return list<array<string, mixed>>
*/
private function paginate(AdsenseConnection $connection, string $path, string $itemsKey): array
{
$items = [];
$pageToken = null;
do {
$query = [];
if ($pageToken !== null) {
$query['pageToken'] = $pageToken;
}
$json = $this->getJson($connection, $path, $query);
$pageItems = $json[$itemsKey] ?? [];
if (is_array($pageItems)) {
foreach ($pageItems as $item) {
if (is_array($item)) {
$items[] = $item;
}
}
}
$pageToken = isset($json['nextPageToken']) && is_string($json['nextPageToken']) && $json['nextPageToken'] !== ''
? $json['nextPageToken']
: null;
} while ($pageToken !== null);
return $items;
}
/**
* @param list<string> $dimensions
* @param list<string> $metrics
* @return array<string, scalar>
*/
private function reportQuery(array $dimensions, array $metrics, Carbon $from, Carbon $to, ?string $pageToken): array
{
$query = [
'startDate.year' => $from->year,
'startDate.month' => $from->month,
'startDate.day' => $from->day,
'endDate.year' => $to->year,
'endDate.month' => $to->month,
'endDate.day' => $to->day,
];
foreach ($dimensions as $index => $dimension) {
$query['dimensions'.$index] = $dimension;
}
foreach ($metrics as $index => $metric) {
$query['metrics'.$index] = $metric;
}
if ($pageToken !== null) {
$query['pageToken'] = $pageToken;
}
return $query;
}
/**
* @param array<string, scalar|null> $query
* @return array<string, mixed>
*/
private function getJson(AdsenseConnection $connection, string $path, array $query = [], string $report = ''): array
{
$url = $this->url($path, $query);
$response = $this->send($connection, $url, $report);
$json = $response->json();
if (! is_array($json)) {
throw new AdsenseApiException('Malformed AdSense API response.', $response->status(), $report);
}
return $json;
}
private function send(AdsenseConnection $connection, string $url, string $report = ''): Response
{
$maxAttempts = max(1, (int) config('adsense.retry_times', 3));
$sleepMs = max(0, (int) config('adsense.retry_sleep_ms', 400));
$refreshed = false;
$attempt = 0;
while (true) {
$attempt++;
try {
$response = Http::acceptJson()
->withToken($this->oauth->accessToken($connection))
->timeout((int) config('adsense.timeout', 20))
->connectTimeout((int) config('adsense.connect_timeout', 5))
->get($url);
} catch (AdsenseAuthorizationException $exception) {
throw $exception;
} catch (ConnectionException $exception) {
if ($attempt < $maxAttempts) {
$this->backoff($sleepMs, $attempt);
continue;
}
Log::warning('AdSense API connection failed.', AdsenseLogSanitizer::context([
'message' => $exception->getMessage(),
'report' => $report,
]));
throw new AdsenseApiException('AdSense API connection failed.', 0, $report, $exception);
}
$status = $response->status();
if ($status === 401 && ! $refreshed) {
$this->oauth->forgetAccessToken((int) $connection->id);
try {
$this->oauth->accessToken($connection, true);
} catch (AdsenseAuthorizationException $exception) {
throw $exception;
}
$refreshed = true;
$attempt--;
continue;
}
if (in_array($status, [429, 500, 502, 503, 504], true) && $attempt < $maxAttempts) {
$this->backoff($sleepMs, $attempt);
continue;
}
if ($status === 401 || $status === 403) {
$message = $this->errorMessage($response, 'AdSense API authorization failed.');
Log::warning('AdSense API authorization failed.', AdsenseLogSanitizer::context([
'status' => $status,
'report' => $report,
]));
if ($this->isRevoked($response, $message)) {
$this->oauth->markReconnectRequired($connection, 'AdSense authorization expired or was revoked.');
throw new AdsenseAuthorizationException('AdSense authorization expired or was revoked.');
}
throw new AdsenseApiException($message, $status, $report);
}
if ($response->failed()) {
$message = $this->errorMessage($response, 'AdSense API request failed.');
Log::warning('AdSense API request failed.', AdsenseLogSanitizer::context([
'status' => $status,
'report' => $report,
]));
throw new AdsenseApiException($message, $status, $report);
}
return $response;
}
}
/**
* @param array<string, scalar|null> $query
*/
private function url(string $path, array $query): string
{
$base = rtrim((string) config('adsense.api_base'), '/');
$url = $base.'/'.$this->trimPath($path);
$parts = [];
foreach ($query as $key => $value) {
if ($value === null || $value === '') {
continue;
}
if (str_starts_with((string) $key, 'dimensions')) {
$parts[] = 'dimensions='.rawurlencode((string) $value);
continue;
}
if (str_starts_with((string) $key, 'metrics')) {
$parts[] = 'metrics='.rawurlencode((string) $value);
continue;
}
$parts[] = rawurlencode((string) $key).'='.rawurlencode((string) $value);
}
if ($parts === []) {
return $url;
}
return $url.'?'.implode('&', $parts);
}
private function trimPath(string $path): string
{
return ltrim($path, '/');
}
private function backoff(int $sleepMs, int $attempt): void
{
if ($sleepMs <= 0) {
return;
}
usleep($sleepMs * 1000 * $attempt);
}
private function errorMessage(Response $response, string $fallback): string
{
$json = $response->json();
if (! is_array($json)) {
return $fallback;
}
$error = $json['error'] ?? null;
if (is_string($error) && $error !== '') {
return $error;
}
if (is_array($error)) {
$status = (string) ($error['status'] ?? '');
$message = (string) ($error['message'] ?? '');
$combined = trim($status.' '.$message);
return $combined !== '' ? $combined : $fallback;
}
return $fallback;
}
private function isRevoked(Response $response, string $message): bool
{
$haystack = Str::lower($message.' '.$response->body());
return str_contains($haystack, 'invalid_grant')
|| str_contains($haystack, 'invalid credentials')
|| str_contains($haystack, 'revoked');
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense;
final class AdsenseLogSanitizer
{
/**
* @var list<string>
*/
private const SENSITIVE_KEYS = [
'access_token',
'refresh_token',
'id_token',
'token',
'code',
'client_secret',
'authorization',
'encrypted_refresh_token',
];
/**
* @param array<string, mixed> $context
* @return array<string, mixed>
*/
public static function context(array $context): array
{
$clean = [];
foreach ($context as $key => $value) {
$normalized = strtolower((string) $key);
if (in_array($normalized, self::SENSITIVE_KEYS, true) || str_contains($normalized, 'token') || str_contains($normalized, 'secret')) {
continue;
}
if (is_array($value)) {
$clean[$key] = self::context($value);
continue;
}
if (is_string($value) && self::looksLikeSecret($value)) {
continue;
}
$clean[$key] = $value;
}
return $clean;
}
public static function looksLikeSecret(string $value): bool
{
if ($value === '') {
return false;
}
foreach (['refresh-secret', 'access-secret', 'ya29.', '1//'] as $marker) {
if (str_contains($value, $marker)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,327 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense;
use App\Models\AdsenseConnection;
use App\Services\Adsense\Exceptions\AdsenseAuthorizationException;
use App\Services\Adsense\Exceptions\AdsenseOAuthException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
final class AdsenseOAuthService
{
public const SESSION_STATE_KEY = 'adsense.oauth_state';
public const SESSION_PENDING_ACCOUNTS_KEY = 'adsense.pending_accounts';
public function isConfigured(): bool
{
return $this->clientId() !== '' && $this->clientSecret() !== '' && $this->redirectUri() !== '';
}
public function authorizationUrl(Request $request, bool $promptConsent = true): string
{
if (! $this->isConfigured()) {
throw new AdsenseOAuthException('Google AdSense OAuth is not configured.');
}
$state = bin2hex(random_bytes(32));
$request->session()->put(self::SESSION_STATE_KEY, $state);
$query = [
'client_id' => $this->clientId(),
'redirect_uri' => $this->redirectUri(),
'response_type' => 'code',
'scope' => (string) config('adsense.scope'),
'access_type' => 'offline',
'include_granted_scopes' => 'true',
'state' => $state,
];
if ($promptConsent) {
$query['prompt'] = 'consent';
}
return (string) config('adsense.oauth_authorize_url').'?'.http_build_query($query);
}
/**
* @return array{access_token: string, refresh_token: ?string, expires_in: int}
*/
public function exchangeAuthorizationCode(string $code): array
{
return $this->requestToken([
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => $this->redirectUri(),
'client_id' => $this->clientId(),
'client_secret' => $this->clientSecret(),
]);
}
/**
* @return array{access_token: string, refresh_token: ?string, expires_in: int}
*/
public function refreshAccessToken(string $refreshToken): array
{
try {
return $this->requestToken([
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken,
'client_id' => $this->clientId(),
'client_secret' => $this->clientSecret(),
]);
} catch (AdsenseOAuthException $exception) {
if ($this->isInvalidGrant($exception)) {
throw new AdsenseAuthorizationException(
'AdSense authorization expired or was revoked.',
0,
$exception,
);
}
throw $exception;
}
}
public function persistTokens(AdsenseConnection $connection, array $tokens, ?int $userId = null): void
{
$refreshToken = $tokens['refresh_token'] ?? null;
if (is_string($refreshToken) && $refreshToken !== '') {
$connection->encrypted_refresh_token = $refreshToken;
}
if (! $connection->hasRefreshToken()) {
throw new AdsenseOAuthException('Google did not return a refresh token. Reconnect with consent.');
}
if ($userId !== null) {
$connection->connected_by_user_id = $userId;
}
if ($connection->connected_at === null) {
$connection->connected_at = now();
}
if ($connection->status === AdsenseConnection::STATUS_DISCONNECTED) {
$connection->status = AdsenseConnection::STATUS_PENDING;
}
$connection->last_error = null;
$connection->save();
if (isset($tokens['access_token']) && is_string($tokens['access_token']) && $tokens['access_token'] !== '') {
$this->cacheAccessToken(
(int) $connection->id,
$tokens['access_token'],
(int) ($tokens['expires_in'] ?? 3600),
);
}
}
public function accessToken(AdsenseConnection $connection, bool $forceRefresh = false): string
{
if (! $connection->hasRefreshToken()) {
$this->markReconnectRequired($connection, 'AdSense authorization expired or was revoked.');
throw new AdsenseAuthorizationException('AdSense authorization expired or was revoked.');
}
$cacheKey = $this->cacheKey((int) $connection->id);
if (! $forceRefresh) {
$cached = Cache::get($cacheKey);
if (is_string($cached) && $cached !== '') {
return $cached;
}
}
try {
$tokens = $this->refreshAccessToken((string) $connection->encrypted_refresh_token);
} catch (AdsenseAuthorizationException $exception) {
$this->forgetAccessToken((int) $connection->id);
$this->markReconnectRequired($connection, $exception->getMessage());
throw $exception;
}
$accessToken = (string) ($tokens['access_token'] ?? '');
if ($accessToken === '') {
throw new AdsenseOAuthException('Google did not return an access token.');
}
if (isset($tokens['refresh_token']) && is_string($tokens['refresh_token']) && $tokens['refresh_token'] !== '') {
$connection->encrypted_refresh_token = $tokens['refresh_token'];
$connection->save();
}
$this->cacheAccessToken((int) $connection->id, $accessToken, (int) ($tokens['expires_in'] ?? 3600));
return $accessToken;
}
public function cacheAccessToken(int $connectionId, string $accessToken, int $expiresIn): void
{
$ttl = max(30, $expiresIn - (int) config('adsense.access_token_skew_seconds', 60));
Cache::put($this->cacheKey($connectionId), $accessToken, $ttl);
}
public function forgetAccessToken(int $connectionId): void
{
Cache::forget($this->cacheKey($connectionId));
}
public function markReconnectRequired(AdsenseConnection $connection, string $message): void
{
$connection->status = AdsenseConnection::STATUS_RECONNECT_REQUIRED;
$connection->last_error = $message;
$connection->save();
}
public function disconnect(AdsenseConnection $connection): void
{
$refreshToken = $connection->encrypted_refresh_token;
$this->forgetAccessToken((int) $connection->id);
if (is_string($refreshToken) && $refreshToken !== '') {
$this->revokeToken($refreshToken);
}
$connection->encrypted_refresh_token = null;
$connection->status = AdsenseConnection::STATUS_DISCONNECTED;
$connection->last_error = null;
$connection->save();
}
public function revokeToken(string $token): void
{
try {
Http::asForm()
->timeout((int) config('adsense.timeout', 20))
->connectTimeout((int) config('adsense.connect_timeout', 5))
->post((string) config('adsense.oauth_revoke_url'), [
'token' => $token,
]);
} catch (\Throwable $exception) {
Log::warning('AdSense token revocation failed.', AdsenseLogSanitizer::context([
'message' => $exception->getMessage(),
]));
}
}
public function assertValidCallback(Request $request): string
{
$error = trim((string) $request->query('error', ''));
if ($error !== '') {
$description = trim((string) $request->query('error_description', ''));
$request->session()->forget(self::SESSION_STATE_KEY);
throw new AdsenseOAuthException(
$description !== ''
? 'Google AdSense authorization was denied: '.$description
: 'Google AdSense authorization was denied.'
);
}
$expected = (string) $request->session()->pull(self::SESSION_STATE_KEY, '');
$provided = (string) $request->query('state', '');
if ($expected === '' || $provided === '' || ! hash_equals($expected, $provided)) {
throw new AdsenseOAuthException('Invalid OAuth state.');
}
$code = trim((string) $request->query('code', ''));
if ($code === '') {
throw new AdsenseOAuthException('Missing authorization code.');
}
return $code;
}
/**
* @param array<string, string> $payload
* @return array{access_token: string, refresh_token: ?string, expires_in: int}
*/
private function requestToken(array $payload): array
{
try {
$response = Http::asForm()
->acceptJson()
->timeout((int) config('adsense.timeout', 20))
->connectTimeout((int) config('adsense.connect_timeout', 5))
->post((string) config('adsense.oauth_token_url'), $payload);
} catch (ConnectionException $exception) {
Log::warning('AdSense OAuth token request failed.', AdsenseLogSanitizer::context([
'message' => $exception->getMessage(),
]));
throw new AdsenseOAuthException('Unable to contact Google OAuth.', 0, $exception);
}
$json = $response->json();
$json = is_array($json) ? $json : [];
if ($response->failed()) {
$error = $json['error'] ?? 'oauth_error';
if (is_array($error)) {
$error = (string) ($error['message'] ?? $error['status'] ?? 'oauth_error');
} else {
$error = (string) $error;
}
Log::warning('AdSense OAuth token request rejected.', AdsenseLogSanitizer::context([
'status' => $response->status(),
'error' => $error,
]));
throw new AdsenseOAuthException($error, $response->status());
}
$accessToken = (string) ($json['access_token'] ?? '');
if ($accessToken === '') {
throw new AdsenseOAuthException('Google did not return an access token.');
}
$refreshToken = $json['refresh_token'] ?? null;
return [
'access_token' => $accessToken,
'refresh_token' => is_string($refreshToken) && $refreshToken !== '' ? $refreshToken : null,
'expires_in' => (int) ($json['expires_in'] ?? 3600),
];
}
private function isInvalidGrant(AdsenseOAuthException $exception): bool
{
$message = Str::lower($exception->getMessage());
return str_contains($message, 'invalid_grant')
|| str_contains($message, 'revoked')
|| str_contains($message, 'invalid_token');
}
private function cacheKey(int $connectionId): string
{
return (string) config('adsense.access_token_cache_prefix', 'adsense.access_token.').$connectionId;
}
private function clientId(): string
{
return trim((string) config('adsense.client_id'));
}
private function clientSecret(): string
{
return trim((string) config('adsense.client_secret'));
}
public function redirectUri(): string
{
return trim((string) config('adsense.redirect_uri'));
}
}
@@ -0,0 +1,216 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense;
use App\Models\AdsenseDailyStat;
final class AdsenseReportParser
{
/**
* @var array<string, string>
*/
private const METRIC_COLUMNS = [
'ESTIMATED_EARNINGS' => 'estimated_earnings',
'PAGE_VIEWS' => 'page_views',
'PAGE_VIEWS_CTR' => 'page_views_ctr',
'PAGE_VIEWS_RPM' => 'page_views_rpm',
'AD_REQUESTS' => 'ad_requests',
'AD_REQUESTS_COVERAGE' => 'ad_requests_coverage',
'AD_REQUESTS_CTR' => 'ad_requests_ctr',
'AD_REQUESTS_RPM' => 'ad_requests_rpm',
'MATCHED_AD_REQUESTS' => 'matched_ad_requests',
'IMPRESSIONS' => 'impressions',
'IMPRESSIONS_CTR' => 'impressions_ctr',
'IMPRESSIONS_RPM' => 'impressions_rpm',
'CLICKS' => 'clicks',
'COST_PER_CLICK' => 'cost_per_click',
];
/**
* @var list<string>
*/
private const INTEGER_COLUMNS = [
'page_views',
'ad_requests',
'matched_ad_requests',
'impressions',
'clicks',
];
/**
* @param array<string, mixed> $report
* @return list<array<string, mixed>>
*/
public function parse(array $report, string $dimensionType, string $accountResourceName): array
{
$indexByName = $this->headerIndex($report['headers'] ?? []);
$currencyCode = $this->currencyCode($report['headers'] ?? []);
$rows = [];
foreach ($report['rows'] ?? [] as $row) {
if (! is_array($row)) {
continue;
}
$cells = $row['cells'] ?? [];
if (! is_array($cells)) {
continue;
}
$date = $this->cell($cells, $indexByName, 'DATE');
if (! is_string($date) || $date === '') {
continue;
}
$dimensionKey = $this->dimensionKey($cells, $indexByName, $dimensionType);
if ($dimensionKey === null || $dimensionKey === '') {
continue;
}
$parsed = [
'date' => $date,
'account_resource_name' => $accountResourceName,
'dimension_type' => $dimensionType,
'dimension_key' => $dimensionKey,
'dimension_label' => $this->dimensionLabel($cells, $indexByName, $dimensionType, $dimensionKey),
'currency_code' => $currencyCode,
];
foreach (self::METRIC_COLUMNS as $header => $column) {
$parsed[$column] = $this->metricValue($cells, $indexByName, $header, $column);
}
$rows[] = $parsed;
}
return $rows;
}
public function currencyCode(array $headers): ?string
{
foreach ($headers as $header) {
if (! is_array($header)) {
continue;
}
$type = strtoupper((string) ($header['type'] ?? ''));
$code = trim((string) ($header['currencyCode'] ?? ''));
if ($type === 'METRIC_CURRENCY' && $code !== '') {
return $code;
}
}
return null;
}
/**
* @return array<string, int>
*/
private function headerIndex(mixed $headers): array
{
$index = [];
if (! is_array($headers)) {
return $index;
}
foreach ($headers as $position => $header) {
if (! is_array($header)) {
continue;
}
$name = strtoupper(trim((string) ($header['name'] ?? '')));
if ($name === '') {
continue;
}
$index[$name] = (int) $position;
}
return $index;
}
/**
* @param array<int, mixed> $cells
* @param array<string, int> $indexByName
*/
private function dimensionKey(array $cells, array $indexByName, string $dimensionType): ?string
{
return match ($dimensionType) {
AdsenseDailyStat::DIMENSION_TOTAL => AdsenseDailyStat::TOTAL_DIMENSION_KEY,
AdsenseDailyStat::DIMENSION_AD_UNIT => $this->cell($cells, $indexByName, 'AD_UNIT_ID')
?? $this->cell($cells, $indexByName, 'AD_UNIT_NAME'),
AdsenseDailyStat::DIMENSION_CUSTOM_CHANNEL => $this->cell($cells, $indexByName, 'CUSTOM_CHANNEL_ID')
?? $this->cell($cells, $indexByName, 'CUSTOM_CHANNEL_NAME'),
AdsenseDailyStat::DIMENSION_PLATFORM => $this->cell($cells, $indexByName, 'PLATFORM_TYPE_CODE')
?? $this->cell($cells, $indexByName, 'PLATFORM_TYPE_NAME'),
AdsenseDailyStat::DIMENSION_COUNTRY => $this->cell($cells, $indexByName, 'COUNTRY_CODE')
?? $this->cell($cells, $indexByName, 'COUNTRY_NAME'),
default => null,
};
}
/**
* @param array<int, mixed> $cells
* @param array<string, int> $indexByName
*/
private function dimensionLabel(array $cells, array $indexByName, string $dimensionType, string $dimensionKey): string
{
$label = match ($dimensionType) {
AdsenseDailyStat::DIMENSION_TOTAL => 'Total',
AdsenseDailyStat::DIMENSION_AD_UNIT => $this->cell($cells, $indexByName, 'AD_UNIT_NAME'),
AdsenseDailyStat::DIMENSION_CUSTOM_CHANNEL => $this->cell($cells, $indexByName, 'CUSTOM_CHANNEL_NAME'),
AdsenseDailyStat::DIMENSION_PLATFORM => $this->cell($cells, $indexByName, 'PLATFORM_TYPE_NAME')
?? $this->cell($cells, $indexByName, 'PLATFORM_TYPE_CODE'),
AdsenseDailyStat::DIMENSION_COUNTRY => $this->cell($cells, $indexByName, 'COUNTRY_NAME')
?? $this->cell($cells, $indexByName, 'COUNTRY_CODE'),
default => $dimensionKey,
};
return is_string($label) && $label !== '' ? $label : $dimensionKey;
}
/**
* @param array<int, mixed> $cells
* @param array<string, int> $indexByName
*/
private function cell(array $cells, array $indexByName, string $name): ?string
{
$name = strtoupper($name);
if (! array_key_exists($name, $indexByName)) {
return null;
}
$cell = $cells[$indexByName[$name]] ?? null;
if (is_array($cell)) {
$value = $cell['value'] ?? null;
return is_scalar($value) ? (string) $value : null;
}
return is_scalar($cell) ? (string) $cell : null;
}
/**
* @param array<int, mixed> $cells
* @param array<string, int> $indexByName
*/
private function metricValue(array $cells, array $indexByName, string $header, string $column): int|string|null
{
$raw = $this->cell($cells, $indexByName, $header);
if ($raw === null || $raw === '') {
return null;
}
if (in_array($column, self::INTEGER_COLUMNS, true)) {
return (int) $raw;
}
if (! is_numeric($raw)) {
return null;
}
return $raw;
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense;
final class AdsenseSyncResult
{
/**
* @param list<string> $failedReports
*/
public function __construct(
public string $accountDisplayName = '',
public string $from = '',
public string $to = '',
public int $adUnits = 0,
public int $customChannels = 0,
public int $totalRows = 0,
public int $adUnitRows = 0,
public int $customChannelRows = 0,
public int $platformRows = 0,
public int $countryRows = 0,
public array $failedReports = [],
public bool $entitiesSynced = false,
public bool $reconnectRequired = false,
) {}
public function succeeded(): bool
{
return ! $this->reconnectRequired && $this->failedReports === [];
}
}
+358
View File
@@ -0,0 +1,358 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense;
use App\Models\AdsenseConnection;
use App\Models\AdsenseDailyStat;
use App\Models\AdsenseEntity;
use App\Services\Adsense\Exceptions\AdsenseApiException;
use App\Services\Adsense\Exceptions\AdsenseAuthorizationException;
use App\Services\Adsense\Exceptions\AdsenseOAuthException;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
final class AdsenseSyncService
{
public function __construct(
private readonly AdsenseApiClient $api,
private readonly AdsenseReportParser $parser,
private readonly AdsenseOAuthService $oauth,
) {}
public function sync(
AdsenseConnection $connection,
Carbon $from,
Carbon $to,
bool $entitiesOnly = false,
): AdsenseSyncResult {
$result = new AdsenseSyncResult(
accountDisplayName: (string) ($connection->account_display_name ?: $connection->account_resource_name),
from: $from->toDateString(),
to: $to->toDateString(),
);
$connection->last_sync_attempt_at = now();
$connection->save();
try {
$this->syncEntities($connection, $result);
if (! $entitiesOnly) {
$this->syncReports($connection, $from, $to, $result);
}
if ($result->reconnectRequired) {
return $result;
}
$connection->last_successful_sync_at = now();
$connection->status = $result->failedReports === []
? AdsenseConnection::STATUS_CONNECTED
: AdsenseConnection::STATUS_ERROR;
$connection->last_error = $result->failedReports === []
? null
: 'Partial AdSense sync failure: '.implode(', ', $result->failedReports);
$connection->save();
} catch (AdsenseAuthorizationException $exception) {
$result->reconnectRequired = true;
$this->oauth->markReconnectRequired($connection, $exception->getMessage());
} catch (AdsenseOAuthException $exception) {
$result->failedReports[] = 'oauth';
$connection->status = AdsenseConnection::STATUS_ERROR;
$connection->last_error = $exception->getMessage();
$connection->save();
} catch (AdsenseApiException $exception) {
$result->failedReports[] = 'entities';
Log::warning('AdSense entity synchronization failed.', AdsenseLogSanitizer::context([
'status' => $exception->status,
'message' => $exception->getMessage(),
]));
$connection->status = AdsenseConnection::STATUS_ERROR;
$connection->last_error = $exception->getMessage();
$connection->save();
}
return $result;
}
public function syncEntities(AdsenseConnection $connection, ?AdsenseSyncResult $result = null): AdsenseSyncResult
{
$result ??= new AdsenseSyncResult(
accountDisplayName: (string) ($connection->account_display_name ?: $connection->account_resource_name),
);
$account = (string) $connection->account_resource_name;
if ($account === '') {
throw new AdsenseApiException('No AdSense account is selected.');
}
$adClients = $this->api->listAdClients($connection, $account);
$now = now();
$adUnits = 0;
$customChannels = 0;
foreach ($adClients as $client) {
$clientName = (string) ($client['name'] ?? '');
if ($clientName === '' || ! $this->supportsInventory($client)) {
continue;
}
try {
foreach ($this->api->listAdUnits($connection, $clientName) as $unit) {
$this->upsertEntity($account, $clientName, AdsenseEntity::TYPE_AD_UNIT, $unit, $now);
$adUnits++;
}
} catch (AdsenseAuthorizationException $exception) {
throw $exception;
} catch (AdsenseApiException $exception) {
$this->logSkippedClient($clientName, 'ad_units', $exception);
}
try {
foreach ($this->api->listCustomChannels($connection, $clientName) as $channel) {
$this->upsertEntity($account, $clientName, AdsenseEntity::TYPE_CUSTOM_CHANNEL, $channel, $now);
$customChannels++;
}
} catch (AdsenseAuthorizationException $exception) {
throw $exception;
} catch (AdsenseApiException $exception) {
$this->logSkippedClient($clientName, 'custom_channels', $exception);
}
}
$result->adUnits = $adUnits;
$result->customChannels = $customChannels;
$result->entitiesSynced = true;
return $result;
}
private function syncReports(
AdsenseConnection $connection,
Carbon $from,
Carbon $to,
AdsenseSyncResult $result,
): void {
$account = (string) $connection->account_resource_name;
$metrics = array_values((array) config('adsense.metrics', []));
$definitions = [
AdsenseDailyStat::DIMENSION_TOTAL => ['DATE'],
AdsenseDailyStat::DIMENSION_AD_UNIT => ['DATE', 'AD_UNIT_ID'],
AdsenseDailyStat::DIMENSION_CUSTOM_CHANNEL => ['DATE', 'CUSTOM_CHANNEL_ID'],
AdsenseDailyStat::DIMENSION_PLATFORM => ['DATE', 'PLATFORM_TYPE_CODE'],
AdsenseDailyStat::DIMENSION_COUNTRY => ['DATE', 'COUNTRY_CODE'],
];
foreach ($definitions as $dimensionType => $dimensions) {
try {
$report = $this->api->generateReport(
$connection,
$account,
$dimensions,
$metrics,
$from,
$to,
$dimensionType,
);
$rows = $this->parser->parse($report, $dimensionType, $account);
$this->applyEntityLabels($rows, $account, $dimensionType);
$saved = $this->upsertStats($rows);
match ($dimensionType) {
AdsenseDailyStat::DIMENSION_TOTAL => $result->totalRows = $saved,
AdsenseDailyStat::DIMENSION_AD_UNIT => $result->adUnitRows = $saved,
AdsenseDailyStat::DIMENSION_CUSTOM_CHANNEL => $result->customChannelRows = $saved,
AdsenseDailyStat::DIMENSION_PLATFORM => $result->platformRows = $saved,
AdsenseDailyStat::DIMENSION_COUNTRY => $result->countryRows = $saved,
default => null,
};
} catch (AdsenseAuthorizationException $exception) {
$result->reconnectRequired = true;
throw $exception;
} catch (AdsenseApiException $exception) {
$result->failedReports[] = $dimensionType;
Log::warning('AdSense report synchronization failed.', AdsenseLogSanitizer::context([
'report' => $dimensionType,
'status' => $exception->status,
'message' => $exception->getMessage(),
]));
}
}
}
/**
* Website content ad clients (AFC / ca-pub-...) expose ad units.
* YouTube host clients (ca-yt-host-pub-...) are listed by Google but 404 on adunits.
*
* @param array<string, mixed> $client
*/
private function supportsInventory(array $client): bool
{
$name = strtolower((string) ($client['name'] ?? ''));
$reportingId = strtolower((string) ($client['reportingDimensionId'] ?? ''));
$haystack = $name.' '.$reportingId;
foreach ((array) config('adsense.inventory_excluded_client_prefixes', ['ca-yt-host-']) as $prefix) {
$prefix = strtolower(trim((string) $prefix));
if ($prefix !== '' && str_contains($haystack, $prefix)) {
return false;
}
}
$product = strtoupper(trim((string) ($client['productCode'] ?? '')));
$allowed = array_values(array_filter(array_map(
static fn (mixed $code): string => strtoupper(trim((string) $code)),
(array) config('adsense.inventory_product_codes', ['AFC']),
)));
if ($product !== '' && $allowed !== [] && ! in_array($product, $allowed, true)) {
return false;
}
return true;
}
private function logSkippedClient(string $clientName, string $kind, AdsenseApiException $exception): void
{
Log::warning('AdSense skipped an ad client inventory request.', AdsenseLogSanitizer::context([
'client' => $clientName,
'kind' => $kind,
'status' => $exception->status,
'message' => $exception->getMessage(),
]));
}
/**
* @param array<string, mixed> $entity
*/
private function upsertEntity(
string $account,
string $adClient,
string $type,
array $entity,
Carbon $seenAt,
): void {
$resourceName = (string) ($entity['name'] ?? '');
$reportingId = (string) ($entity['reportingDimensionId'] ?? '');
if ($reportingId === '' && $resourceName !== '') {
$reportingId = (string) str($resourceName)->afterLast('/');
}
if ($reportingId === '') {
return;
}
$state = strtoupper((string) ($entity['state'] ?? ''));
$active = $state === '' ? null : $state === 'ACTIVE' || $state === 'READY';
AdsenseEntity::query()->updateOrCreate(
[
'account_resource_name' => $account,
'type' => $type,
'reporting_dimension_id' => $reportingId,
],
[
'ad_client_resource_name' => $adClient,
'resource_name' => $resourceName !== '' ? $resourceName : null,
'display_name' => (string) ($entity['displayName'] ?? $reportingId),
'active' => $active,
'last_seen_at' => $seenAt,
],
);
}
/**
* @param list<array<string, mixed>> $rows
*/
private function applyEntityLabels(array &$rows, string $account, string $dimensionType): void
{
if (! in_array($dimensionType, [AdsenseDailyStat::DIMENSION_AD_UNIT, AdsenseDailyStat::DIMENSION_CUSTOM_CHANNEL], true)) {
return;
}
$labels = AdsenseEntity::query()
->where('account_resource_name', $account)
->where('type', $dimensionType)
->pluck('display_name', 'reporting_dimension_id');
foreach ($rows as &$row) {
$key = (string) ($row['dimension_key'] ?? '');
if ($key !== '' && isset($labels[$key]) && is_string($labels[$key]) && $labels[$key] !== '') {
$row['dimension_label'] = $labels[$key];
}
}
unset($row);
}
/**
* @param list<array<string, mixed>> $rows
*/
private function upsertStats(array $rows): int
{
if ($rows === []) {
return 0;
}
$now = now();
$payload = [];
foreach ($rows as $row) {
$payload[] = [
'date' => $row['date'],
'account_resource_name' => $row['account_resource_name'],
'dimension_type' => $row['dimension_type'],
'dimension_key' => $row['dimension_key'],
'dimension_label' => $row['dimension_label'] ?? null,
'currency_code' => $row['currency_code'] ?? null,
'page_views' => $row['page_views'] ?? null,
'ad_requests' => $row['ad_requests'] ?? null,
'matched_ad_requests' => $row['matched_ad_requests'] ?? null,
'impressions' => $row['impressions'] ?? null,
'clicks' => $row['clicks'] ?? null,
'estimated_earnings' => $row['estimated_earnings'] ?? null,
'page_views_ctr' => $row['page_views_ctr'] ?? null,
'page_views_rpm' => $row['page_views_rpm'] ?? null,
'ad_requests_coverage' => $row['ad_requests_coverage'] ?? null,
'ad_requests_ctr' => $row['ad_requests_ctr'] ?? null,
'ad_requests_rpm' => $row['ad_requests_rpm'] ?? null,
'impressions_ctr' => $row['impressions_ctr'] ?? null,
'impressions_rpm' => $row['impressions_rpm'] ?? null,
'cost_per_click' => $row['cost_per_click'] ?? null,
'last_synced_at' => $now,
'created_at' => $now,
'updated_at' => $now,
];
}
foreach (array_chunk($payload, 200) as $chunk) {
AdsenseDailyStat::query()->upsert(
$chunk,
['account_resource_name', 'date', 'dimension_type', 'dimension_key'],
[
'dimension_label',
'currency_code',
'page_views',
'ad_requests',
'matched_ad_requests',
'impressions',
'clicks',
'estimated_earnings',
'page_views_ctr',
'page_views_rpm',
'ad_requests_coverage',
'ad_requests_ctr',
'ad_requests_rpm',
'impressions_ctr',
'impressions_rpm',
'cost_per_click',
'last_synced_at',
'updated_at',
],
);
}
return count($payload);
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense\Exceptions;
final class AdsenseApiException extends AdsenseException
{
public function __construct(
string $message,
public readonly int $status = 0,
public readonly string $report = '',
?\Throwable $previous = null,
) {
parent::__construct($message, $status, $previous);
}
}
@@ -0,0 +1,7 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense\Exceptions;
final class AdsenseAuthorizationException extends AdsenseException {}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense\Exceptions;
use RuntimeException;
class AdsenseException extends RuntimeException {}
@@ -0,0 +1,7 @@
<?php
declare(strict_types=1);
namespace App\Services\Adsense\Exceptions;
final class AdsenseOAuthException extends AdsenseException {}