# GET /v1/stats

获取统计

站长的弹出数、收益和eCPM，可按date、hour、site、zone、country、device、os、browser或page_domain分组；支持JSON或CSV。browser筛选接受规范的浏览器键。按浏览器统计的收益按展示量比例分摊。浏览器视图可能不可用或已关闭；请检查/v1/stats/availability。在执行统计查询之前，不可用的浏览器分组或筛选会返回400 breakdown_unavailable，并附带breakdown browser（JSON和CSV）。按page_domain分组或筛选仅在测量生效后可用：在此之前返回400 `page_domain_unavailable`，JSON响应会带有`page_domain_available`。当group_by包含`hour`时，范围（两端均含，按EST工作日）最多31天，否则返回400 `hour_range`；已最终确认日期的小时收益是对当日收益的分摊（响应中带有`hourly_revenue_allocated: true`），并非逐小时测量值；尚未最终确认日期的小时数据为预估。JSON中的小时为ISO UTC格式；CSV中的小时按EST（UTC-5）显示。每行的状态为estimated、reported、final或mixed；有效展示为零时eCPM为null。响应会标明所接受的计数和金额快照。需要权限范围publisher:read（API密钥或网页会话）。速率限制等级：stats。

- 所需权限范围: `publisher:read`
- 速率限制: `stats` — 30 次请求/60秒窗口 每个API密钥或网页会话

## 参数

| 名称 | 位置 | 类型 | 必填 |
|---|---|---|---|
| `from` | query | string | 是 |
| `to` | query | string | 是 |
| `group_by` | query | ("date" \| "hour" \| "site" \| "zone" \| "country" \| "device" \| "os" \| "browser" \| "page_domain")[] | 否 |
| `metrics` | query | ("pops" \| "revenue" \| "ecpm")[] | 否 |
| `site_id` | query | integer | 否 |
| `zone_id` | query | integer | 否 |
| `country` | query | string | 否 |
| `browser` | query | "chrome" \| "safari" \| "firefox" \| "edge" \| "samsung_internet" \| "opera" \| "uc_browser" \| "yandex" \| "other" | 否 |
| `page_domain` | query | string | 否 |
| `format` | query | "json" \| "csv" | 否 |

## 响应

```
{ browser_missing_days?: string[]; count_basis?: "valid" | "legacy" | "mixed"; currency: "USD"; data_as_of?: string | null; estimated_from: string | null; forecast_basis_version?: "forecast-basis-v1"; forecast_generation?: string; forecast_updated_at?: string | null; hourly_revenue_allocated?: true; measurement_definition?: { complete: boolean; includes_direct: boolean; includes_legacy: boolean; tag_valid_after_ms: integer[] }; measurement_generation?: string; measurement_status?: "ok" | "stale" | "updating"; measurement_updated_at?: string | null; money_basis_version?: string; money_generation?: string; page_domain_available?: boolean; rows: { browser?: "chrome" | "safari" | "firefox" | "edge" | "samsung_internet" | "opera" | "uc_browser" | "yandex" | "other"; country?: string; date?: string; device?: string; ecpm?: string | null; hour?: string; os?: string; page_domain?: string | null; pops?: integer; publisher_id?: integer; revenue?: string; site_deleted?: true; site_domain?: string; site_id?: integer; status?: "estimated" | "reported" | "final" | "mixed"; zone_deleted?: true; zone_id?: integer; zone_name?: string }[]; totals: { ecpm: string | null; pops: integer; revenue: string; status?: "estimated" | "reported" | "final" | "mixed" }; truncated?: boolean; updated_at?: string | null }
```

## 错误

有速率限制的路由会返回`RateLimit-Limit`、`RateLimit-Remaining`和`RateLimit-Reset`（距窗口结束的秒数）；429响应还会带有`Retry-After`。限流器暂时不可用时，这些响应头可能缺失（此时请求会被放行）。

| 状态码 | 含义 |
|---|---|
| 401 | API密钥缺失、无效或已被撤销。 |
| 403 | 该密钥缺少所需的权限范围，或该主体无权执行此操作。 |
| 429 | 已超出速率限制；请等待`Retry-After`秒后重试。 |
| 400 | Default Response |
| 404 | Default Response |
| 503 | Default Response |

## 示例

### cURL

```bash
#!/usr/bin/env bash
# GET /v1/stats: daily pops, revenue and eCPM for the last 7 calendar days (EST, fixed UTC-5).
# Needs: AGIMONE_API_KEY (create one at https://app.agimone.com/app/account/api-keys). Optional: AGIMONE_API_BASE, AGIMONE_FROM, AGIMONE_TO.
set -euo pipefail
BASE="${AGIMONE_API_BASE:-https://app.agimone.com}"
# Snapshot the EST day once; calendar arithmetic uses that date label.
TODAY="$(TZ=Etc/GMT+5 date +%F)"
# `date -v` is BSD/macOS, `date -d` is GNU/Linux.
FROM="${AGIMONE_FROM:-$(date -u -j -v-6d -f '%Y-%m-%d' "$TODAY" +%F 2>/dev/null || date -u -d "$TODAY -6 days" +%F)}"
TO="${AGIMONE_TO:-$TODAY}"
curl -fsS -H "Authorization: Bearer $AGIMONE_API_KEY" \
  "$BASE/v1/stats?from=$FROM&to=$TO&group_by=date&metrics=pops,revenue,ecpm"
echo
```

### Node.js

```js
// GET /v1/stats: daily pops, revenue and eCPM for the last 7 calendar days (EST, fixed UTC-5). Node 18+, no dependencies.
// Needs: AGIMONE_API_KEY (create one at https://app.agimone.com/app/account/api-keys). Optional: AGIMONE_API_BASE, AGIMONE_FROM, AGIMONE_TO.
const base = process.env.AGIMONE_API_BASE ?? 'https://app.agimone.com';
const parts = new Intl.DateTimeFormat('en-US', { timeZone: 'Etc/GMT+5', year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date());
const part = (type) => parts.find((p) => p.type === type).value;
const today = `${part('year')}-${part('month')}-${part('day')}`;
const day = (offset) => new Date(Date.parse(`${today}T00:00:00Z`) + offset * 86_400_000).toISOString().slice(0, 10);
const query = new URLSearchParams({
  from: process.env.AGIMONE_FROM ?? day(-6),
  to: process.env.AGIMONE_TO ?? today,
  group_by: 'date',
  metrics: 'pops,revenue,ecpm',
});

const res = await fetch(`${base}/v1/stats?${query}`, {
  headers: { Authorization: `Bearer ${process.env.AGIMONE_API_KEY}` },
});
if (!res.ok) {
  console.error(`HTTP ${res.status}: ${await res.text()}`);
  process.exit(1);
}
console.log(JSON.stringify(await res.json()));
```

### PHP

```php
<?php
// GET /v1/stats: daily pops, revenue and eCPM for the last 7 calendar days (EST, fixed UTC-5). PHP 8 with the curl extension, no other dependencies.
// Needs: AGIMONE_API_KEY (create one at https://app.agimone.com/app/account/api-keys). Optional: AGIMONE_API_BASE, AGIMONE_FROM, AGIMONE_TO.
$base = getenv('AGIMONE_API_BASE') ?: 'https://app.agimone.com';
$today = new DateTimeImmutable('now', new DateTimeZone('Etc/GMT+5'));
$query = http_build_query([
    'from' => getenv('AGIMONE_FROM') ?: $today->modify('-6 days')->format('Y-m-d'),
    'to' => getenv('AGIMONE_TO') ?: $today->format('Y-m-d'),
    'group_by' => 'date',
    'metrics' => 'pops,revenue,ecpm',
]);

$ch = curl_init("$base/v1/stats?$query");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('AGIMONE_API_KEY')],
    CURLOPT_TIMEOUT => 15,
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
    fwrite(STDERR, "HTTP $status: " . ($body === false ? curl_error($ch) : $body) . "\n");
    exit(1);
}
curl_close($ch);
echo trim($body), "\n";
```

### Python

```python
# GET /v1/stats: daily pops, revenue and eCPM for the last 7 calendar days (EST, fixed UTC-5). Python 3.8+, standard library only.
# Needs: AGIMONE_API_KEY (create one at https://app.agimone.com/app/account/api-keys). Optional: AGIMONE_API_BASE, AGIMONE_FROM, AGIMONE_TO.
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone

base = os.environ.get("AGIMONE_API_BASE", "https://app.agimone.com")
# Fixed UTC-5 is Etc/GMT+5; Python 3.8 needs no zoneinfo/tzdata dependency.
today = datetime.now(timezone(timedelta(hours=-5))).date()
query = urllib.parse.urlencode({
    "from": os.environ.get("AGIMONE_FROM", str(today - timedelta(days=6))),
    "to": os.environ.get("AGIMONE_TO", str(today)),
    "group_by": "date",
    "metrics": "pops,revenue,ecpm",
})
req = urllib.request.Request(
    f"{base}/v1/stats?{query}",
    headers={"Authorization": f"Bearer {os.environ['AGIMONE_API_KEY']}"},
)
try:
    with urllib.request.urlopen(req, timeout=15) as res:
        print(json.dumps(json.load(res)))
except urllib.error.HTTPError as e:
    print(f"HTTP {e.code}: {e.read().decode()}", file=sys.stderr)
    sys.exit(1)
```

HTML文档: https://agimone.com/zh/developers/api/#get-stats
API 2026-10
