Pirsch Integrations | OpsBlu Docs

Pirsch Integrations

Connect Pirsch with third-party tools — CRM, marketing, CMS, and data warehouse integration guides.

Pirsch offers flexible integration options for connecting analytics data to your broader tech stack. This guide covers API access, webhooks, SDKs, third-party platform connections, and self-hosting configurations.

API Integration

Authentication

Pirsch API uses OAuth 2.0 client credentials for authentication.

Generate API Credentials:

  1. Navigate to Settings → Integrations in your Pirsch dashboard
  2. Click "Create API Client"
  3. Copy your Client ID and Client Secret
  4. Store credentials securely (they're shown only once)

Obtain Access Token:

curl -X POST "https://api.pirsch.io/api/v1/token" \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "YOUR_CLIENT_ID",
    "client_secret": "YOUR_CLIENT_SECRET"
  }'

Response:

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expires_in": 3600,
  "token_type": "Bearer"
}

Statistics Endpoints

Retrieve Page Views:

curl "https://api.pirsch.io/api/v1/statistics/page" \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "YOUR_DOMAIN_ID",
    "from": "2024-01-01",
    "to": "2024-01-31"
  }'

Get Visitor Metrics:

curl "https://api.pirsch.io/api/v1/statistics/visitor" \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "YOUR_DOMAIN_ID",
    "from": "2024-01-01",
    "to": "2024-01-31",
    "scale": "day"
  }'

Query Event Data:

curl "https://api.pirsch.io/api/v1/statistics/events" \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "YOUR_DOMAIN_ID",
    "from": "2024-01-01",
    "to": "2024-01-31",
    "event_name": "button_click"
  }'

Available Parameters:

  • id - Domain identifier (required)
  • from - Start date (YYYY-MM-DD)
  • to - End date (YYYY-MM-DD)
  • scale - Time grouping: day, week, month, year
  • path - Filter by URL path
  • event_name - Filter by event name
  • pattern - Path pattern matching
  • utm_source, utm_medium, utm_campaign - UTM parameter filters

Real-Time Data

Active Visitors:

curl "https://api.pirsch.io/api/v1/statistics/active" \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -d '{"id": "YOUR_DOMAIN_ID"}'

Returns currently active visitor count and active pages.

Export Data

Export Raw Events:

curl "https://api.pirsch.io/api/v1/export" \
  -H "Authorization: Bearer ACCESS_TOKEN" \
  -d '{
    "id": "YOUR_DOMAIN_ID",
    "from": "2024-01-01",
    "to": "2024-01-31",
    "format": "json"
  }' \
  -o export.json

Supported Export Formats:

Rate Limits

API Quotas:

  • Free Plan - 1,000 requests/month
  • Starter - 10,000 requests/month
  • Business - 100,000 requests/month
  • Enterprise - Custom limits

Rate Limit Headers:

X-RateLimit-Limit: 10000
X-RateLimit-Remaining: 9847
X-RateLimit-Reset: 1640995200

Webhooks

Configure webhooks to receive real-time notifications when specific events occur.

Webhook Configuration

Setup:

  1. Go to Settings → Integrations → Webhooks
  2. Click "Add Webhook"
  3. Enter your endpoint URL (must be HTTPS)
  4. Select events to subscribe to
  5. Optionally add a secret for signature validation
  6. Save configuration

Webhook Events:

  • pageview - New pageview recorded
  • event - Custom event tracked
  • session_start - New visitor session begins
  • session_end - Visitor session ends
  • goal_conversion - Goal completion

Webhook Payload

Example Payload:

{
  "event_type": "pageview",
  "timestamp": "2024-01-15T14:30:00Z",
  "domain": "example.com",
  "data": {
    "path": "/products/analytics",
    "referrer": "https://google.com/search",
    "utm_source": "google",
    "utm_medium": "organic",
    "country": "US",
    "device_type": "desktop",
    "browser": "Chrome",
    "os": "Windows"
  }
}

Signature Validation

Pirsch signs webhook payloads with HMAC-SHA256.

Verify Signature (Node.js):

const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const hmac = crypto.createHmac('sha256', secret);
  const digest = hmac.update(JSON.stringify(payload)).digest('hex');
  return signature === digest;
}

// In your webhook handler
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-pirsch-signature'];
  const isValid = verifyWebhook(req.body, signature, WEBHOOK_SECRET);

  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }

  // Process webhook
  res.status(200).send('OK');
});

Retry Behavior

  • Failed webhooks retry with exponential backoff
  • Maximum 5 retry attempts
  • Webhooks disabled after 10 consecutive failures
  • Re-enable in dashboard after fixing endpoint

SDKs & Libraries

Official SDKs

Go SDK:

import "github.com/pirsch-analytics/pirsch-go-sdk"

client := pirsch.NewClient("CLIENT_ID", "CLIENT_SECRET")
stats, err := client.GetPageStats(pirsch.Filter{
    DomainID: "YOUR_DOMAIN_ID",
    From:     time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC),
    To:       time.Date(2024, 1, 31, 0, 0, 0, 0, time.UTC),
})

JavaScript/Node.js SDK:

const Pirsch = require('pirsch-sdk');

const client = new Pirsch({
  clientId: 'CLIENT_ID',
  clientSecret: 'CLIENT_SECRET'
});

const stats = await client.statistics.pageViews({
  domainId: 'YOUR_DOMAIN_ID',
  from: '2024-01-01',
  to: '2024-01-31'
});

Python SDK:

from pirsch import PirschClient

client = PirschClient(
    client_id='CLIENT_ID',
    client_secret='CLIENT_SECRET'
)

stats = client.get_page_stats(
    domain_id='YOUR_DOMAIN_ID',
    from_date='2024-01-01',
    to_date='2024-01-31'
)

Community Libraries

PHP:

use Pirsch\Client;

$client = new Client('CLIENT_ID', 'CLIENT_SECRET');
$stats = $client->getPageViews([
    'id' => 'YOUR_DOMAIN_ID',
    'from' => '2024-01-01',
    'to' => '2024-01-31'
]);

Ruby:

require 'pirsch'

client = Pirsch::Client.new(
  client_id: 'CLIENT_ID',
  client_secret: 'CLIENT_SECRET'
)

stats = client.page_views(
  domain_id: 'YOUR_DOMAIN_ID',
  from: '2024-01-01',
  to: '2024-01-31'
)

Self-Hosting

Pirsch offers an open-source version for self-hosting complete control over data and infrastructure.

Installation

Docker Deployment:

docker run -d \
  --name pirsch \
  -p 8080:8080 \
  -e DATABASE_URL="postgres://user:pass@localhost/pirsch" \
  -e SECRET_KEY="your-secret-key" \
  pirsch/pirsch:latest

Docker Compose:

version: '3.8'
services:
  pirsch:
    image: pirsch/pirsch:latest
    ports:
      - "8080:8080"
    environment:
      DATABASE_URL: postgres://pirsch:password@db:5432/pirsch
      SECRET_KEY: ${SECRET_KEY}
    depends_on:
      - db

  db:
    image: postgres:14
    environment:
      POSTGRES_DB: pirsch
      POSTGRES_USER: pirsch
      POSTGRES_PASSWORD: password
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:

Binary Installation:

# Download latest release
wget https://github.com/pirsch-analytics/pirsch/releases/latest/download/pirsch-linux-amd64

# Make executable
chmod +x pirsch-linux-amd64

# Run with configuration
./pirsch-linux-amd64 \
  --database.url="postgres://user:pass@localhost/pirsch" \
  --server.port=8080

Configuration

Environment Variables:

  • DATABASE_URL - PostgreSQL connection string (required)
  • SECRET_KEY - Session encryption key (required)
  • SERVER_PORT - HTTP server port (default: 8080)
  • SERVER_HOST - Bind address (default: 0.0.0.0)
  • LOG_LEVEL - Logging verbosity: debug, info, warn, error
  • ENABLE_GEOLOCATION - GeoIP lookups (default: true)
  • GEOIP_DATABASE - Path to MaxMind GeoLite2 database

Configuration File (config.yml):

database:
  url: postgres://pirsch:password@localhost:5432/pirsch
  max_connections: 20

server:
  port: 8080
  host: 0.0.0.0
  read_timeout: 30s
  write_timeout: 30s

analytics:
  session_timeout: 30m
  ignore_bots: true
  salt: "random-salt-for-hashing"

geolocation:
  enabled: true
  database_path: /data/GeoLite2-City.mmdb

Database Setup

PostgreSQL Requirements:

  • PostgreSQL 12 or higher
  • Recommended: 16GB+ RAM for high-traffic sites
  • SSD storage for query performance

Initialization:

CREATE DATABASE pirsch;
CREATE USER pirsch WITH PASSWORD 'your-password';
GRANT ALL PRIVILEGES ON DATABASE pirsch TO pirsch;

Pirsch automatically runs migrations on startup.

CMS & Platform Integrations

WordPress

Plugin Installation:

  1. Download Pirsch WordPress plugin
  2. Upload to /wp-content/plugins/
  3. Activate in WordPress admin
  4. Enter your Pirsch domain identification code
  5. Configure tracking options

Manual Integration:

Add to theme's header.php before </head>:

<script defer src="https://api.pirsch.io/pirsch.js"
    id="pirschjs"
    data-code="YOUR_IDENTIFICATION_CODE"></script>

Ghost

Code Injection:

  1. Navigate to Settings → Code Injection
  2. Add to Site Header:
<script defer src="https://api.pirsch.io/pirsch.js"
    id="pirschjs"
    data-code="YOUR_IDENTIFICATION_CODE"></script>

Hugo

Partial Template:

Create layouts/partials/pirsch.html:

{{ if not .Site.IsServer }}
<script defer src="https://api.pirsch.io/pirsch.js"
    id="pirschjs"
    data-code="{{ .Site.Params.pirschCode }}"></script>
{{ end }}

Add to config.toml:

[params]
  pirschCode = "YOUR_IDENTIFICATION_CODE"

Include in layouts/_default/baseof.html:

<head>
  {{ partial "pirsch.html" . }}
</head>

Next.js

App Router (app/layout.js):

export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <script
          defer
          src="https://api.pirsch.io/pirsch.js"
          id="pirschjs"
          data-code={process.env.NEXT_PUBLIC_PIRSCH_CODE}
        />
      </head>
      <body>{children}</body>
    </html>
  );
}

Pages Router (_app.js):

import Script from 'next/script';

export default function App({ Component, pageProps }) {
  return (
    <>
      <Script
        defer
        src="https://api.pirsch.io/pirsch.js"
        id="pirschjs"
        data-code={process.env.NEXT_PUBLIC_PIRSCH_CODE}
      />
      <Component {...pageProps} />
    </>
  );
}

Webflow

  1. Open Project Settings → Custom Code
  2. Add to Head Code:
<script defer src="https://api.pirsch.io/pirsch.js"
    id="pirschjs"
    data-code="YOUR_IDENTIFICATION_CODE"></script>
  1. Publish site

Data Export & Business Intelligence

Google Sheets Integration

Use Pirsch API with Google Apps Script:

function importPirschData() {
  const CLIENT_ID = 'YOUR_CLIENT_ID';
  const CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
  const DOMAIN_ID = 'YOUR_DOMAIN_ID';

  // Get token
  const tokenResponse = UrlFetchApp.fetch('https://api.pirsch.io/api/v1/token', {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify({
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET
    })
  });

  const token = JSON.parse(tokenResponse.getContentText()).access_token;

  // Fetch stats
  const statsResponse = UrlFetchApp.fetch('https://api.pirsch.io/api/v1/statistics/page', {
    method: 'post',
    headers: {
      'Authorization': 'Bearer ' + token
    },
    contentType: 'application/json',
    payload: JSON.stringify({
      id: DOMAIN_ID,
      from: '2024-01-01',
      to: '2024-01-31'
    })
  });

  // Process and write to sheet
  const data = JSON.parse(statsResponse.getContentText());
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  // ... write data to cells
}

Data Warehouse Integration

Export to BigQuery:

from pirsch import PirschClient
from google.cloud import bigquery

pirsch = PirschClient(client_id='...', client_secret='...')
bq_client = bigquery.Client()

# Export Pirsch data
data = pirsch.export_events(
    domain_id='YOUR_DOMAIN_ID',
    from_date='2024-01-01',
    to_date='2024-01-31',
    format='json'
)

# Load to BigQuery
table_id = 'project.dataset.pirsch_events'
job = bq_client.load_table_from_json(data, table_id)
job.result()

Monitoring & Alerts

Integration with Monitoring Tools

Datadog:

Forward Pirsch webhook events to Datadog:

app.post('/webhook/pirsch', async (req, res) => {
  const event = req.body;

  await fetch('https://api.datadoghq.com/api/v1/events', {
    method: 'POST',
    headers: {
      'DD-API-KEY': DATADOG_API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      title: 'Pirsch Analytics Event',
      text: `Event: ${event.event_type}`,
      tags: [`domain:${event.domain}`, `type:${event.event_type}`]
    })
  });

  res.sendStatus(200);
});

Slack Notifications:

app.post('/webhook/pirsch', async (req, res) => {
  const event = req.body;

  if (event.event_type === 'goal_conversion') {
    await fetch(SLACK_WEBHOOK_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        text: `Goal converted: ${event.data.goal_name}`,
        attachments: [{
          fields: [
            { title: 'Path', value: event.data.path },
            { title: 'Referrer', value: event.data.referrer }
          ]
        }]
      })
    });
  }

  res.sendStatus(200);
});

Best Practices

API Usage:

  • Cache access tokens (valid for 1 hour)
  • Implement exponential backoff for rate limit errors
  • Use bulk endpoints when querying multiple metrics
  • Request only necessary date ranges to minimize processing

Self-Hosting:

  • Use PostgreSQL connection pooling
  • Enable query caching for frequently accessed data
  • Implement CDN for serving tracking script
  • Monitor database size and implement data retention policies
  • Regular backups of analytics database

Security:

  • Rotate API credentials periodically
  • Use environment variables for secrets (never commit to version control)
  • Validate webhook signatures
  • Implement rate limiting on webhook endpoints
  • Use HTTPS for all API communications

Support Resources