# Shopee Affiliate Products Finder (`viralanalyzer/shopee-affiliate-products`) Actor

Discover viral Shopee products with commission rates and generate trackable short links (subIds) via the official Shopee Affiliate Open API (GraphQL + HMAC-SHA256).

- **URL**: https://apify.com/viralanalyzer/shopee-affiliate-products.md
- **Developed by:** [viralanalyzer](https://apify.com/viralanalyzer) (community)
- **Categories:** E-commerce, SEO tools, Lead generation
- **Stats:** 1 total users, 1 monthly users, 0.0% runs succeeded, NaN bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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

## 🛒 Shopee Affiliate Open API — Multi-Mode Discovery (BR)

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

Pull **Shopee Brazil affiliate data** straight from the official **Shopee Affiliate Open Platform GraphQL API**. Discover products, shops, and campaigns; pull your conversion reports; download bulk catalog feeds; and generate trackable short links with sub-IDs — all from a single actor in 5 operation modes. Built for performance-marketing pipelines with real commission data, not scraped prices.

### ✨ Features

- 🎯 **5 operation modes** — `products` · `shops` · `campaigns` · `conversions` · `feeds` (pick one per run)
- 💸 **Real commission rates** — `commissionRate`, `commission` (BRL), `sellerCommissionRate`, `shopeeCommissionRate` straight from Open API
- 🔗 **Trackable short links** — Optional `subIdsTemplate` triggers `generateBatchShortLink` to create attribution-ready links (max 5 sub-IDs per link with tokens like `{{date}}`, `{{shopId}}`, `{{itemId}}`, `{{keyword}}`)
- 📊 **Conversion reporting** — Pull your own affiliate sales (`conversionReport` query) for DW / analytics pipelines
- 📦 **Bulk catalog feeds** — `listItemFeeds` returns full Shopee data feeds (FULL / DELTA) instead of paginating product-by-product
- 🏪 **Shop discovery with differentiated commission** — `shopOfferV2` finds shops paying above-baseline rates
- 🛡️ **HMAC-SHA256 signature** — Pure HTTP + official auth, no scraping, no anti-bot games
- 🔒 **Secret credential handling** — `appSecret` stored encrypted via Apify input-secret
- 🇧🇷 **Brazil-native** — Endpoint `open-api.affiliate.shopee.com.br/graphql` (BR catalog, BRL pricing)

### ⚙️ Requirements

You need a **Shopee Affiliate Open Platform account** with API credentials:

1. Apply for the affiliate program at [affiliate.shopee.com.br](https://affiliate.shopee.com.br) (manual review, ~5-15 days)
2. After approval, open the **Open API** section in your affiliate dashboard
3. Copy **App ID** (numeric) and **App Secret** (long string)
4. Paste into the actor input (`appId` + `appSecret`)

### 📥 Input

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `appId` | string | ✅ | — | Shopee Affiliate App ID |
| `appSecret` | string (secret) | ✅ | — | Shopee Affiliate App Secret (encrypted) |
| `mode` | enum | ✅ | `products` | `products` · `shops` · `campaigns` · `conversions` · `feeds` |
| `keywords` | string[] | conditional | — | Required for `products` and `shops` modes. 1-20 terms. |
| `maxResults` | integer | ❌ | `50` | Cap on entities returned (1-500). Each = 1 PPE event. |
| `sortType` | integer | ❌ | `5` | `1`=Relevance · `2`=Sales · `3`=Price High→Low · `4`=Price Low→High · `5`=Commission High→Low |
| `minSales` | integer | ❌ | `0` | Client-side: drop products with fewer sales (mode=products only) |
| `minRating` | number | ❌ | `0` | Client-side: drop products below this rating (0-5) |
| `minCommissionRate` | number | ❌ | `0` | Client-side: drop entities below this commission % |
| `subIdsTemplate` | string[] | ❌ | `[]` | Up to 5 templates. Non-empty triggers `generateBatchShortLink`. Tokens: `{{date}}`, `{{shopId}}`, `{{itemId}}`, `{{keyword}}` |
| `conversionTimeRangeDays` | integer | ❌ | `30` | Look-back window for `mode=conversions` (1-90) |
| `feedMode` | string | ❌ | `""` | `FULL` or `DELTA` for `mode=feeds`; empty lists all available feeds |
| `proxyConfiguration` | object | ❌ | none | Open API doesn't require proxy; enable only if Apify IP gets rate-limited (error 10030) |

#### Input examples

**Mode `products` (most common):**
```json
{
  "appId": "18384911047",
  "appSecret": "<your-secret>",
  "mode": "products",
  "keywords": ["fone bluetooth", "tênis casual"],
  "maxResults": 50,
  "sortType": 5,
  "minCommissionRate": 5,
  "subIdsTemplate": ["viral", "tiktok", "{{date}}", "{{shopId}}", "{{itemId}}"]
}
````

**Mode `conversions` (pull your sales report):**

```json
{
  "appId": "18384911047",
  "appSecret": "<your-secret>",
  "mode": "conversions",
  "conversionTimeRangeDays": 30,
  "maxResults": 500
}
```

**Mode `feeds` (bulk catalogs):**

```json
{
  "appId": "18384911047",
  "appSecret": "<your-secret>",
  "mode": "feeds",
  "feedMode": "FULL"
}
```

### 📤 Output

Every record has a unified schema with `_entityType` discriminating the mode (`product` · `shop` · `campaign` · `conversion` · `feedItem`).

Core fields (always present when applicable):

| Field | Type | Description |
|---|---|---|
| `_entityType` | string | `product` / `shop` / `campaign` / `conversion` / `feedItem` |
| `itemId` / `shopId` | number | Shopee IDs |
| `name` | string | Product / shop / campaign name |
| `url` | string | Canonical Shopee URL |
| `offerLink` | string | Long affiliate link with built-in tracking (returned by Open API) |
| `shortLink` | string | Shortlink from `generateBatchShortLink` (when `subIdsTemplate` is set) |
| `price` / `priceMin` / `priceMax` | number | BRL |
| `discountPct` | number | 0-100 |
| `sales` | number | Total historical sales |
| `rating` | number | 0-5 |
| `commissionRate` | number | Affiliate commission rate (decimal, 0.05 = 5%) |
| `commission` | number | Estimated commission in BRL (price × commissionRate) |
| `sellerCommissionRate` / `shopeeCommissionRate` | number | Breakdown of who pays what |
| `shopName` / `shopType` / `isOfficialShop` | mixed | Seller info (`shopType: 1`=Mall, `2`=Star) |
| `periodStartTime` / `periodEndTime` | string | ISO 8601 — offer validity window |
| `categoryIds` | number\[] | Shopee category hierarchy |
| `discoveredVia` | string | The keyword (or feed name) that surfaced this entity |
| `_dataQuality` | string | `full` or `partial` |
| `scrapedAt` | string | ISO 8601 fetch timestamp |

**Mode `conversions` adds:** `conversionId`, `purchaseTime`, `orderStatus`, `totalCommission`, `device`, `utmContent`, `attributionType`.

#### Output example (mode=products)

```json
{
  "itemId": 23398164028,
  "shopId": 933390061,
  "name": "Fone De Ouvido Bluetooth TWS Pro 6",
  "url": "https://shopee.com.br/product/933390061/23398164028",
  "imageUrl": "https://cf.shopee.com.br/file/br-...",
  "offerLink": "https://s.shopee.com.br/2qRLhfwL03",
  "shortLink": "https://s.shopee.com.br/2abc...",
  "price": 49.99,
  "priceMin": 49.99,
  "priceMax": 53.99,
  "discountPct": 37,
  "currency": "BRL",
  "sales": 272,
  "rating": 5.0,
  "shopName": "RK_IMPORTS",
  "shopType": 2,
  "isOfficialShop": false,
  "_entityType": "product",
  "commissionRate": 0.38,
  "commission": 18.99,
  "sellerCommissionRate": 0.35,
  "shopeeCommissionRate": 0.03,
  "periodStartTime": "2026-04-27T03:00:00+00:00",
  "periodEndTime": "2026-06-01T02:59:59+00:00",
  "discoveredVia": "fone bluetooth",
  "platform": "shopee_br",
  "_dataQuality": "full",
  "scrapedAt": "2026-05-12T14:10:38.584Z"
}
```

### 📋 Use cases

- 🤝 **Affiliate marketing** — Find high-commission products, generate tracked links, ship to TikTok/Instagram/YouTube
- 📊 **Attribution analytics** — Pull `conversionReport` into your DW; close the loop on which sub-ID generated revenue
- 📈 **Trend detection** — Filter by `sortType=2` (sales) + `minCommissionRate` to find products you can actually profit from
- 🛍️ **Catalog enrichment** — `feeds` mode delivers Shopee's full catalog with commission rates pre-computed
- 🏪 **Shop research** — `shops` mode surfaces sellers offering differentiated commission (key sellers)

### ❓ FAQ

**Q: Do I need Shopee Affiliate API credentials?**
A: **Yes.** Unlike scraping actors, this one uses the official Open Platform. Apply at [affiliate.shopee.com.br](https://affiliate.shopee.com.br) → wait for approval → grab App ID + App Secret from the Open API panel.

**Q: How is the signature computed?**
A: `SHA256(appId + timestamp + payload + secret)`. Header format: `Authorization: SHA256 Credential={appId}, Timestamp={ts}, Signature={sig}`. Timestamp is Unix seconds (not ms); window is ~5 minutes.

**Q: What's the difference between `offerLink` and `shortLink`?**
A: `offerLink` is the long pre-tracked URL returned by Open API automatically. `shortLink` is a shortened version generated via `generateBatchShortLink` — only when you provide `subIdsTemplate`. Use sub-IDs to track which channel/creative drove each conversion.

**Q: Why are numeric fields returned as decimals (e.g., `commissionRate: 0.38`)?**
A: That's how Open API encodes them. `0.38` = 38% commission. Our actor parses the API's `String!` representation into `float` for you.

**Q: What does error code 10030 mean?**
A: Shopee Open API rate limit. The actor implements exponential backoff (up to 3 retries). If it persists, enable Apify Proxy (datacenter US) to rotate IP.

**Q: Can I run all 5 modes in one run?**
A: No. Each run = one mode (it determines the PPE event charged). To pull products + conversions, run the actor twice with different `mode` values.

**Q: Does this actor scrape Shopee?**
A: **No.** Pure REST/GraphQL via the official Open Platform. No browsers, no fingerprinting, no anti-bot games. Just signed HTTP calls.

### 💰 Pricing

This actor uses **Pay Per Event (PPE)** pricing across 6 event types and 6 plan tiers:

| Event (mode) | FREE | BRONZE | SILVER | GOLD | PLATINUM | DIAMOND |
|---|---|---|---|---|---|---|
| `product-discovered` (products) | $0.0009 | $0.0008 | $0.0007 | $0.0005 | $0.0003 | $0.0002 |
| `shop-discovered` (shops) | $0.0012 | $0.0010 | $0.0008 | $0.0007 | $0.0004 | $0.0002 |
| `campaign-discovered` (campaigns) | $0.0014 | $0.0012 | $0.0010 | $0.0008 | $0.0005 | $0.0003 |
| `conversion-pulled` (conversions) | $0.0023 | $0.0020 | $0.0017 | $0.0013 | $0.0008 | $0.0004 |
| `feed-item-discovered` (feeds) | $0.0007 | $0.0006 | $0.0005 | $0.0004 | $0.0002 | $0.0001 |
| `short-link-generated` (add-on) | $0.0018 | $0.0015 | $0.0012 | $0.0010 | $0.0006 | $0.0003 |

**Example:** A BRONZE-plan user running `mode=products` with `maxResults=100` and `subIdsTemplate` set pays roughly `100 × $0.0008 + 100 × $0.0015 = $0.23` for a full discovery + attribution batch.

### 🔗 Related actors

- [AliExpress Product Discovery](https://apify.com/viralanalyzer/aliexpress-affiliate-products) — Cross-border sourcing via Dropshipping API
- [Awin Multi-Merchant Affiliate](https://apify.com/viralanalyzer/awin-multi-merchant-affiliate) — Hundreds of BR + global brands via Awin Publisher REST
- [Mercado Livre Scraper](https://apify.com/viralanalyzer/mercadolivre-scraper) — ML BR products
- [Amazon Brazil Intelligence](https://apify.com/viralanalyzer/amazon-brazil-intelligence) — Amazon BR product data
- [TikTok Viral Scanner](https://apify.com/viralanalyzer/tiktok-viral-scanner) — Validate trends before promoting

### 📝 Changelog

#### v4.0 (Current, 2026-05-12)

- **Migrated to Shopee Affiliate Open Platform (official GraphQL API)** — no more scraping
- HMAC-SHA256 signature authentication
- 5 operation modes via `mode` input: products / shops / campaigns / conversions / feeds
- 6 PPE events with 6-tier pricing (FREE → DIAMOND)
- `generateBatchShortLink` integration with sub-ID templating
- Anti-hallucination guardrails (BANNED\_PATTERNS) + zero-NULL contract preserved
- Owner-skip for internal ViralAnalyzer runs

#### v3.0 (Legacy, deprecated)

- Curl-cffi scraping of frontend API v4 — blocked by anti-bot

***

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

## 🛒 Shopee Affiliate Open API — Descoberta Multi-Modo (BR)

> 🔗 [Ver na Apify Store](https://apify.com/viralanalyzer/shopee-affiliate-products) | [🇺🇸 English](#-shopee-affiliate-open-api--multi-mode-discovery-br) | 🇧🇷 Português

Extraia dados de afiliado da **Shopee Brasil** diretamente da **API oficial GraphQL do Open Platform**. Descubra produtos, lojas e campanhas; puxe relatórios de conversão; baixe data feeds em bulk; e gere shortlinks rastreáveis com sub-IDs — tudo em um único actor com 5 modos de operação. Pensado para pipelines de marketing de performance com **comissão real**, não preço scrapado.

### ✨ Funcionalidades

- 🎯 **5 modos de operação** — `products` · `shops` · `campaigns` · `conversions` · `feeds`
- 💸 **Taxas de comissão reais** — `commissionRate`, `commission` (BRL), comissão do vendedor + subsídio Shopee
- 🔗 **Shortlinks rastreáveis** — Opcional via `subIdsTemplate` (até 5 sub-IDs com tokens `{{date}}`, `{{shopId}}`, `{{itemId}}`, `{{keyword}}`)
- 📊 **Relatório de conversão** — `conversionReport` para fechar o loop de atribuição no DW
- 📦 **Data feeds bulk** — `listItemFeeds` traz o catálogo Shopee inteiro
- 🛡️ **Assinatura HMAC-SHA256** — HTTP puro + auth oficial, sem scraping
- 🔒 **Segredos criptografados** — `appSecret` via Apify input-secret
- 🇧🇷 **Nativo do Brasil** — Endpoint `open-api.affiliate.shopee.com.br/graphql`

### ⚙️ Requisitos

Você precisa de uma conta no **Shopee Affiliate Open Platform**:

1. Solicite no [affiliate.shopee.com.br](https://affiliate.shopee.com.br) (revisão manual, ~5-15 dias)
2. Após aprovado, abra a aba **Open API** no seu dashboard
3. Copie **App ID** (numérico) e **App Secret** (string longa)
4. Cole no input do actor (`appId` + `appSecret`)

### 📥 Entrada (campos principais)

Veja tabela completa em inglês acima. Campos obrigatórios: `appId`, `appSecret`, `mode`. Os modos `products` e `shops` exigem `keywords`. Os modos `conversions` e `feeds` ignoram `keywords`.

#### Exemplo (mode=products):

```json
{
  "appId": "18384911047",
  "appSecret": "<seu-secret>",
  "mode": "products",
  "keywords": ["fone bluetooth", "tênis casual"],
  "maxResults": 50,
  "sortType": 5,
  "minCommissionRate": 5,
  "subIdsTemplate": ["viral", "tiktok", "{{date}}", "{{shopId}}", "{{itemId}}"]
}
```

### 📤 Saída

Schema unificado com discriminador `_entityType` (`product` / `shop` / `campaign` / `conversion` / `feedItem`). Veja tabela completa em inglês. Campos-chave: `itemId`, `shopId`, `name`, `offerLink`, `shortLink`, `commissionRate`, `commission`, `sales`, `rating`, `discountPct`, `periodStartTime/End`.

### 📋 Casos de uso

- 🤝 **Marketing de afiliados** — Achar produtos de alta comissão + gerar links rastreáveis + distribuir em TikTok/Instagram
- 📊 **Atribuição** — `conversionReport` no seu DW; saber qual sub-ID gerou receita
- 📈 **Detecção de tendência** — Filtrar por `sortType=2` (vendas) + `minCommissionRate` para achar produtos lucrativos
- 🛍️ **Enriquecimento de catálogo** — `feeds` traz catálogo completo com comissão pré-calculada
- 🏪 **Pesquisa de lojas** — `shops` revela vendedores com comissão diferenciada

### ❓ Perguntas Frequentes

**P: Preciso de credenciais Open API da Shopee?**
R: **Sim.** Diferente de actors de scraping, este usa Open Platform oficial. Solicite em affiliate.shopee.com.br → aguarde aprovação → pegue App ID + Secret.

**P: Como é a assinatura?**
R: `SHA256(appId + timestamp + payload + secret)`. Header: `Authorization: SHA256 Credential={appId}, Timestamp={ts}, Signature={sig}`. Timestamp em segundos Unix (não ms); janela ~5 min.

**P: Diferença entre `offerLink` e `shortLink`?**
R: `offerLink` é o link longo já com tracking, retornado pela API. `shortLink` é gerado via `generateBatchShortLink` apenas se você passar `subIdsTemplate`. Use sub-IDs para rastrear canal/criativo.

**P: Por que `commissionRate: 0.38` em vez de `38`?**
R: É como a Open API codifica. `0.38` = 38% de comissão. Convertemos a String! da API para float automaticamente.

**P: O que é o erro 10030?**
R: Rate limit da Shopee. O actor faz backoff exponencial (3 retries). Se persistir, ative Apify Proxy (datacenter US).

**P: Posso rodar 5 modos numa execução?**
R: Não. Cada run = um modo (define o evento PPE cobrado). Rode 2x se quiser produtos + conversões.

**P: Este actor faz scraping da Shopee?**
R: **Não.** REST/GraphQL puro via Open Platform. Sem browser, sem fingerprint, sem anti-bot. Só HTTP assinado.

### 💰 Preços

Veja tabela completa em inglês. PPE em 6 eventos × 6 tiers (FREE → DIAMOND). Exemplo BRONZE: rodar `mode=products` com `maxResults=100` + shortlinks custa ~`$0.23` (100 × $0.0008 produto + 100 × $0.0015 shortlink).

### 🔗 Actors Relacionados

- [AliExpress Product Discovery](https://apify.com/viralanalyzer/aliexpress-affiliate-products)
- [Awin Multi-Merchant Affiliate](https://apify.com/viralanalyzer/awin-multi-merchant-affiliate)
- [Mercado Livre Scraper](https://apify.com/viralanalyzer/mercadolivre-scraper)
- [Amazon Brazil Intelligence](https://apify.com/viralanalyzer/amazon-brazil-intelligence)
- [TikTok Viral Scanner](https://apify.com/viralanalyzer/tiktok-viral-scanner)

### 📝 Changelog

#### v4.0 (Atual, 2026-05-12)

- **Migrado para Shopee Affiliate Open Platform (GraphQL oficial)** — fim do scraping
- Assinatura HMAC-SHA256
- 5 modos via input `mode`: products / shops / campaigns / conversions / feeds
- 6 eventos PPE × 6 tiers (FREE → DIAMOND)
- `generateBatchShortLink` integrado com template de sub-IDs
- Guardrails anti-placeholder + zero-NULL contract preservados
- Owner-skip para runs internos ViralAnalyzer

#### v3.0 (Legacy, descontinuado)

- Scraping da API v4 via curl-cffi — bloqueado por anti-bot

# Actor input Schema

## `appId` (type: `string`):

Numeric ID from Shopee Affiliate Open Platform (Open API section in your affiliate dashboard at affiliate.shopee.com.br).

## `appSecret` (type: `string`):

Secret key from Shopee Affiliate Open Platform. Stored encrypted by Apify.

## `mode` (type: `string`):

products = productOfferV2 | shops = shopOfferV2 | campaigns = shopeeOfferV2 | conversions = conversionReport | feeds = listItemFeeds + getItemFeedData

## `keywords` (type: `array`):

Product/shop search terms. Ignored for mode=campaigns | conversions | feeds. Each keyword runs a separate query; results deduplicated by entity ID.

## `maxResults` (type: `integer`):

Open API page limit is 500. We paginate until reaching this total. Each entity = 1 PPE event.

## `sortType` (type: `integer`):

Open API enum: 1=Relevance, 2=Sales, 3=High Price (Desc), 4=Low Price (Asc), 5=Commission High→Low (recommended for affiliates).

## `minSales` (type: `integer`):

Drop products with fewer historical sales. Use 0 for no filter. mode=products only.

## `minRating` (type: `number`):

Drop products with average rating below this (0-5). mode=products only.

## `minCommissionRate` (type: `number`):

Drop products/shops with affiliate commission below this %. Use 0 for no filter. mode=products | shops.

## `subIdsTemplate` (type: `array`):

Optional. If non-empty, calls generateBatchShortLink for each discovered product. Max 5 subIds. Supported tokens: {{date}}, {{shopId}}, {{itemId}}, {{keyword}}. Empty array = skip shortlinks. Each generated shortlink = 1 additional PPE 'short-link-generated' event.

## `conversionTimeRangeDays` (type: `integer`):

Look back N days for conversionReport. purchaseTimeStart = now - N days.

## `feedMode` (type: `string`):

Specific feedMode enum value for listItemFeeds. Leave empty to list available feeds first.

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

Shopee Open API doesn't require proxy. Only enable if Apify IP gets rate-limited (error code 10030).

## Actor input object example

```json
{
  "mode": "products",
  "keywords": [
    "fone bluetooth",
    "tênis casual"
  ],
  "maxResults": 50,
  "sortType": 5,
  "minSales": 0,
  "minRating": 0,
  "minCommissionRate": 0,
  "subIdsTemplate": [],
  "conversionTimeRangeDays": 30,
  "feedMode": "",
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

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

Dataset containing all scraped Shopee products. Each item follows the dataset schema.

# 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 = {
    "keywords": [
        "fone bluetooth",
        "tênis casual"
    ],
    "subIdsTemplate": []
};

// Run the Actor and wait for it to finish
const run = await client.actor("viralanalyzer/shopee-affiliate-products").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 = {
    "keywords": [
        "fone bluetooth",
        "tênis casual",
    ],
    "subIdsTemplate": [],
}

# Run the Actor and wait for it to finish
run = client.actor("viralanalyzer/shopee-affiliate-products").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 '{
  "keywords": [
    "fone bluetooth",
    "tênis casual"
  ],
  "subIdsTemplate": []
}' |
apify call viralanalyzer/shopee-affiliate-products --silent --output-dataset

```

## MCP server setup

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

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Shopee Affiliate Products Finder",
        "description": "Discover viral Shopee products with commission rates and generate trackable short links (subIds) via the official Shopee Affiliate Open API (GraphQL + HMAC-SHA256).",
        "version": "4.0",
        "x-build-id": "H3Da67Vpshzwdsk5F"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/viralanalyzer~shopee-affiliate-products/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-viralanalyzer-shopee-affiliate-products",
                "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~shopee-affiliate-products/runs": {
            "post": {
                "operationId": "runs-sync-viralanalyzer-shopee-affiliate-products",
                "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~shopee-affiliate-products/run-sync": {
            "post": {
                "operationId": "run-sync-viralanalyzer-shopee-affiliate-products",
                "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": [
                    "appId",
                    "appSecret",
                    "mode"
                ],
                "properties": {
                    "appId": {
                        "title": "Shopee Open API — App ID",
                        "minLength": 5,
                        "type": "string",
                        "description": "Numeric ID from Shopee Affiliate Open Platform (Open API section in your affiliate dashboard at affiliate.shopee.com.br)."
                    },
                    "appSecret": {
                        "title": "Shopee Open API — App Secret",
                        "type": "string",
                        "description": "Secret key from Shopee Affiliate Open Platform. Stored encrypted by Apify."
                    },
                    "mode": {
                        "title": "Operation Mode",
                        "enum": [
                            "products",
                            "shops",
                            "campaigns",
                            "conversions",
                            "feeds"
                        ],
                        "type": "string",
                        "description": "products = productOfferV2 | shops = shopOfferV2 | campaigns = shopeeOfferV2 | conversions = conversionReport | feeds = listItemFeeds + getItemFeedData",
                        "default": "products"
                    },
                    "keywords": {
                        "title": "Search Keywords (mode=products | shops)",
                        "minItems": 0,
                        "maxItems": 20,
                        "type": "array",
                        "description": "Product/shop search terms. Ignored for mode=campaigns | conversions | feeds. Each keyword runs a separate query; results deduplicated by entity ID.",
                        "items": {
                            "type": "string"
                        }
                    },
                    "maxResults": {
                        "title": "Max Results per Run (or per keyword for products/shops)",
                        "minimum": 1,
                        "maximum": 500,
                        "type": "integer",
                        "description": "Open API page limit is 500. We paginate until reaching this total. Each entity = 1 PPE event.",
                        "default": 50
                    },
                    "sortType": {
                        "title": "Sort Order (mode=products | shops | campaigns)",
                        "minimum": 1,
                        "maximum": 5,
                        "type": "integer",
                        "description": "Open API enum: 1=Relevance, 2=Sales, 3=High Price (Desc), 4=Low Price (Asc), 5=Commission High→Low (recommended for affiliates).",
                        "default": 5
                    },
                    "minSales": {
                        "title": "Minimum Sales (client-side filter)",
                        "minimum": 0,
                        "type": "integer",
                        "description": "Drop products with fewer historical sales. Use 0 for no filter. mode=products only.",
                        "default": 0
                    },
                    "minRating": {
                        "title": "Minimum Rating (client-side filter)",
                        "minimum": 0,
                        "maximum": 5,
                        "type": "number",
                        "description": "Drop products with average rating below this (0-5). mode=products only.",
                        "default": 0
                    },
                    "minCommissionRate": {
                        "title": "Minimum Commission Rate %",
                        "minimum": 0,
                        "maximum": 100,
                        "type": "number",
                        "description": "Drop products/shops with affiliate commission below this %. Use 0 for no filter. mode=products | shops.",
                        "default": 0
                    },
                    "subIdsTemplate": {
                        "title": "Sub-IDs Template (shortlink attribution)",
                        "maxItems": 5,
                        "type": "array",
                        "description": "Optional. If non-empty, calls generateBatchShortLink for each discovered product. Max 5 subIds. Supported tokens: {{date}}, {{shopId}}, {{itemId}}, {{keyword}}. Empty array = skip shortlinks. Each generated shortlink = 1 additional PPE 'short-link-generated' event.",
                        "items": {
                            "type": "string"
                        }
                    },
                    "conversionTimeRangeDays": {
                        "title": "Conversion Time Window (days, mode=conversions only)",
                        "minimum": 1,
                        "maximum": 90,
                        "type": "integer",
                        "description": "Look back N days for conversionReport. purchaseTimeStart = now - N days.",
                        "default": 30
                    },
                    "feedMode": {
                        "title": "Feed Mode (mode=feeds only)",
                        "type": "string",
                        "description": "Specific feedMode enum value for listItemFeeds. Leave empty to list available feeds first.",
                        "default": ""
                    },
                    "proxyConfiguration": {
                        "title": "Proxy Configuration (advanced, usually unnecessary)",
                        "type": "object",
                        "description": "Shopee Open API doesn't require proxy. Only enable if Apify IP gets rate-limited (error code 10030).",
                        "default": {
                            "useApifyProxy": false
                        }
                    }
                }
            },
            "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
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
