Download the PHP package sfere-io/sfere-laravel without Composer

On this page you can find all versions of the php package sfere-io/sfere-laravel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package sfere-laravel

Sfere for Laravel

CI Release Quality gate status Coverage Lines of Code Duplicated Lines (%) Reliability Rating Security Rating Maintainability Rating Reliability Issues Security Issues Maintainability Issues Technical Debt

Send analytics and conversion events from your Laravel backend to Sfere ingestion.

The SDK forwards your customer's IP, user agent and ad click IDs with every server event. Ad-platform conversion APIs (Meta, TikTok, Google Ads, Snap, …) match on exactly these values. Sfere ingestion does not fill them in for server-sent events: the request comes from your server, not from your customer.

Requirements: PHP 8.2+, Laravel 12 or 13 (Laravel 13 needs PHP 8.3+).


Contents


Installation

The package is on packagist.org, so Composer needs no extra repository or token. Composer adds the constraint ^0.1, which stays on 0.1.x releases. Before 1.0, a breaking change moves the minor version (0.2), so upgrade to it deliberately after reading CHANGELOG.md.

The service provider and the Sfere facade are auto-discovered. sfere:install publishes config/sfere.php and prints the environment variables to add:

Check the credentials with a real test event:

Getting a server key

Sfere gives you two kinds of write key, both in the form keyId:secret:

Key Where it goes
Browser key Web pages and apps. It is public by design.
Server key Your backend only. It is a secret.

This package needs a server key. Create one in the Sfere dashboard on your source's write keys. The secret is shown only once; store it as SFERE_WRITE_KEY in the form keyId:secret.

⚠️ A browser key is accepted by ingestion, but then every event reports your server's IP instead of your customer's. Conversions stop matching on ad platforms. If your events all show the same IP, see Troubleshooting.

SFERE_HOST is the Sfere ingestion origin, https://events.sfere.io, unless Sfere gives you a different host with your keys. Use the scheme and host only, with no path: https://events.sfere.io, not https://events.sfere.io/v1/batch.

Configuration

All keys in config/sfere.php:

Key Env Default Notes
enabled SFERE_ENABLED true false turns every call into a no-op
host SFERE_HOST — Ingestion origin, no path
write_key SFERE_WRITE_KEY — Server key, keyId:secret
delivery SFERE_DELIVERY batch sync, batch or queue. See Delivery modes
batch.max_size 100 Events per request (capped at 100)
batch.max_bytes 500000 Bytes per request (capped at 500 KB)
batch.max_wait_seconds 10 Flush when the oldest buffered event is this old (long-running processes)
queue.connection SFERE_QUEUE_CONNECTION default connection Queue mode only
queue.name SFERE_QUEUE default Queue mode only
queue.tries 5 Attempts per SendEvents job
queue.backoff [10, 30, 60, 120] Seconds between job attempts
queue.encrypt SFERE_QUEUE_ENCRYPT true Encrypt queued payloads with the app key (ShouldBeEncrypted); they carry PII
http.timeout 3 Seconds per request
http.connect_timeout 2 Seconds to connect
http.retries 3 Attempts per request on network errors, 429 and 5xx
http.max_retry_after 10 Cap, in seconds, on a server's Retry-After
http.compression false Gzip batch request bodies
context.include_request true Add the customer's IP, user agent, locale, page, campaign and click IDs
context.trust_proxy true Read the client IP from the left-most X-Forwarded-For. false uses $request->ip(), which follows your app's TrustProxies setup
context.anonymous_id_cookie ajs_anonymous_id Browser anonymous id cookie, read when an event has none. null disables it. Experimental
context.static [] Merged into every event's context
throw_exceptions SFERE_THROW false Throw on invalid events and delivery failures instead of logging
log_channel SFERE_LOG_CHANNEL default channel Where warnings and failures are logged

If enabled is false, or host or write_key is missing or invalid, the SDK becomes a no-op. It then logs one warning per process that says why.

Quick start

Inside an HTTP request, the customer's IP, user agent, page, campaign and click IDs are added automatically. In batch mode, the events are sent after the response.

API reference

Every send method returns the event's messageId (a string). It returns one even when the SDK is disabled or faked, so your code never needs to branch on it.

track

properties.sfere_dedup_id is set on every track. Your own value is kept; otherwise it is the event's messageId.

identify

page

A server-side page view.

group

alias

Links a previous id, usually the anonymous id, to a user id.

Scoped clients

These return a new client and never change the shared one, so they are safe under Octane.

Fluent builder

For advanced cases. send() returns the messageId.

The builder also has traits() (identify, group), groupId() (group) and previousId() (alias).

Other methods

Method What it does
Sfere::resolveUserIdUsing(?Closure $resolver) How forUser() gets the user id. Default: getAuthIdentifier(), cast to string
Sfere::resolveTraitsUsing(?Closure $resolver) Traits forUser() adds as context.traits. No default
Sfere::requestContext(?Request $request = null, ?string $pageUrl = null): array The customer context of a request. See Request context
Sfere::flush() Send (or enqueue) everything buffered now

Overrides

Invalid input

The SDK checks these rules before it buffers an event:

An invalid event is logged and dropped. With throw_exceptions on, it throws Sfere\Exceptions\InvalidEventException instead.

E-commerce events

Sfere uses the GA4 e-commerce vocabulary for event and property names. A single instrumentation then feeds analytics and every server-side conversion destination. Sfere\Ecommerce\Event has a constant for each name:

Constant Event When
VIEW_ITEM view_item Product detail page viewed
VIEW_ITEM_LIST view_item_list Product listing viewed
SELECT_ITEM select_item Product clicked in a list
ADD_TO_CART add_to_cart Product added to cart
REMOVE_FROM_CART remove_from_cart Product removed from cart
ADD_TO_WISHLIST add_to_wishlist Product added to a wishlist
VIEW_CART view_cart Cart viewed
BEGIN_CHECKOUT begin_checkout Checkout started
ADD_SHIPPING_INFO add_shipping_info Shipping method chosen
ADD_PAYMENT_INFO add_payment_info Payment details entered
PURCHASE purchase Order completed
REFUND refund Order refunded
SEARCH search Site search submitted
SIGN_UP sign_up Account created
LOGIN login User logged in
GENERATE_LEAD generate_lead Lead form submitted

Other names are accepted and forwarded unchanged.

Property rules:

Item fields:

Extra keys are forwarded unchanged.

Request context

Inside an HTTP request, every event gets this context from the customer's request:

Field From
context.ip Left-most X-Forwarded-For, then X-Real-IP, then the socket address. With trust_proxy off: $request->ip()
context.userAgent User-Agent
context.locale First Accept-Language tag
context.page url, path, search of the request URL, plus referrer from Referer
context.campaign utm_* → source, medium, name, term, content, plus gad_source and gad_campaignid. Read from the page URL, else from the referrer
context.clientIds Ad cookies (_fbp, _fbc, _ttp, _gcl_aw, _scid, _clck, …) and landing click IDs (gclid, ttclid, msclkid, …). A landing fbclid becomes fbc

The context is captured when you call track(), not when the event is sent. Batched and queued events therefore keep it.

trust_proxy. Most deployments sit behind a load balancer, so it defaults to true. Set it to false if the app is reached directly; otherwise a client could choose the IP it is reported with.

Cookies and EncryptCookies. Laravel's EncryptCookies middleware turns every cookie it did not encrypt (_fbp, _gcl_aw, …) into null on $request->cookie(). The SDK reads the raw Cookie header instead, so you do not need to add the ad cookies to EncryptCookies::$except.

API calls from a page. When the request is an API call made by a page (for example the checkout page's AJAX call), pass that page's URL. Its query string then supplies the landing click IDs and UTM parameters:

Events outside a customer request (webhooks, cron)

A payment webhook, a cron job or a refund issued by staff has no customer request, so there is no IP or click ID to read. Save the customer's context while you have it, and pass it back later:

You can also send without a context. The event is still recorded, but it matches less well on ad platforms.

Browser and server deduplication

If a browser pixel and Sfere both report the same conversion, the ad platform counts it once only when both carry the same event ID and the same event name. Sfere's server-side destinations use the event's messageId as that ID.

track() returns the messageId. Pass a deterministic one, or use the returned one, and render it into the page for the pixel:

Other platforms take the same value:

Notes:

Identity

User id rules. The userId must be your stable, opaque, non-PII internal id, sent as a string. Integer ids are cast for you; "10293" is fine. Do not use an email or a phone number. The placeholder values 0, -1, null, undefined, test, na and n/a are rejected, as are ids longer than 512 characters.

The authenticated user:

Resolvers. Set these once, for example in AppServiceProvider::boot():

There is no default traits resolver: sending PII is your decision. On identify, resolver traits are merged into traits, and traits you pass explicitly win.

Anonymous visitors:

Anonymous id from the browser (experimental). When an event has no anonymousId, the SDK reads the browser SDK's anonymous id cookie (context.anonymous_id_cookie, default ajs_anonymous_id) from the current request. That links server events to the visitor's browser session for profile merging. Set the option to null to turn this off.

Delivery modes

Set the mode with SFERE_DELIVERY.

Mode When events leave Use for
sync Immediately, one request per event, inside your call The console and debugging. Retries block your code, up to a few seconds when ingestion is slow or down
batch (default) In batches of up to 100 events and 500 KB, after the response Web apps
queue A Sfere\Jobs\SendEvents job per batch, on your queue When you want the durability and retries of your queue

When batch mode flushes:

Call Sfere::flush() to send everything immediately.

queue mode uses the same buffering. Each flush dispatches a job on queue.connection / queue.name. The job retries up to queue.tries times with queue.backoff. Payloads are encrypted with your APP_KEY (SendEncryptedEvents) unless queue.encrypt is false, because they carry traits, IPs and click IDs.

Retries:

Laravel events

Event Fired when Properties
Sfere\Events\EventsSent Ingestion accepted events messageIds, okEvents
Sfere\Events\DeliveryFailed Events were not accepted after every retry, including partially rejected batches messageIds, status, reason, retryable

Failures are also logged to log_channel, with the event count, messageIds, status and reason. The write key and event payloads are never logged.

Testing your app

Sfere::fake() records events in memory and makes no HTTP calls. The recorded events are the exact arrays that would be sent, including context.

track() still returns a messageId under the fake.

Page-view middleware

Sfere\Http\Middleware\TrackPageViews sends a page event for every GET request that returns a successful HTML response. It skips /horizon*, /telescope*, /livewire* and /_debugbar*.

To skip more paths, extend the class and override $except.

⚠️ If the Sfere browser SDK is also installed on your pages, it already sends page views. Adding this middleware then counts every page view twice. Use one or the other.

Privacy

Troubleshooting

Symptom Cause and fix
Nothing is sent at all The SDK is a no-op. Look for the one-time warning Sfere: events are not sent: … in your log: it names the missing or invalid setting. Run php artisan sfere:test
invalid write key / 401 The key is wrong, revoked, or not in keyId:secret form. Create a new server key
no destinations configured for this stream Ingestion accepted the request, but the source has no destination connected, so the event went nowhere. Connect a destination in Sfere
Every event shows your server's IP You are using a browser key. Switch SFERE_WRITE_KEY to a server key
Events have no click IDs (context.clientIds) The event was sent outside the customer's request (pass a stored context), or a proxy or CDN strips cookies. On a landing page, pixel cookies may not exist yet on the very first request
The IP is your load balancer's Keep context.trust_proxy on, and make sure the proxy sets X-Forwarded-For
The IP is wrong or spoofable The app is reached directly: set context.trust_proxy to false and configure Laravel's TrustProxies
Events arrive late In batch mode, events leave at the end of the request, job or command. Long-running processes flush every batch.max_wait_seconds
Some events are rejected in a batch Listen for DeliveryFailed. Its reason comes from ingestion, and those events are not retried

Contributing

Pull request policy, local setup and the CI checks: docs/ci-cd.md.

License

MIT. See LICENSE.md.


All versions of sfere-laravel with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
illuminate/console Version ^12.0|^13.0
illuminate/contracts Version ^12.0|^13.0
illuminate/http Version ^12.0|^13.0
illuminate/queue Version ^12.0|^13.0
illuminate/support Version ^12.0|^13.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package sfere-io/sfere-laravel contains the following files

Loading the files please wait ...