# Rakuten Advertising Publisher Reports (BYOC) (`viralanalyzer/rakuten-marketing-publisher-stats`) Actor

Retrieve Rakuten Advertising publisher advanced reports via the official API (BYOC): commissions, advertiser payments, performance metrics and payout data.

- **URL**: https://apify.com/viralanalyzer/rakuten-marketing-publisher-stats.md
- **Developed by:** [viralanalyzer](https://apify.com/viralanalyzer) (community)
- **Categories:** E-commerce, Marketing
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 record scrapeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/platform/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## 📊 Rakuten Advertising Publisher Stats — Advanced Financial Reports via Official API

> 🔗 [View on Apify Store](https://apify.com/viralanalyzer/rakuten-marketing-publisher-stats) | 🇺🇸 English | [🇧🇷 Português](#português)

Pull your **Rakuten Advertising (formerly LinkShare) publisher financial reports** straight from the **official Advanced Reports API** — payment history, advertiser payments, and payment details. This is a **BYOC** actor (Bring Your Own Credentials): you authenticate with your own Rakuten tokens, and the data returned is *your* account's, fetched directly from `api.linksynergy.com`. No scraping, no browser — a clean authenticated API call.

### ✨ Features

- 🏦 **Official Advanced Reports API** — Direct `GET api.linksynergy.com/advancedreports/1.0`, no scraping
- 💵 **5 report types** — Payment History Summary, Advertiser Payments (v1/v2), Payment Details (v1/v2)
- 🔐 **Two auth modes** — Pre-generated Bearer token, OR OAuth `client_credentials` (clientId + clientSecret + siteId)
- 📅 **Flexible date window** — `startDate` / `endDate` in `YYYYMMDD`; defaults to the **last 90 days**
- 🧾 **CSV → structured JSON** — Comma-delimited report parsed into clean records (numeric coercion; blanks → `null`)
- 🔄 **Dynamic columns** — Fields mirror the chosen report's columns, plus `reportId`, `bdate`, `edate`, `scrapedAt`
- 🛡️ **BYOC & owner-skip** — Tokens stay in secret inputs; PPE is never charged on internal owner runs
- 🧭 **Self-diagnosing** — Missing/expired credentials or empty ranges return a Setup Guide, not a silent failure

### 📥 Input

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `reportId` | string | ✅ | `"22"` | Which report to fetch (see report types below) |
| `securityToken` | string (secret) | ✅ | — | Web Service Security Token from your Publisher Dashboard (Support → Manage Tokens → Security Token) |
| `accessToken` | string (secret) | ⬦ | — | Pre-generated Developer Access Token (Bearer/JWT). If blank, OAuth fields are required |
| `clientId` | string | ⬦ | — | OAuth Client ID (required if `accessToken` is blank) |
| `clientSecret` | string (secret) | ⬦ | — | OAuth Client Secret (required if `accessToken` is blank) |
| `siteId` | string | ⬦ | — | Your numeric Publisher Site ID, e.g. a 7-digit number (required if `accessToken` is blank) |
| `startDate` | string | ❌ | 90 days ago | Report start date in `YYYYMMDD` (e.g. `20260401`) |
| `endDate` | string | ❌ | today | Report end date in `YYYYMMDD` (e.g. `20260525`) |
| `proxyConfiguration` | object | ❌ | Apify Proxy on | Apify Proxy configuration |

> ⬦ **Authentication:** `securityToken` is **always** required. For the Bearer token you choose **one** path: provide `accessToken` directly, **or** provide all three OAuth fields (`clientId` + `clientSecret` + `siteId`) so the actor performs the `client_credentials` flow for you.

#### Report Types (`reportId`)

| `reportId` | Report |
|---|---|
| `1` | Payment History Summary |
| `2` | Advertiser Payments History (v1) |
| `22` | Advertiser Payments History (v2) — **default** |
| `3` | Payment Details (v1) |
| `23` | Payment Details (v2) |

> v2 reports (`22`, `23`) generally contain additional columns compared to their v1 counterparts.

#### Input Example

```json
{
  "reportId": "22",
  "securityToken": "YOUR_WEB_SERVICE_SECURITY_TOKEN",
  "clientId": "YOUR_OAUTH_CLIENT_ID",
  "clientSecret": "YOUR_OAUTH_CLIENT_SECRET",
  "siteId": "1234567",
  "startDate": "20260401",
  "endDate": "20260525",
  "proxyConfiguration": { "useApifyProxy": true }
}
````

> To use a pre-generated Bearer token instead of OAuth, drop `clientId` / `clientSecret` / `siteId` and add `"accessToken": "YOUR_PRE_GENERATED_BEARER_TOKEN"`.

### 📤 Output

Rakuten returns each report as a **comma-delimited CSV**. The actor parses it into one dataset record per row, using the **report's own header line as field names** — so the exact columns are **dynamic and depend on the `reportId` you choose** (and whether it is a v1 or v2 report). Values that look numeric are automatically coerced to numbers; blanks become `null`.

On **every** record, the actor appends these run-context fields:

| Field | Type | Description |
|---|---|---|
| *(report columns)* | string | number | null | Dynamic — taken verbatim from the report's CSV header (e.g. advertiser, amount, currency, payment date, etc., varying by report) |
| `reportId` | string | The report type that was fetched |
| `bdate` | string | Effective report start date used (`YYYYMMDD`) |
| `edate` | string | Effective report end date used (`YYYYMMDD`) |
| `scrapedAt` | string | ISO 8601 timestamp of the run |

#### Output Example (illustrative — actual columns vary by report)

```json
{
  "Advertiser ID": 38901,
  "Advertiser Name": "Example Merchant",
  "Payment Amount": 152.47,
  "Currency": "USD",
  "Payment Date": "2026-05-15",
  "reportId": "22",
  "bdate": "20260401",
  "edate": "20260525",
  "scrapedAt": "2026-06-06T12:00:00.000Z"
}
```

> ℹ️ Column names above are placeholders to show the shape of a record. The real field names come directly from Rakuten's report header for your chosen `reportId`.

#### Diagnostic output

If credentials are missing/expired or the date range has no data, the actor **succeeds** with a single diagnostic record (`setup_status: "DIAGNOSTIC_GUIDE"`, `_dataQuality: "diagnostic"`) describing the likely cause and how to fix it. Diagnostic runs **do not** charge PPE, and the raw API response is saved to the Key-Value Store under `debug-raw-response` for inspection.

### 📋 Use Cases

- **Affiliate revenue accounting** — Reconcile Rakuten advertiser payments against your books
- **Payment tracking** — Monitor what has been paid, by which advertiser, and when
- **Commission analytics** — Feed advertiser payment data into dashboards or a data warehouse
- **Automated finance pipelines** — Schedule recurring pulls (e.g. monthly) and route to Sheets, BigQuery, or a database
- **Multi-period comparison** — Pull different date windows to track payment trends over time
- **Cross-network consolidation** — Combine Rakuten payouts with other affiliate networks in one data layer

### ❓ FAQ

**Q: Do I need my own Rakuten credentials?**
A: Yes — this is a BYOC (Bring Your Own Credentials) actor. You must supply your own `securityToken` plus either a pre-generated `accessToken` or OAuth `clientId` + `clientSecret` + `siteId`. The actor only accesses *your* Rakuten account.

**Q: Where do I get the Security Token?**
A: From your Rakuten Publisher Dashboard under **Support → Manage Tokens → Security Token**, or at `https://publisher.rakutenadvertising.com/api-links/tokens`.

**Q: Where do I get OAuth credentials or a Developer Access Token?**
A: From the Rakuten Developer Portal at `https://developers.rakutenadvertising.com/` under **Applications**.

**Q: Bearer token vs OAuth — which should I use?**
A: If you already have a pre-generated Developer Access Token, paste it into `accessToken`. Otherwise provide `clientId` + `clientSecret` + `siteId` and the actor will run the OAuth `client_credentials` flow and obtain a Bearer token automatically. Pre-generated tokens typically expire (~24h), so OAuth is more convenient for scheduled runs.

**Q: What date range is used if I leave the dates blank?**
A: The last **90 days** — `endDate` defaults to today and `startDate` to 90 days ago. Provide `startDate` / `endDate` in `YYYYMMDD` to override.

**Q: Why did my run return zero records?**
A: Common causes: no transactions in the date range, an expired `securityToken` or `accessToken`, or an account not yet approved for the Advanced Reports API. The actor returns a Setup Guide with remediation steps and saves the raw response to the `debug-raw-response` Key-Value Store key.

**Q: Which columns will I get?**
A: It depends on the report. The output columns are dynamic and come straight from the CSV header Rakuten returns for the `reportId` you selected. v2 reports usually include more columns than v1.

### 💰 Pricing

This actor uses **Pay Per Event (PPE)** pricing with a single event:

| Event | When it fires |
|---|---|
| `record-scraped` | Once per report record (CSV row) pushed to the dataset |

Diagnostic runs (missing credentials, expired tokens, empty date ranges) **do not** charge any event. Internal owner runs are skipped from charging.

For current per-event pricing, see the actor page: **https://apify.com/viralanalyzer/rakuten-marketing-publisher-stats**

### 🔗 Related Actors

- [Awin Multi-Merchant Affiliate](https://apify.com/viralanalyzer/awin-multi-merchant-affiliate) — Affiliate merchant discovery & tracking links
- [Yahoo Finance Intelligence](https://apify.com/viralanalyzer/yahoo-finance-intelligence) — Quotes, fundamentals & analyst ratings
- [TradingView Screener](https://apify.com/viralanalyzer/tradingview-screener) — Technical analysis & market scanner
- [Amazon Brazil Intelligence](https://apify.com/viralanalyzer/amazon-brazil-intelligence) — Product & price intelligence

### 📝 Changelog

#### v1.0 (Current)

- ✅ Official Rakuten Advertising Advanced Reports API integration
- ✅ 5 report types (Payment History Summary, Advertiser Payments v1/v2, Payment Details v1/v2)
- ✅ Two auth modes: pre-generated Bearer token or OAuth `client_credentials`
- ✅ Configurable `YYYYMMDD` date window (defaults to last 90 days)
- ✅ CSV → structured JSON with dynamic columns + numeric coercion
- ✅ Run-context fields (`reportId`, `bdate`, `edate`, `scrapedAt`) on every record
- ✅ Self-diagnosing Setup Guide for recoverable errors (never silent-fail)
- ✅ BYOC secret inputs + owner-skip PPE billing (`record-scraped`)

***

<a name="português"></a>

## 📊 Rakuten Advertising Publisher Stats — Relatórios Financeiros Avançados via API Oficial

> [🇺🇸 English](#-rakuten-advertising-publisher-stats--advanced-financial-reports-via-official-api) | 🇧🇷 Português

Obtenha seus **relatórios financeiros de publisher do Rakuten Advertising (antigo LinkShare)** diretamente da **API oficial de Advanced Reports** — histórico de pagamentos, pagamentos de anunciantes e detalhes de pagamento. Este é um actor **BYOC** (Traga Suas Próprias Credenciais): você autentica com seus próprios tokens Rakuten e os dados retornados são da *sua* conta, buscados diretamente em `api.linksynergy.com`. Sem scraping, sem navegador — uma chamada de API autenticada e limpa.

### ✨ Funcionalidades

- 🏦 **API oficial de Advanced Reports** — Chamada direta `GET https://api.linksynergy.com/advancedreports/1.0`, sem scraping
- 💵 **5 tipos de relatório financeiro** — Resumo de Histórico de Pagamentos, Pagamentos de Anunciantes (v1/v2), Detalhes de Pagamento (v1/v2)
- 🔐 **Dois modos de autenticação** — Token Bearer pré-gerado, OU OAuth `client_credentials` (clientId + clientSecret + siteId)
- 📅 **Janela de datas flexível** — `startDate` / `endDate` em `YYYYMMDD`; padrão são os **últimos 90 dias** quando omitidos
- 🧾 **CSV convertido em JSON estruturado** — O relatório CSV (delimitado por vírgula) do Rakuten vira registros limpos com conversão numérica automática (vazios → `null`)
- 🔄 **Colunas dinâmicas** — Os campos de saída espelham as colunas que o relatório escolhido retorna, mais `reportId`, `bdate`, `edate`, `scrapedAt` em cada registro
- 🛡️ **BYOC & owner-skip** — Seus tokens ficam em campos de input secretos; o PPE nunca é cobrado em execuções internas do dono
- 🧭 **Autodiagnóstico** — Credenciais ausentes, tokens expirados ou intervalo de datas vazio retornam um Guia de Configuração claro em vez de falha silenciosa

### 📥 Entrada

| Parâmetro | Tipo | Obrigatório | Padrão | Descrição |
|---|---|---|---|---|
| `reportId` | string | ✅ | `"22"` | Qual relatório buscar (veja os tipos abaixo) |
| `securityToken` | string (secreto) | ✅ | — | Web Service Security Token do Painel do Publisher (Support → Manage Tokens → Security Token) |
| `accessToken` | string (secreto) | ⬦ | — | Developer Access Token (Bearer/JWT) pré-gerado. Se vazio, os campos OAuth são obrigatórios |
| `clientId` | string | ⬦ | — | OAuth Client ID (obrigatório se `accessToken` estiver vazio) |
| `clientSecret` | string (secreto) | ⬦ | — | OAuth Client Secret (obrigatório se `accessToken` estiver vazio) |
| `siteId` | string | ⬦ | — | Seu Publisher Site ID numérico, ex. um número de 7 dígitos (obrigatório se `accessToken` estiver vazio) |
| `startDate` | string | ❌ | 90 dias atrás | Data inicial do relatório em `YYYYMMDD` (ex. `20260401`) |
| `endDate` | string | ❌ | hoje | Data final do relatório em `YYYYMMDD` (ex. `20260525`) |
| `proxyConfiguration` | objeto | ❌ | Apify Proxy ligado | Configuração do Apify Proxy |

> ⬦ **Autenticação:** `securityToken` é **sempre** obrigatório. Para o token Bearer você escolhe **um** caminho: fornecer `accessToken` diretamente, **ou** fornecer os três campos OAuth (`clientId` + `clientSecret` + `siteId`) para que o actor execute o fluxo `client_credentials` por você.

#### Tipos de Relatório (`reportId`)

| `reportId` | Relatório |
|---|---|
| `1` | Resumo de Histórico de Pagamentos |
| `2` | Histórico de Pagamentos de Anunciantes (v1) |
| `22` | Histórico de Pagamentos de Anunciantes (v2) — **padrão** |
| `3` | Detalhes de Pagamento (v1) |
| `23` | Detalhes de Pagamento (v2) |

> Relatórios v2 (`22`, `23`) geralmente contêm colunas adicionais em comparação com suas versões v1.

#### Exemplo de Entrada

```json
{
  "reportId": "22",
  "securityToken": "SEU_WEB_SERVICE_SECURITY_TOKEN",
  "clientId": "SEU_OAUTH_CLIENT_ID",
  "clientSecret": "SEU_OAUTH_CLIENT_SECRET",
  "siteId": "1234567",
  "startDate": "20260401",
  "endDate": "20260525",
  "proxyConfiguration": { "useApifyProxy": true }
}
```

> Para usar um token Bearer pré-gerado em vez do OAuth, remova `clientId` / `clientSecret` / `siteId` e adicione `"accessToken": "SEU_TOKEN_BEARER_PRE_GERADO"`.

### 📤 Saída

O Rakuten retorna cada relatório como um **CSV delimitado por vírgula**. O actor o converte em um registro por linha, usando a **linha de cabeçalho do próprio relatório como nomes de campo** — portanto as colunas exatas são **dinâmicas e dependem do `reportId` escolhido** (e se é um relatório v1 ou v2). Valores que parecem numéricos são automaticamente convertidos para números; vazios viram `null`.

Em **todo** registro, o actor acrescenta estes campos de contexto da execução:

| Campo | Tipo | Descrição |
|---|---|---|
| *(colunas do relatório)* | string | número | null | Dinâmicas — extraídas literalmente do cabeçalho CSV do relatório (ex. anunciante, valor, moeda, data de pagamento, etc., variando por relatório) |
| `reportId` | string | O tipo de relatório que foi buscado |
| `bdate` | string | Data inicial efetiva usada (`YYYYMMDD`) |
| `edate` | string | Data final efetiva usada (`YYYYMMDD`) |
| `scrapedAt` | string | Timestamp ISO 8601 da execução |

#### Exemplo de Saída (ilustrativo — as colunas reais variam por relatório)

```json
{
  "Advertiser ID": 38901,
  "Advertiser Name": "Example Merchant",
  "Payment Amount": 152.47,
  "Currency": "USD",
  "Payment Date": "2026-05-15",
  "reportId": "22",
  "bdate": "20260401",
  "edate": "20260525",
  "scrapedAt": "2026-06-06T12:00:00.000Z"
}
```

> ℹ️ Os nomes de coluna acima são exemplos para mostrar o formato de um registro. Os nomes reais vêm diretamente do cabeçalho do relatório Rakuten para o `reportId` escolhido.

#### Saída de diagnóstico

Se as credenciais estiverem ausentes/expiradas ou o intervalo de datas não tiver dados, o actor **conclui com sucesso** emitindo um único registro de diagnóstico (`setup_status: "DIAGNOSTIC_GUIDE"`, `_dataQuality: "diagnostic"`) descrevendo a causa provável e como corrigir. Execuções de diagnóstico **não** cobram PPE, e a resposta bruta da API é salva no Key-Value Store na chave `debug-raw-response` para inspeção.

### 📋 Casos de Uso

- **Contabilidade de receita de afiliados** — Concilie os pagamentos de anunciantes Rakuten com sua contabilidade
- **Acompanhamento de pagamentos** — Monitore o que foi pago, por qual anunciante e quando
- **Analytics de comissões** — Alimente dados de pagamento de anunciantes em dashboards ou um data warehouse
- **Pipelines financeiros automatizados** — Agende coletas recorrentes (ex. mensais) e direcione para Sheets, BigQuery ou banco de dados
- **Comparação de períodos** — Busque diferentes janelas de datas para acompanhar tendências de pagamento ao longo do tempo
- **Consolidação entre redes** — Combine os repasses do Rakuten com outras redes de afiliados numa única camada de dados

### ❓ Perguntas Frequentes

**P: Preciso das minhas próprias credenciais Rakuten?**
R: Sim — este é um actor BYOC (Traga Suas Próprias Credenciais). Você deve fornecer seu próprio `securityToken` mais um `accessToken` pré-gerado ou OAuth `clientId` + `clientSecret` + `siteId`. O actor acessa apenas a *sua* conta Rakuten.

**P: Onde obtenho o Security Token?**
R: No Painel do Publisher Rakuten em **Support → Manage Tokens → Security Token**, ou em `https://publisher.rakutenadvertising.com/api-links/tokens`.

**P: Onde obtenho credenciais OAuth ou um Developer Access Token?**
R: No Rakuten Developer Portal em `https://developers.rakutenadvertising.com/`, na seção **Applications**.

**P: Token Bearer vs OAuth — qual usar?**
R: Se você já tem um Developer Access Token pré-gerado, cole-o em `accessToken`. Caso contrário, forneça `clientId` + `clientSecret` + `siteId` e o actor executará o fluxo OAuth `client_credentials` e obterá um token Bearer automaticamente. Tokens pré-gerados costumam expirar (~24h), então o OAuth é mais conveniente para execuções agendadas.

**P: Qual intervalo de datas é usado se eu deixar as datas em branco?**
R: Os últimos **90 dias** — `endDate` assume hoje e `startDate` assume 90 dias atrás. Forneça `startDate` / `endDate` em `YYYYMMDD` para sobrescrever.

**P: Por que minha execução retornou zero registros?**
R: Causas comuns: nenhuma transação no intervalo de datas, `securityToken` ou `accessToken` expirado, ou conta ainda não aprovada para a Advanced Reports API. O actor retorna um Guia de Configuração com passos de correção e salva a resposta bruta na chave `debug-raw-response` do Key-Value Store.

**P: Quais colunas vou receber?**
R: Depende do relatório. As colunas de saída são dinâmicas e vêm diretamente do cabeçalho CSV que o Rakuten retorna para o `reportId` selecionado. Relatórios v2 normalmente incluem mais colunas que os v1.

### 💰 Preços

Este actor usa precificação **Pay Per Event (PPE)** com um único evento:

| Evento | Quando dispara |
|---|---|
| `record-scraped` | Uma vez por registro do relatório (linha do CSV) enviado ao dataset |

Execuções de diagnóstico (credenciais ausentes, tokens expirados, intervalo de datas vazio) **não** cobram nenhum evento. Execuções internas do dono são puladas da cobrança.

Para o preço por evento atual, consulte a página do actor: **https://apify.com/viralanalyzer/rakuten-marketing-publisher-stats**

### 🔗 Actors Relacionados

- [Awin Multi-Merchant Affiliate](https://apify.com/viralanalyzer/awin-multi-merchant-affiliate) — Descoberta de anunciantes & links de rastreamento
- [Yahoo Finance Intelligence](https://apify.com/viralanalyzer/yahoo-finance-intelligence) — Cotações, fundamentos & ratings de analistas
- [TradingView Screener](https://apify.com/viralanalyzer/tradingview-screener) — Análise técnica & scanner de mercado
- [Amazon Brazil Intelligence](https://apify.com/viralanalyzer/amazon-brazil-intelligence) — Inteligência de produtos & preços

### 📝 Changelog

#### v1.0 (Atual)

- ✅ Integração com a API oficial Rakuten Advertising Advanced Reports
- ✅ 5 tipos de relatório (Resumo de Pagamentos, Pagamentos de Anunciantes v1/v2, Detalhes de Pagamento v1/v2)
- ✅ Dois modos de autenticação: token Bearer pré-gerado ou OAuth `client_credentials`
- ✅ Janela de datas `YYYYMMDD` configurável (padrão: últimos 90 dias)
- ✅ CSV → JSON estruturado com colunas dinâmicas + conversão numérica
- ✅ Campos de contexto da execução (`reportId`, `bdate`, `edate`, `scrapedAt`) em cada registro
- ✅ Guia de Configuração autodiagnóstico para erros recuperáveis (nunca falha silenciosa)
- ✅ Inputs secretos BYOC + cobrança PPE com owner-skip (`record-scraped`)
  </content>

# Actor input Schema

## `securityToken` (type: `string`):

Retrieved from your Publisher Dashboard under Support > Manage Tokens > Security Token. This token is required by Rakuten Advanced Reports.

## `reportId` (type: `string`):

Which advanced financial report to fetch. v2 reports contain additional fields compared to v1.

## `accessToken` (type: `string`):

Optional pre-generated Bearer Token from the Developer Portal. If left blank, you must provide clientId, clientSecret, and siteId to auto-generate the token.

## `clientId` (type: `string`):

Client ID from the Rakuten Developer Portal. Required if Developer Access Token is not provided.

## `clientSecret` (type: `string`):

Client Secret from the Rakuten Developer Portal. Required if Developer Access Token is not provided.

## `siteId` (type: `string`):

Your numeric Publisher Site ID (7-digit number). Required if Developer Access Token is not provided.

## `startDate` (type: `string`):

Start date for report data. Example: 20260401. If blank, defaults to 90 days ago.

## `endDate` (type: `string`):

End date for report data. Example: 20260525. If blank, defaults to today.

## `proxyConfiguration` (type: `object`):

Apify Proxy configuration.

## Actor input object example

```json
{
  "reportId": "22",
  "proxyConfiguration": {
    "useApifyProxy": true
  }
}
```

# Actor output Schema

## `results` (type: `string`):

All records as a dataset (JSON/CSV/Excel).

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "reportId": "22"
};

// Run the Actor and wait for it to finish
const run = await client.actor("viralanalyzer/rakuten-marketing-publisher-stats").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = { "reportId": "22" }

# Run the Actor and wait for it to finish
run = client.actor("viralanalyzer/rakuten-marketing-publisher-stats").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "reportId": "22"
}' |
apify call viralanalyzer/rakuten-marketing-publisher-stats --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=viralanalyzer/rakuten-marketing-publisher-stats",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Rakuten Advertising Publisher Reports (BYOC)",
        "description": "Retrieve Rakuten Advertising publisher advanced reports via the official API (BYOC): commissions, advertiser payments, performance metrics and payout data.",
        "version": "1.0",
        "x-build-id": "viQcpO8ffvwlfy8y4"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/viralanalyzer~rakuten-marketing-publisher-stats/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-viralanalyzer-rakuten-marketing-publisher-stats",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/viralanalyzer~rakuten-marketing-publisher-stats/runs": {
            "post": {
                "operationId": "runs-sync-viralanalyzer-rakuten-marketing-publisher-stats",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/viralanalyzer~rakuten-marketing-publisher-stats/run-sync": {
            "post": {
                "operationId": "run-sync-viralanalyzer-rakuten-marketing-publisher-stats",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "reportId"
                ],
                "properties": {
                    "securityToken": {
                        "title": "Web Service Security Token",
                        "type": "string",
                        "description": "Retrieved from your Publisher Dashboard under Support > Manage Tokens > Security Token. This token is required by Rakuten Advanced Reports."
                    },
                    "reportId": {
                        "title": "Report Type",
                        "enum": [
                            "1",
                            "2",
                            "22",
                            "3",
                            "23"
                        ],
                        "type": "string",
                        "description": "Which advanced financial report to fetch. v2 reports contain additional fields compared to v1.",
                        "default": "22"
                    },
                    "accessToken": {
                        "title": "Developer Access Token (Optional JWT)",
                        "type": "string",
                        "description": "Optional pre-generated Bearer Token from the Developer Portal. If left blank, you must provide clientId, clientSecret, and siteId to auto-generate the token."
                    },
                    "clientId": {
                        "title": "OAuth Client ID",
                        "type": "string",
                        "description": "Client ID from the Rakuten Developer Portal. Required if Developer Access Token is not provided."
                    },
                    "clientSecret": {
                        "title": "OAuth Client Secret",
                        "type": "string",
                        "description": "Client Secret from the Rakuten Developer Portal. Required if Developer Access Token is not provided."
                    },
                    "siteId": {
                        "title": "Publisher Site ID",
                        "type": "string",
                        "description": "Your numeric Publisher Site ID (7-digit number). Required if Developer Access Token is not provided."
                    },
                    "startDate": {
                        "title": "Start Date (YYYYMMDD)",
                        "type": "string",
                        "description": "Start date for report data. Example: 20260401. If blank, defaults to 90 days ago."
                    },
                    "endDate": {
                        "title": "End Date (YYYYMMDD)",
                        "type": "string",
                        "description": "End date for report data. Example: 20260525. If blank, defaults to today."
                    },
                    "proxyConfiguration": {
                        "title": "Proxy Configuration",
                        "type": "object",
                        "description": "Apify Proxy configuration.",
                        "default": {
                            "useApifyProxy": true
                        }
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
