PHP code example of sfere-io / sfere-laravel

1. Go to this page and download the library: Download sfere-io/sfere-laravel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sfere-io / sfere-laravel example snippets


use Sfere\Facades\Sfere;
use Sfere\Ecommerce\Event;

Sfere::forUser(auth()->user())->track(Event::PURCHASE, [
    'transaction_id' => 'order_98765',
    'currency'       => 'SAR',
    'value'          => 256.96,
    'items'          => [['item_id' => 'sku_12345', 'item_name' => 'Away Jersey', 'price' => 89.99, 'quantity' => 2]],
]);

use Sfere\Facades\Sfere;
use Sfere\Ecommerce\Event;

// Who the user is
Sfere::identify('10293', ['email' => '[email protected]', 'phone' => '+966500000000']);

// What they did
Sfere::track(Event::ADD_TO_CART, [
    'currency' => 'SAR',
    'value'    => 89.99,
    'items'    => [['item_id' => 'sku_12345', 'item_name' => 'Away Jersey', 'price' => 89.99, 'quantity' => 1]],
], userId: '10293');

// Or let the SDK take the id from the authenticated user
Sfere::forUser(auth()->user())->track(Event::SIGN_UP, ['method' => 'email']);

Sfere::track(
    string $event,
    array $properties = [],
    string|int|null $userId = null,
    ?string $anonymousId = null,
    ?DateTimeInterface $timestamp = null,
    array $context = [],
    ?string $messageId = null,
    ?array $integrations = null,
): string

Sfere::identify(
    string|int|null $userId = null,
    array $traits = [],
    ?string $anonymousId = null,
    ?DateTimeInterface $timestamp = null,
    array $context = [],
    ?string $messageId = null,
    ?array $integrations = null,
): string

Sfere::page(
    ?string $name = null,
    array $properties = [],
    string|int|null $userId = null,
    ?string $anonymousId = null,
    ?DateTimeInterface $timestamp = null,
    array $context = [],
    ?string $messageId = null,
    ?array $integrations = null,
): string

Sfere::group(
    string|int $groupId,
    array $traits = [],
    string|int|null $userId = null,
    ?string $anonymousId = null,
    ?DateTimeInterface $timestamp = null,
    array $context = [],
    ?string $messageId = null,
    ?array $integrations = null,
): string

Sfere::alias(
    string|int $previousId,
    string|int|null $userId = null,
    ?DateTimeInterface $timestamp = null,
    array $context = [],
    ?string $messageId = null,
    ?array $integrations = null,
): string

Sfere::forUser(?Authenticatable $user);   // userId (and resolver traits) on every event
Sfere::anonymous(?string $anonymousId);   // anonymousId on every event
Sfere::withContext(array $context);       // merged into every event's context

Sfere::forUser($user)->withContext(['campaign' => ['source' => 'newsletter']])->track(Event::LOGIN);

Sfere::event('track')
    ->name(Event::ADD_TO_CART)       // event name on track, page name on page
    ->userId('10293')
    ->anonymousId($anonymousId)
    ->messageId('cart-abc-1')
    ->timestamp(now())
    ->properties(['currency' => 'SAR', 'value' => 89.99, 'items' => [/* … */]])
    ->context(['campaign' => ['source' => 'newsletter']])
    ->integrations([/* … */])
    ->send();

Sfere::track('import_completed', [], userId: 'u1', timestamp: now()->subDay(), context: ['source' => 'csv']);

$messageId = Sfere::track(Event::PURCHASE, [
    'transaction_id' => 'order_98765',
    'currency'       => 'SAR',
    'value'          => 256.96,
    'tax'            => 16.99,
    'shipping'       => 10.0,
    'coupon'         => 'SUMMER20',
    'items'          => [
        ['item_id' => 'sku_12345', 'item_name' => 'Away Jersey', 'price' => 89.99, 'quantity' => 2, 'coupon' => 'SUMMER20'],
        ['item_id' => 'sku_67890', 'item_name' => 'Home Shorts', 'price' => 49.99, 'quantity' => 1],
    ],
], userId: '10293', messageId: 'purchase-order_98765');

$context = Sfere::requestContext($request, pageUrl: $request->input('page_url'));
Sfere::track(Event::BEGIN_CHECKOUT, $props, userId: $id, context: $context);

// At checkout (customer request): store the context with the order
$order->sfere_context = Sfere::requestContext();   // e.g. a JSON column
$order->save();

// Later, in the payment provider's webhook
Sfere::track(Event::PURCHASE, $props, userId: $order->user_id, context: $order->sfere_context ?? []);

// Controller
$eventId = Sfere::forUser($user)->track(Event::PURCHASE, $props, messageId: "purchase-{$order->id}");

return view('checkout.thanks', ['sfereEventId' => $eventId]);

Sfere::forUser(auth()->user())->track(Event::LOGIN, ['method' => 'password']);
Sfere::forUser(null)->track(...);   // no user: falls back to the anonymous id

use Sfere\Facades\Sfere;

// Use a UUID column instead of the primary key
Sfere::resolveUserIdUsing(fn ($user) => $user->uuid);

// Add email and phone to context.traits of every forUser() event (improves ad matching)
Sfere::resolveTraitsUsing(fn ($user) => ['email' => $user->email, 'phone' => $user->phone]);

Sfere::anonymous($anonymousId)->track(Event::BEGIN_CHECKOUT, $props);

use Illuminate\Support\Facades\Event;
use Sfere\Events\DeliveryFailed;

Event::listen(function (DeliveryFailed $e) {
    report(new RuntimeException("Sfere: {$e->reason} for ".count($e->messageIds).' events'));
});

use Sfere\Facades\Sfere;
use Sfere\Ecommerce\Event;

public function test_checkout_tracks_a_purchase(): void
{
    Sfere::fake();

    $this->actingAs($user)->post('/checkout', $payload);

    Sfere::assertTracked(Event::PURCHASE);
    Sfere::assertTracked(Event::PURCHASE, fn (array $event) => $event['properties']['value'] === 256.96);
    Sfere::assertIdentified('10293');
    Sfere::assertNotTracked(Event::REFUND);
    Sfere::assertSentCount(2);
}

public function test_nothing_is_tracked_for_guests(): void
{
    Sfere::fake();

    $this->get('/');

    Sfere::assertNothingSent();
}

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [\Sfere\Http\Middleware\TrackPageViews::class]);
})
bash
php artisan sfere:test