### Initialize SimplestatsClient Source: https://simplestats.io/docs/php-client.html Create a new instance of the SimplestatsClient by providing your API token during initialization. This is the basic setup required to start using the client. ```php use SimpleStatsIo\PhpClient\SimplestatsClient; $client = new SimplestatsClient([ 'api_token' => 'your-api-token', ]); ``` -------------------------------- ### Installation Source: https://simplestats.io/docs/php-client.html Install the PHP client using Composer. ```APIDOC ## Installation Install the PHP client using Composer: ```bash composer require simplestats-io/php-client ``` ``` -------------------------------- ### Install PHP Client Source: https://simplestats.io/docs/php-client.html Install the SimpleStats PHP client using Composer. This command adds the package to your project's dependencies. ```bash composer require simplestats-io/php-client ``` -------------------------------- ### Install SimpleStats Filament Plugin Source: https://simplestats.io/docs/filament-plugin.html Install the plugin using Composer. Ensure your .env file has the SIMPLESTATS_API_TOKEN. ```bash composer require simplestats-io/filament-plugin ``` ```env SIMPLESTATS_API_TOKEN=your-api-token-here ``` -------------------------------- ### SimpleStats Filament Config File Example Source: https://simplestats.io/docs/filament-plugin.html Example configuration for the SimpleStats Filament plugin, setting API URL, token, and cache TTL. ```php return [ 'api_url' => env('SIMPLESTATS_API_URL', 'https://simplestats.io/api/v1'), 'api_token' => env('SIMPLESTATS_API_TOKEN'), 'cache_ttl' => 60, ]; ``` -------------------------------- ### Install Statamic Addon Source: https://simplestats.io/docs/statamic-addon.html Install the addon using Composer. Ensure you have PHP 8.2+ and Statamic 6+. ```bash composer require simplestats-io/statamic-addon ``` -------------------------------- ### Valid Tracking URL Examples Source: https://simplestats.io/docs/tracking-codes.html Examples of URL parameters that will be tracked based on the provided configuration. These URLs correctly map to the defined tracking dimensions. ```url https://example.com?utm_source=twitter&utm_medium=desktop ``` ```url https://example.com?utm_source=twitter&utm_medium=mobile ``` ```url https://example.com?ref=google&adGroup=banner ``` -------------------------------- ### Install SimpleStats Laravel Client via Composer Source: https://simplestats.io/docs/installation.html Use this command to add the SimpleStats Laravel client package to your project. Ensure your Laravel version is supported. ```bash composer require simplestats-io/laravel-client ``` -------------------------------- ### Server-rendered Configuration - SimpleStats Source: https://simplestats.io/docs/headless-stateless-spa.html Default configuration for server-rendered Laravel applications. No setup is needed as defaults cover this case. ```php ```php // config/simplestats-client.php 'middleware_groups' => ['web'], 'tracking_storage' => 'session', ``` ``` -------------------------------- ### Define Backend API Route Source: https://simplestats.io/docs/headless-stateless-spa.html Define a GET route for tracking initialization. Ensure this route does not match the 'except' list in the configuration. ```php // routes/api.php Route::get('/track-init', fn () => response()->noContent()); ``` -------------------------------- ### Stats Request with Comparison Source: https://simplestats.io/docs/query-api.html An example of a GET request to the stats endpoint that includes a comparison parameter to analyze data against a previous period. ```http GET /api/v1/stats?preset=last_7_days&comparison=period ``` -------------------------------- ### Invalid Tracking URL Examples Source: https://simplestats.io/docs/tracking-codes.html Examples of URL parameters that will NOT be tracked because they are not defined in the configuration. These URLs use parameter names not present in the 'tracking_codes' array. ```url https://example.com?my_source=twitter&my_medium=desktop ``` ```url https://example.com?my_ref=google&group=banner ``` -------------------------------- ### Example Stats Request Source: https://simplestats.io/docs/query-api.html A basic GET request to the stats endpoint using a preset date range. Ensure your API token is included in the Authorization header. ```http GET /api/v1/stats?preset=last_7_days ``` -------------------------------- ### Configure SimpleStats Tracking Storage Source: https://simplestats.io/docs/installation.html Set the method for persisting visitor attribution data across requests. 'session' is suitable for traditional apps, while 'cache' works for stateless or headless setups. ```php 'tracking_storage' => 'session', ``` -------------------------------- ### Listen for Transaction Changes in PHP Source: https://simplestats.io/docs/how-to-update-a-payment.html Implement `watchTrackingFields` to specify which fields trigger re-tracking when they change. This example watches 'status' and 'total' to update gross and net amounts. ```php use SimpleStatsIo\LaravelClient\Contracts\TrackablePaymentWithCondition; class Transaction extends Model implements TrackablePaymentWithCondition { //.. /** * The gross amount of the payment in cents ($1 = 100 Cent). */ public function getTrackingGross(): float { return $this->total; } /** * The net amount of the payment in cents ($1 = 100 Cent). */ public function getTrackingNet(): float { return $this->total - $this->tax; } /** * The condition that should be fulfilled in order to track the payment. */ public function passTrackingCondition(): bool { return $this->status === 'completed'; } /** * The field(s) we should watch for changes to recheck the condition. */ public function watchTrackingFields(): array { return ['status', 'total']; } //.. } ``` -------------------------------- ### Export All User Data with Timestamp Source: https://simplestats.io/docs/how-to-import-existing-data.html This SQL query selects user IDs and their registration times formatted as 'YYYY-MM-DD HH:MM:SS'. It's a basic example for exporting all user data. ```sql SELECT id, DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as `time` FROM users WHERE 1; ``` -------------------------------- ### Non-Blocking Tracking with fastcgi_finish_request Source: https://simplestats.io/docs/php-client.html Perform tracking operations after sending the response to the client to avoid slowing down the application. This example uses `fastcgi_finish_request` for PHP environments. ```php // Send the response to the browser fastcgi_finish_request(); // Now track (runs after the response is delivered) $client->trackVisitor($visitorHash, $trackingData); ``` -------------------------------- ### Stats Response Example Source: https://simplestats.io/docs/query-api.html The structure of a typical JSON response from the stats endpoint, containing daily data and metadata. Results are in reverse chronological order. ```json { "data": [ { "date": "2026-03-11", "date_clear": "2026-03-11", "pd_visitor": 42, "pd_reg": 5, "pd_cr": 11.9, "pd_net": 15000, "pd_gross": 17850, "pd_dau": 12, "lt_visitor": 1250, "lt_reg": 180, "lt_net": 450000, "lt_arpu": 2500, "lt_arppu": 7500, "lt_arpv": 360, "lt_pu": 60 } ], "meta": { "project_id": 1, "range_amount": 7, "range_type": "days", "range_start": "2026-03-11", "comparison": "0", "preset": "last_7_days", ... } } ``` -------------------------------- ### Get Available Stats Groups Source: https://simplestats.io/docs/query-api.html Use this endpoint to discover the available IDs for filtering stats. For example, call with `statsType=trackReferer` to find referrer IDs. ```http GET /api/v1/stats/groups?stats_type=track_source ``` -------------------------------- ### Publish and Run SimpleStats Migrations Source: https://simplestats.io/docs/how-to-track-a-new-payment.html Publish the SimpleStats client migrations and apply them to your database to add necessary columns, such as `visitor_hash`. ```bash php artisan vendor:publish --tag=simplestats-client-migrations php artisan migrate ``` -------------------------------- ### Publish SimpleStats Configuration File Source: https://simplestats.io/docs/installation.html After obtaining your API token, publish the configuration file to set up your SimpleStats integration. This command is used to copy the default configuration to your project. ```bash php artisan vendor:publish --tag="simplestats-client-config" ``` -------------------------------- ### Configuration Source: https://simplestats.io/docs/php-client.html Configure the SimpleStats client with your API token and other optional settings. ```APIDOC ## Configuration Create a client instance with your API token: ```php use SimpleStatsIo\PhpClient\SimplestatsClient; $client = new SimplestatsClient([ 'api_token' => 'your-api-token', ]); ``` Available config options: ```php $client = new SimplestatsClient([ 'api_token' => 'your-api-token', // required 'api_url' => 'https://simplestats.io/api/v1/', // default 'timeout' => 5, // seconds, default 5 'max_retries' => 3, // default 3 'enabled' => true, // set false to disable tracking ]); ``` ``` -------------------------------- ### Configure Self-Hosted SimpleStats Client Source: https://simplestats.io/docs/php-client.html Instantiate the SimpleStats client, pointing it to your own SimpleStats instance by providing the API token and the custom API URL. ```php $client = new SimplestatsClient([ 'api_token' => 'your-api-token', 'api_url' => 'https://stats.yourdomain.com/api/v1/', ]); ``` -------------------------------- ### Listen to Queue Source: https://simplestats.io/docs/troubleshooting.html For database queues, run this command locally to test if the queue is processing jobs. ```bash php artisan queue:listen ``` -------------------------------- ### Get Grouped Stats Source: https://simplestats.io/docs/query-api.html Returns analytics data grouped by a specific category such as sources, countries, or browsers. ```APIDOC ## GET /api/v1/stats/grouped ### Description Returns analytics data grouped by a specific group (e.g., sources, countries, browsers). ### Method GET ### Endpoint /api/v1/stats/grouped ### Parameters #### Query Parameters - **stats_type** (string) - required - The group to aggregate by. See Available Stats Types below. - **stats_sort** (string) - optional - Sort results by: `name`, `visitors`, `reg`, `cr`, `dau`, `net`, `total`. Default: `visitors`. - **limit** (integer) - optional - Maximum number of results (1-100). Default: 10. - **preset** (string) - optional - A predefined date range. See Available Presets below. - **range_type** (string) - optional - The granularity: `hours`, `days`, `weeks`, `months`, `years`. - **range_amount** (integer) - optional - Number of periods to include. - **range_start** (date) - optional - The starting point from which the range is calculated backwards (format: `Y-m-d`). Defaults to today. Filter parameters The same filter parameters as the Stats endpoint apply here as well. ### Request Example ``` GET /api/v1/stats/grouped?stats_type=track_source&limit=5 ``` ### Response #### Success Response (200) - **data** (array) - Contains aggregated stats data. - **name** (string) - The name of the group. - **type_id** (integer) - The ID of the group. - **visitors** (integer) - Number of visitors. - **reg** (integer) - Number of registrations. - **cr** (float) - Conversion rate. - **dau** (integer) - Daily active users. - **net** (integer) - Net value. - **total** (integer) - Total count. - **meta** (object) - Metadata about the response. - **project_id** (integer) - The project ID. - **range_amount** (integer) - The amount of periods in the range. - **range_type** (string) - The type of range (e.g., `days`). - **range_start** (string) - The start date of the range. - **comparison** (string) - Comparison indicator. #### Response Example ```json { "data": [ { "name": "google", "type_id": 3, "visitors": 120, "reg": 15, "cr": 12.5, "dau": 8, "net": 45000, "total": 1 }, { "name": "twitter", "type_id": 7, "visitors": 85, "reg": 10, "cr": 11.76, "dau": 5, "net": 20000, "total": 1 } ], "meta": { "project_id": 1, "range_amount": 7, "range_type": "days", "range_start": "2026-03-11", "comparison": "0", "preset": "last_7_days", ... } } ``` ``` -------------------------------- ### Get Groups Source: https://simplestats.io/docs/query-api.html Retrieves the available values for a specific stats type, which can be used as IDs for filtering in other endpoints. ```APIDOC ## GET /api/v1/stats/groups ### Description Returns the available values for a specific stats type. Use this to discover the `id`s you need for filtering. For example, to find the `id` for a specific referrer, call this endpoint with `statsType=trackReferer`. ### Method GET ### Endpoint /api/v1/stats/groups ### Parameters #### Query Parameters - **stats_type** (string) - required - The stats type to list values for. See Available Stats Types below. ### Request Example ``` GET /api/v1/stats/groups?stats_type=track_source ``` ### Response #### Success Response (200) - **data** (array) - Contains a list of objects, each with an `id` and `name`. - **id** (integer) - The unique identifier for the group. - **name** (string) - The name of the group. #### Response Example ```json { "data": [ { "id": 3, "name": "google" }, { "id": 7, "name": "twitter" }, { "id": 12, "name": "newsletter" } ] } ``` ``` -------------------------------- ### Publish SimpleStats Filament Config File Source: https://simplestats.io/docs/filament-plugin.html Publish the configuration file to customize settings via environment variables or the config file. ```bash php artisan vendor:publish --tag="simplestats-filament-config" ``` -------------------------------- ### Configure SimpleStats Plugin via Methods Source: https://simplestats.io/docs/filament-plugin.html Customize navigation and caching behavior directly in your PanelProvider using fluent API methods. ```php SimplestatsPlugin::make() ->navigationGroup('Analytics') ->navigationLabel('Stats') ->navigationSort(5) ->navigationIcon('heroicon-o-chart-bar-square') ->cacheTtl(120) ``` -------------------------------- ### Publish Configuration File Source: https://simplestats.io/docs/statamic-addon.html Publish the addon's configuration file to override default settings. This allows customization of API URL, token, and cache TTL. ```bash php artisan vendor:publish --tag="simplestats-config" ``` -------------------------------- ### Get Grouped Stats Data Source: https://simplestats.io/docs/query-api.html Retrieve analytics data aggregated by a specific group, such as sources or countries. You can sort results and specify a date range or granularity. ```http GET /api/v1/stats/grouped?stats_type=track_source&limit=5 ``` -------------------------------- ### Track User Registration with Login Source: https://simplestats.io/docs/php-client.html Track a user registration event and simultaneously record a login event. This is useful for scenarios like auto-login after a user registers. Pass `addLogin: true` to include the login event. ```php $client->trackUser( id: $user->id, registeredAt: $user->createdAt, trackingData: $trackingData, addLogin: true, ); ``` -------------------------------- ### Configure SimplestatsClient Options Source: https://simplestats.io/docs/php-client.html Configure the SimplestatsClient with various options including API token, API URL, request timeout, maximum retries, and an enabled flag to control tracking. The API token is required, while other options have default values. ```php $client = new SimplestatsClient([ 'api_token' => 'your-api-token', 'api_url' => 'https://simplestats.io/api/v1/', 'timeout' => 5, 'max_retries' => 3, 'enabled' => true, ]); ``` -------------------------------- ### Create User Source: https://simplestats.io/docs/ingest-api.html Records a new user registration with associated tracking and location data. ```APIDOC ## Create User ### Description Records a new user registration with associated tracking and location data. ### Method POST ### Endpoint /api/v1/stats-user ### Parameters #### Request Body - **id** (mixed) - Required - The user id. - **time** (string) - Required - The time when the user has registered. Format: `Y-m-d H:i:s P`, before or equal `now` - **ip** (string) - Optional - The `ip` of the user. _(does not get stored)_ - **user_agent** (string) - Optional - The `user_agent` of the user. _(does not get stored)_ - **track_referer** (string) - Optional - The http tracking `referer` of the user. - **track_source** (string) - Optional - The tracking `source` of the user. - **track_medium** (string) - Optional - The tracking `medium` of the user. - **track_campaign** (string) - Optional - The tracking `campaign` of the user. - **track_term** (string) - Optional - The tracking `term` of the user. - **track_content** (string) - Optional - The tracking `content` of the user. - **page_entry** (string) - Optional - The tracking `page_entry` of the user. - **location_country** (string) - Optional - The location `country` of the user. (If the `ip` is set, we take the country that refers to it.) - **location_region** (string) - Optional - The location `region` of the user. (If the `ip` is set, we take the region that refers to it.) - **location_city** (string) - Optional - The location `city` of the user. (If the `ip` is set, we take the city that refers to it.) - **device_type** (string) - Optional - The device `type` of the user. (If the `user_agent` is set, we take the device type that refers to it.) - **device_platform** (string) - Optional - The device `platform` (OS) of the user. (If the `user_agent` is set, we take the device platform that refers to it.) - **device_browser** (string) - Optional - The device `browser` of the user. (If the `user_agent` is set, we take the device browser that refers to it.) - **visitor_hash** (string) - Optional - The `visitor_hash` of the visitor this registration converted from. Links the user to its prior visit (for visit-to-registration timing). - **properties** (object) - Optional - Custom properties to group analytics by, as a `name: value` map (e.g. `{"ab_test": "B"}`). Values must be scalar. Max 50 names per request. See custom properties. ### Request Example ```json { "id": 1, "track_source": "test", "time": "2024-04-04" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **id** (integer) - The ID of the created user. #### Response Example ```json { "message": "Stats User Request accepted.", "id": 1 } ``` ``` -------------------------------- ### Configure API Token Source: https://simplestats.io/docs/statamic-addon.html Add your SimpleStats API token to your .env file. This is required for the addon to authenticate with the API. ```env SIMPLESTATS_API_TOKEN=your-api-token-here ``` -------------------------------- ### Frontend Tracking Initialization - JavaScript Source: https://simplestats.io/docs/headless-stateless-spa.html Place this code at the top of your SPA's root component to send an initial tracking request on page load. It forwards UTM parameters, document referrer, and the current path to your Laravel API. ```javascript ```javascript const params = new URLSearchParams(location.search) const referrer = document.referrer; // this check drops your own frontend as a referrer on in-app navigation, reloads, or expired sessions, only an external referrer is forwarded. const documentReferer = referrer && new URL(referrer).hostname !== location.hostname ? referrer : '' ; fetch('https://api.your-app.com/track-init', { method: 'GET', credentials: 'include', headers: { 'X-Utm-Source': params.get('utm_source') ?? '', 'X-Utm-Medium': params.get('utm_medium') ?? '', 'X-Utm-Campaign': params.get('utm_campaign') ?? '', 'X-Utm-Term': params.get('utm_term') ?? '', 'X-Utm-Content': params.get('utm_content') ?? '', 'X-Document-Referer': documentReferer, 'X-Page': location.pathname, }, }) ``` ``` -------------------------------- ### Track Subscription Details in PHP Source: https://simplestats.io/docs/how-to-track-a-new-payment.html Implement `getTrackingSubscription` to return subscription details or null for one-time payments. This is crucial for calculating recurring revenue metrics. ```php use SimpleStatsIo\LaravelClient\Data\TrackingSubscription; use SimpleStatsIo\LaravelClient\Enums\SubscriptionInterval; class Transaction extends Model implements TrackablePayment { //.. public function getTrackingSubscription(): ?TrackingSubscription { return match ($this->billing_cycle) { 'monthly' => new TrackingSubscription($this->plan_name, SubscriptionInterval::Month), 'yearly' => new TrackingSubscription($this->plan_name, SubscriptionInterval::Year), default => null, // one-time payment }; } } ``` -------------------------------- ### Self-Hosted Client Configuration Source: https://simplestats.io/docs/php-client.html Configure the SimpleStats client to point to your own SimpleStats instance by providing the API token and the custom API URL. ```APIDOC ## Self-Hosted Client Configuration ### Description Point the client to your own SimpleStats instance by providing the API token and the custom API URL during client initialization. ### Configuration Example ```php $client = new SimplestatsClient([ 'api_token' => 'your-api-token', 'api_url' => 'https://stats.yourdomain.com/api/v1/', ]); ``` ### Parameters - **api_token** (string) - Required - Your unique API token for authentication. - **api_url** (string) - Required - The base URL of your self-hosted SimpleStats instance, including the API version. ``` -------------------------------- ### Create Login - Response Source: https://simplestats.io/docs/ingest-api.html Confirms successful login event recording and returns an ID for the event. ```json { "message": "Stats Login Request accepted.", "id": 1 } ``` -------------------------------- ### Create User - Response Source: https://simplestats.io/docs/ingest-api.html Confirms successful user creation and returns the assigned user ID. ```json { "message": "Stats User Request accepted.", "id": 1 } ``` -------------------------------- ### Handle Refunds and Chargebacks in PHP Source: https://simplestats.io/docs/how-to-update-a-payment.html Update `getTrackingGross` and `getTrackingNet` to return 0 when a refund occurs. Also, adjust `passTrackingCondition` and `watchTrackingFields` to include refund status. ```php use SimpleStatsIo\LaravelClient\Contracts\TrackablePaymentWithCondition; class Transaction extends Model implements TrackablePaymentWithCondition { // ... /** * The gross amount of the payment in cents ($1 = 100 Cent). */ public function getTrackingGross(): float { if ($this->refunded_at !== null) { return 0; } return $this->total; } /** * The net amount of the payment in cents ($1 = 100 Cent). */ public function getTrackingNet(): float { if ($this->refunded_at !== null) { return 0; } return $this->total - $this->tax; } /** * The condition that should be fulfilled in order to track the payment. */ public function passTrackingCondition(): bool { return $this->status === 'completed' || $this->refunded_at !== null; } /** * The field(s) we should watch for changes to recheck the condition. */ public function watchTrackingFields(): array { return ['status', 'total', 'refunded_at']; } // ... } ``` -------------------------------- ### Create Login Source: https://simplestats.io/docs/ingest-api.html Records a user login event. ```APIDOC ## Create Login ### Description Records a user login event. ### Method POST ### Endpoint /api/v1/stats-login ### Parameters #### Request Body - **stats_user_id** (integer) - Required - The id of the user trying to login. - **time** (string) - Required - The time when the user tries to login. Format: `Y-m-d H:i:s P`, before or equal `now` ### Request Example ```json { "stats_user_id": 1, "time": "2024-04-04" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **id** (integer) - The ID of the created login event. #### Response Example ```json { "message": "Stats Login Request accepted.", "id": 1 } ``` ``` -------------------------------- ### Headless / SPA Configuration - SimpleStats Source: https://simplestats.io/docs/headless-stateless-spa.html Configuration for headless or SPA applications where the frontend is on a separate domain and communicates with the Laravel API. Uses the cache for tracking. ```php ```php // config/simplestats-client.php 'middleware_groups' => ['api'], 'tracking_storage' => 'cache', ``` ``` -------------------------------- ### Hybrid Configuration - SimpleStats Source: https://simplestats.io/docs/headless-stateless-spa.html Configuration for hybrid applications that serve both marketing pages via Blade and a dashboard as a SPA, both backed by the same Laravel app. Uses cache for tracking. ```php ```php // config/simplestats-client.php 'middleware_groups' => ['web', 'api'], 'tracking_storage' => 'cache', ``` ``` -------------------------------- ### Manually Track Custom Properties for Visitor Source: https://simplestats.io/docs/how-to-track-custom-properties.html Use trackCustomProperties to set properties for the current visitor on demand. The visitor must already be tracked. ```php use SimpleStatsIo\LaravelClient\Facades\SimplestatsClient; use SimpleStatsIo\LaravelClient\Visitor; // for the current visitor (e.g. an A/B test variant known before sign-up) SimplestatsClient::trackCustomProperties( properties: ['ab_test' => 'B'], person: new Visitor(SimplestatsClient::getVisitorHash()), ); ``` -------------------------------- ### Configure Tracking Codes in SimpleStats Source: https://simplestats.io/docs/tracking-codes.html Define custom tracking parameters by mapping desired dimensions to specific URL query parameters. Ensure keys match required names: 'source', 'medium', 'campaign', 'term', 'content'. ```php 'tracking_codes' => [ 'source' => ['utm_source', 'ref'], 'medium' => ['utm_medium', 'adGroup', 'adGroupId'], 'campaign' => ['utm_campaign'], 'term' => ['utm_term'], 'content' => ['utm_content'], ], ``` -------------------------------- ### Manually Track Custom Properties for User Source: https://simplestats.io/docs/how-to-track-custom-properties.html Use trackCustomProperties to set properties for a logged-in user on demand. The user must already be tracked. ```php // for a logged-in user SimplestatsClient::trackCustomProperties( properties: ['ab_test' => 'B'], person: auth()->user(), ); ``` -------------------------------- ### Add Visitor Hash to Payment Model in PHP Source: https://simplestats.io/docs/how-to-track-a-new-payment.html When creating a new payment, retrieve the visitor hash using `SimplestatsClient::getVisitorHash()` and add it to your payment model. ```php use SimpleStatsIo\LaravelClient\Facades\SimplestatsClient; Transaction::create([ ... // add the visitor_hash to the models fillable array 'visitor_hash' => SimplestatsClient::getVisitorHash(), ]); ``` -------------------------------- ### Default Configuration Source: https://simplestats.io/docs/statamic-addon.html The default configuration file for the Statamic addon. Values can be overridden by environment variables. ```php return [ 'api_url' => env('SIMPLESTATS_API_URL', 'https://simplestats.io/api/v1'), 'api_token' => env('SIMPLESTATS_API_TOKEN'), 'cache_ttl' => 60, ]; ``` -------------------------------- ### Configure SimpleStats Queue Source: https://simplestats.io/docs/queue.html Define which queue the tracking API calls should be dispatched to by setting the SIMPLESTATS_QUEUE environment variable or directly in the config file. ```php //config/simplestats-client.php 'queue' => env('SIMPLESTATS_QUEUE', 'default'), ``` -------------------------------- ### Implement User Custom Properties Resolver Source: https://simplestats.io/docs/how-to-track-custom-properties.html Implement the ResolvesUserCustomProperties contract to return user properties as a name-value map. Properties are automatically sent when the user is tracked. ```php namespace App\Analytics; use SimpleStatsIo\LaravelClient\Contracts\ResolvesUserCustomProperties; use SimpleStatsIo\LaravelClient\Contracts\TrackablePerson; class UserCustomPropertiesResolver implements ResolvesUserCustomProperties { public function resolve(TrackablePerson $user): array { return [ 'ab_test' => $user->experiment_variant, // e.g. "A" or "B" 'company' => $user->company_name, ]; } } ``` -------------------------------- ### Configure SimpleStats Tracking Types Source: https://simplestats.io/docs/installation.html Specify the models or events that trigger tracking for logins, user registrations, and payments. Ensure models implement the required contracts. ```php 'tracking_types' => [ 'login' => [ 'event' => Login::class, ], // Make sure this model implements the TrackablePerson or // the TrackablePersonWithCondition Contract 'user' => [ 'model' => User::class, ], // Make sure this model implements the TrackablePayment or // the TrackablePaymentWithCondition contract 'payment' => [ 'model' => null, ], ], ``` -------------------------------- ### Implement Visitor Custom Properties Resolver Source: https://simplestats.io/docs/how-to-track-custom-properties.html Implement the ResolvesVisitorCustomProperties contract to resolve visitor properties based on the incoming request. Properties are sent when the visitor is tracked. ```php namespace App\Analytics; use Illuminate\Http\Request; use Illuminate\Support\Arr; use SimpleStatsIo\LaravelClient\Contracts\ResolvesVisitorCustomProperties; class VisitorCustomPropertiesResolver implements ResolvesVisitorCustomProperties { public function resolve(Request $request): array { // assign the variant on the spot and keep it for the rest of the visit $variant = $request->session()->remember('ab_variant', fn () => Arr::random(['A', 'B'])); return ['ab_test' => $variant]; } } ``` -------------------------------- ### Register SimpleStats Plugin in Filament Source: https://simplestats.io/docs/filament-plugin.html Register the SimplestatsPlugin in your Filament PanelProvider to make the dashboard available. ```php use SimpleStatsIo\FilamentPlugin\SimplestatsPlugin; public function panel(Panel $panel): Panel { return $panel // ... your existing config ->plugin(SimplestatsPlugin::make()); } ``` -------------------------------- ### Create Visitor Source: https://simplestats.io/docs/ingest-api.html This endpoint allows you to create a new visitor record or update an existing one if the ID already exists. It accepts various parameters to track user details, referral information, and device specifics. ```APIDOC ## POST /api/v1/stats-visitor ### Description Creates a new visitor record or updates an existing one if the ID already exists. ### Method POST ### Endpoint /api/v1/stats-visitor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **time** (string) - Required - The time when the user has registered. Format: `Y-m-d H:i:s P`, before or equal `now` - **ip** (string) - Nullable - The `ip` of the user. (does not get stored) - **user_agent** (string) - Nullable - The `user_agent` of the user. (does not get stored) - **track_referer** (string) - Nullable - The http tracking `referer` of the user. - **track_source** (string) - Nullable - The tracking `source` of the user. - **track_medium** (string) - Nullable - The tracking `medium` of the user. - **track_campaign** (string) - Nullable - The tracking `campaign` of the user. - **track_term** (string) - Nullable - The tracking `term` of the user. - **track_content** (string) - Nullable - The tracking `content` of the user. - **page_entry** (string) - Nullable - The tracking `page_entry` of the user. - **location_country** (string) - Nullable - The location `country` of the user. (If the `ip` is set, we take the country that refers to it.) - **location_region** (string) - Nullable - The location `region` of the user. (If the `ip` is set, we take the region that refers to it.) - **location_city** (string) - Nullable - The location `city` of the user. (If the `ip` is set, we take the city that refers to it.) - **device_type** (string) - Nullable - The device `type` of the user. (If the `user_agent` is set, we take the device type that refers to it.) - **device_platform** (string) - Nullable - The device `platform` (OS) of the user. (If the `user_agent` is set, we take the device platform that refers to it.) - **device_browser** (string) - Nullable - The device `browser` of the user. (If the `user_agent` is set, we take the device browser that refers to it.) - **properties** (object) - Nullable - Custom properties to group analytics by, as a `name: value` map (e.g. `{"ab_test": "B"}`). Values must be scalar. Max 50 names per request. See custom properties. ### Request Example ```json { "ip": "127.0.0.1", "user_agent": "Mozilla/5.0 (Linux; Android 13; Pixel 6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36", "track_source": "test", "time": "2024-04-04" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **visitor_hash** (string) - A unique hash identifying the visitor. #### Response Example ```json { "message": "Stats Visitor Request accepted.", "visitor_hash": "9a7c4f2e8b1d6a3c5e0f7b2d4a8c1e6f" } ``` ### TIP If no `visitor_hash` is given, it gets generated from `time`, `ip` and `user_agent`. The returned `visitor_hash` can be used to reference this visitor in other endpoints (payments, custom events, custom properties). ``` -------------------------------- ### Configure Self-Hosted API URL Source: https://simplestats.io/docs/statamic-addon.html If using a self-hosted SimpleStats instance, update the API URL in your .env file. ```env SIMPLESTATS_API_URL=https://stats.yourdomain.com/api/v1 SIMPLESTATS_API_TOKEN=your-api-token-here ``` -------------------------------- ### Track Visitor Event Source: https://simplestats.io/docs/php-client.html Send visitor tracking data to SimpleStats using the trackVisitor method. This method requires the generated visitor hash and the TrackingData object. ```php $client->trackVisitor($visitorHash, $trackingData); ``` -------------------------------- ### Clear Configuration Cache Source: https://simplestats.io/docs/troubleshooting.html Run this command after updating the API token in your .env file to refresh your application's configuration. ```bash php artisan config:cache ``` -------------------------------- ### Register Visitor Custom Properties Resolver Source: https://simplestats.io/docs/how-to-track-custom-properties.html Configure the client to use a custom resolver class for visitor properties. This class should implement the ResolvesVisitorCustomProperties contract. ```php 'custom_properties_resolvers' => [ 'visitor' => App\Analytics\VisitorCustomPropertiesResolver::class, ], ``` -------------------------------- ### Configure Self-Hosted SimpleStats API URL Source: https://simplestats.io/docs/filament-plugin.html Point the plugin to your self-hosted SimpleStats API endpoint using plugin methods or .env. ```php SimplestatsPlugin::make() ->apiUrl('https://stats.yourdomain.com/api/v1') ``` ```env SIMPLESTATS_API_URL=https://stats.yourdomain.com/api/v1 ``` -------------------------------- ### Track a Custom Event with SimplestatsClient Source: https://simplestats.io/docs/how-to-track-a-custom-event.html Use the SimplestatsClient facade to track a custom event. Ensure the Custom Events tracking bit is enabled in your project settings. The event ID must be unique per project. ```php use SimpleStatsIo\LaravelClient\Facades\SimplestatsClient; SimplestatsClient::trackCustomEvent( id: 'evt-' . Str::uuid(), name: 'Button Clicked', person: $user, ); ``` -------------------------------- ### Implement User Tracking Contract Source: https://simplestats.io/docs/how-to-track-a-new-user.html Implement the `TrackablePerson` contract in your `User` model to automatically track new registrations. Ensure the `getTrackingTime` method returns the user's creation timestamp. ```php created_at; } // ... } ``` -------------------------------- ### Track Payment with User Details Source: https://simplestats.io/docs/php-client.html Track a payment with associated user information. Amounts must be in cents and currency in ISO 4217 format. ```php $client->trackPayment( id: $payment->id, gross: 2000, // $20.00 net: 1800, // $18.00 currency: 'USD', time: $payment->paidAt, userId: $user->id, userRegisteredAt: $user->createdAt, ); ``` -------------------------------- ### Create Custom Event Source: https://simplestats.io/docs/ingest-api.html Use this endpoint to record custom events. Ensure the 'time' parameter is formatted correctly and is not in the future. ```json { "id": "evt-550e8400-e29b-41d4-a716-446655440000", "name": "Plan Upgraded", "stats_user_id": "1", "time": "2025-04-04" } ``` ```json { "message": "Stats Custom Event Request accepted.", "id": "evt-550e8400-e29b-41d4-a716-446655440000" } ``` -------------------------------- ### Track a Custom Event for a Visitor Source: https://simplestats.io/docs/how-to-track-a-custom-event.html For events triggered by visitors who are not logged in, create a Visitor object using the current visitor hash. The visitor must have been previously tracked for the event to be recorded. ```php use SimpleStatsIo\LaravelClient\Visitor; SimplestatsClient::trackCustomEvent( id: 'evt-' . Str::uuid(), name: 'CTA Clicked', person: new Visitor(SimplestatsClient::getVisitorHash()), ); ``` -------------------------------- ### Configure Custom User Model for Tracking Source: https://simplestats.io/docs/how-to-track-a-new-user.html If you are not using Laravel's default user model, specify your custom user model in the `config/simplestats-client.php` file. ```php [ // ... 'user' => [ 'model' => App\Models\Account::class, ], // ... ], ```