Installation and setup | laravel-analytics-go | Spatie       

 SPATIE  

laravel-analytics-go
====================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-analytics-go](https://spatie.be/docs/laravel-analytics-go/v1)  Installation and setup

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-analytics-go/v1) 

  Installation and setup    
- [ Introduction ](https://spatie.be/docs/laravel-analytics-go/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-analytics-go/v1/support-us)
- [ Installation and setup ](https://spatie.be/docs/laravel-analytics-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-analytics-go/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-analytics-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-analytics-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-analytics-go/v1/changelog)

 Installation and setup
======================

###  On this page 

1. [ How to obtain the credentials to communicate with Google Analytics ](#content-how-to-obtain-the-credentials-to-communicate-with-google-analytics)
2. [ Constructing a client directly ](#content-constructing-a-client-directly)
3. [ Customizing the client ](#content-customizing-the-client)
4. [ HTTP and caching ](#content-http-and-caching)

This version requires Go 1.27 or higher and Laravel Go `go.laravel.com v0.1.0`.

```
go get github.com/spatie/laravel-analytics-go@v0.1.0
```

Install the package explicitly in `bootstrap/app.go`. Adding the module alone does not register it.

```
import (
    analytics "github.com/spatie/laravel-analytics-go"
    laravel "go.laravel.com"
)

func Options() laravel.Options {
    return laravel.Options{
        Packages: []laravel.Package{analytics.New()},
    }
}
```

The package reads these environment settings:

SettingDefaultPurpose`ANALYTICS_PROPERTY_ID`EmptyNumeric GA4 property ID, not a `G-...` measurement ID`ANALYTICS_CREDENTIALS_PATH``storage/app/analytics/service-account-credentials.json`Path to the service-account JSON file, relative to the process working directory`ANALYTICS_CACHE_LIFETIME_IN_MINUTES``1440`Response cache lifetime, zero disables caching`ANALYTICS_CACHE_STORE`EmptyLaravel cache store, empty uses the application's defaultRegistration does not read credentials or contact Google. This lets unrelated console commands run before Analytics is configured. The first report validates the property and loads the credential file. Initialization errors stay on that client, so restart the application after fixing its credentials. Invalid typed environment settings and negative cache lifetimes stop application startup.

There is no published PHP config file. Configure settings with a callback instead. Callbacks run after environment defaults:

```
analytics.New(func(cfg *analytics.Config) {
    cfg.PropertyID = "123456789"
    cfg.CredentialsFile = "/run/secrets/analytics.json"
    cfg.CacheLifetime = 60 * time.Minute
    cfg.CacheStore = "redis"
})
```

Use `CredentialsJSON` for secret JSON supplied by your application rather than a file. Do not commit credentials or put them in public assets. The configured credentials must describe a service account. The package never searches developer logins or the metadata service.

How to obtain the credentials to communicate with Google Analytics
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

### Getting credentials

The first thing you'll need is some credentials to use Google's APIs. Head over to [Google Cloud Console](https://console.cloud.google.com/apis) and select or create a project.

Go to the API Library and search for "Google Analytics Data API". Choose enable to enable the API.

Click "Credentials" in the sidebar and create a service account. Give the service account a name. In the service account ID you'll see an email address. We'll use this email address later in this guide.

Go to the details screen of your service account and select "Keys". From "Add key", select "Create new key". Select "JSON" as the key type and download the file.

Save the JSON at the location specified by `ANALYTICS_CREDENTIALS_PATH` or `Config.CredentialsFile`. Because the JSON contains sensitive information, do not commit it to your Git repository.

### Granting permissions to your Analytics property

Create an Analytics account on the [Analytics site](https://analytics.google.com/analytics) with a GA4 property.

In Analytics, go to Admin &gt; Property settings and copy the property ID. Use this value for `ANALYTICS_PROPERTY_ID`.

Go to "Property access management" in the Admin section. Add a user using the email address in the `client_email` key from your JSON file. The Analyst role is enough.

Constructing a client directly
--------------------------------------------------------------------------------------------------------------------------------------------------

You can also use the client without package registration:

```
client, err := analytics.NewClient(analytics.Config{
    PropertyID: "123456789",
    CredentialsFile: "/run/secrets/analytics.json",
})
if err != nil {
    return err
}
```

This reads and parses credentials without contacting Google. Signing-key validation and token exchange happen on the first report. Direct clients do not attach a cache automatically. Set `Cache: analytics.LaravelCache("redis")` and a positive `CacheLifetime` to use a Laravel cache from a request, job or command context. An application outside Laravel can supply its own `CacheFunc` and use an ordinary `context.Context`.

Customizing the client
--------------------------------------------------------------------------------------------------------------------------

PHP's service bindings and replaceable `TypeCaster` become explicit Go settings:

- `Config.Service` accepts an authenticated `*analyticsdata.Service` from Google's official SDK. This bypasses credential loading and lets you configure SDK options or use a test server.
- `Config.HTTPClient` controls transport, timeout and redirect behavior for both token and report requests when the package builds the service. It does not affect an injected `Service`.
- `Config.Cast` replaces value conversion for every high-level report. Call `analytics.CastValue` for columns you do not change.
- `Config.Cache` replaces report caching. Its loader errors must not be cached.
- `Config.Client` replaces the entire Laravel service, for example with `analytics.Fake(...)`.

Laravel Go v0.1.0 finds the first service of each type. Registering a second client through `Options.Register` does not replace this package's service. Use `Config.Client` instead. The package has no models, jobs or profile classes to override.

HTTP and caching
--------------------------------------------------------------------------------------------------------

The default HTTP client has a 30-second timeout and does not follow redirects. The timeout includes token acquisition. Concurrent requests share a token, and waiting for a token exchange respects cancellation. OAuth assertions and token expiry use Google's OAuth library and the system clock, not Laravel's test clock. Keep the production clock synchronized.

The token URI in the credential file receives a signed assertion. Only use trusted service-account files. HTTPS is required except for loopback test fixtures. If you supply `HTTPClient` or `Service`, you own its redirect and security policy. Do not log OAuth request or response bodies.

The package uses Google's `net/http` SDK, not Laravel's HTTP client. Laravel `httpclienttest` fakes do not intercept it. Use `Config.Service`, `Config.HTTPClient`, an `httptest.Server`, or the high-level fake instead.

Reports are cached as serialized Google response data before value casting. Returned rows are decoded afresh so callers do not mutate cached values. Successful empty responses are cached. HTTP and decoding failures are not. A successful response with an invalid count can be cached, but high-level casting still returns an error on every read. Cache errors propagate. Zero lifetime bypasses the cache without resolving a store.

Keys include authentication identity, service endpoint, property, report kind and the complete request. A custom service gets an isolated namespace by default. Set `CacheNamespace` to a stable identity if custom clients should share entries across restarts. Never reuse a namespace for services with different access rights. Memory caching is process-local. Use Redis or another shared store when multiple processes need the same cache.

There are no automatic report retries or automatic pagination. Applications choose retry and stale-data policies. Google's OAuth library can return `*oauth2.RetrieveError`, and report failures preserve `*googleapi.Error` through `errors.As`.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
