bentonow/bento-php-sdk

🍱 Bento PHP SDK and tracking library

v2.0.0 2022-01-26 00:55 UTC

This package is auto-updated.

Last update: 2024-04-09 01:34:23 UTC


README

🍱 Simple, powerful analytics for PHP (and Laravel) projects!

Track events, update data, record LTV and more in PHP. Data is stored in your Bento account so you can easily research and investigate what's going on.

👋 To get personalized support, please tweet @bento or email jesse@bentonow.com!

❤️ Thank you @cavel (in Discord) from GuitarCreative for your contribution to the Laravel documentation.

Installation

Run the following command in your project folder. (Note, this project requires Composer)

composer require bentonow/bento-php-sdk

Installation Laravel

If you want to make the Bento instance accessible throughout your application, you might want to consider using a Service Provider. Service Providers in Laravel are central to bootstrapping all of the framework's various components, like routing, events, etc. Here's a basic guide:

Step 1: Create a new service provider:

You can use the artisan command to generate a new service provider:

php artisan make:provider BentoServiceProvider

This will create a new file in app/Providers.

Step 2: Register the service in the new provider

Open the newly created provider file. In the register method, bind the Bento instance to the service container. The register method is the perfect place to bind items to the service container:

// Add this at the top of the file
use bentonow\Bento\BentoAnalytics;

public function register()
{
    $this->app->singleton(BentoAnalytics::class, function ($app) {
        return new BentoAnalytics([
            'authentication' => [
                'secretKey' => env('BENTO_SECRET_KEY'),
                'publishableKey' => env('BENTO_PUBLISHABLE_KEY')
            ],
            'siteUuid' => env('BENTO_SITE_UUID')
        ]);
    });
}

Note that the env() function is used to get the values from your environment variables. Replace 'BENTO_SECRET_KEY', 'BENTO_PUBLISHABLE_KEY', and 'BENTO_SITE_UUID' with your actual environment variable names.

Step 3: Register the Service Provider

In config/app.php, add your new service provider to the providers array:

'providers' => [
    // Other Service Providers

    App\Providers\BentoServiceProvider::class,
],

Now, you can resolve (or "get") the Bento instance out of the service container anywhere in your application using dependency injection or the app() helper function:

$bento = app(BentoAnalytics::class);

Or you can use dependency injection in your controller method:

public function someMethod(BentoAnalytics $bento) 
{
    // Use $bento here...
}

This way, you're adhering to the Dependency Inversion Principle, one of the SOLID principles of object-oriented design, which can lead to more maintainable and flexible code.

Get Started

To get started with tracking things in Bento, simply initialize the client and run wild!

use bentonow\Bento\BentoAnalytics;

// 1. Create the Bento client.
$bento = new BentoAnalytics([
  'authentication' => [
    'secretKey' => 'secretKey',
    'publishableKey' => 'publishableKey'
  ],
  'siteUuid' => 'siteUuid'
])

# Send in a custom event that can trigger an automation — this will also create the user in your account, no need for a second call!
# We strongly recommend using track() for most real-time things.
$bento->V1->track([
  'email' => 'test@bentonow.com',
  'type' => '$signed_up',
  'details' => [
    'fromCustomEvent' => true
  ]
]);

// Track a custom unique event (purchase, sale, etc).
$bento->V1->trackPurchase([
  'email' => 'test@bentonow.com',
  'purchaseDetails' => [
    'unique' => [
      'key' => 1234,
    ],
    'value' => [
      'amount' => 100,
      'currency' => 'USD',
    ],
    'cart' => [
      'abandoned_checkout_url' => ''
    ]
  ]
])

Read on to see what all you can do with the SDK.

Modules

In addition to the top-level Analytics object, we also provide access to other parts of the API behind their corresponding modules. You can access these off of the main Analytics object.

The Analytics module also provides access to various versions of the API (currently just V1), and each of those provides access to the corresponding modules documented below.

Analytics (Base Module)

tagSubscriber(parameters: TagSubscriberParameters): boolean

This TRIGGERS automations! - If you do not wish to trigger automations, please use the Commands.addTag method.

Tags a subscriber with the specified email and tag. If either the tag or the user do not exist, they will be created in the system. If the user already has the tag, another tag event will be sent, triggering any automations that take place upon a tag being added to a subscriber. Please be aware of the potential consequences.

Because this method uses the batch API, the tag may take between 1 and 3 minutes to appear in the system.

Returns true if the event was successfully dispatched. Returns false otherwise.

Reference Types: TagSubscriberParameters

$bento->V1->tagSubscriber([
  'email' => 'test@bentonow.com',
  'tagName' => 'Test Tag',
]);

addSubscriber(parameters: AddSubscriberParameters): boolean

This TRIGGERS automations! - If you do not wish to trigger automations, please use the Commands.subscribe method.

Creates a subscriber in the system. If the subscriber already exists, another subscribe event will be sent, triggering any automations that take place upon subscription. Please be aware of the potential consequences.

You may optionally pass any fields that you wish to be set on the subscriber during creation.

Because this method uses the batch API, the tag may take between 1 and 3 minutes to appear in the system.

Returns true if the event was successfully dispatched. Returns false otherwise.

Reference Types: AddSubscriberParameters

$bento->V1->addSubscriber([
  'email' => 'test@bentonow.com'
]);

$bento->V1->addSubscriber([
  'date' => '2021-08-20T01:32:57.530Z',
  'email' => 'test@bentonow.com',
  'fields' => [
    'firstName' => 'Test',
    'lastName' => 'Subscriber'
  ]
]);

removeSubscriber(parameters: RemoveSubscriberParameters): boolean

This TRIGGERS automations! - If you do not wish to trigger automations, please use the Commands.unsubscribe method.

Unsubscribes an email in the system. If the email is already unsubscribed, another unsubscribe event will be sent, triggering any automations that take place upon an unsubscribe happening. Please be aware of the potential consequences.

Because this method uses the batch API, the tag may take between 1 and 3 minutes to appear in the system.

Returns true if the event was successfully dispatched. Returns false otherwise.

Reference Types: RemoveSubscriberParameters

$bento->V1->removeSubscriber([
  'email' => 'test@bentonow.com'
]);

updateFields(parameters: UpdateFieldsParameters): boolean

This TRIGGERS automations! - If you do not wish to trigger automations, please use the Commands.addField method.

Sets the passed-in custom fields on the subscriber, creating the subscriber if it does not exist. If the fields are already set on the subscriber, the event will be sent, triggering any automations that take place upon fields being updated. Please be aware of the potential consequences.

Because this method uses the batch API, the tag may take between 1 and 3 minutes to appear in the system.

Returns true if the event was successfully dispatched. Returns false otherwise.

Reference Types: UpdateFieldsParameters

$bento->V1->updateFields([
  'email' => 'test@bentonow.com',
  'fields' => [
    'firstName' => 'Test',
  ]
]);

trackPurchase(parameters: TrackPurchaseParameters): boolean

This TRIGGERS automations! - There is no way to achieve this same behavior without triggering automations.

Tracks a purchase in Bento, used to calculate LTV for your subscribers. The values that are received should be numbers, in cents. For example, $1.00 should be 100.

Because this method uses the batch API, the tag may take between 1 and 3 minutes to appear in the system.

Returns true if the event was successfully dispatched. Returns false otherwise.

Reference Types: TrackPurchaseParameters

$bento->V1->trackPurchase([
  'email' => 'test@bentonow.com',
  'purchaseDetails' => [
    'unique' => [
      'key' => 1234
    ],
    'value' => [
      'amount' => 100,
      'currency' => 'USD'
    ]
  ]
]);

track(parameters: TrackParameters): boolean

This TRIGGERS automations! - There is no way to achieve this same behavior without triggering automations.

Tracks a custom event in Bento.

Because this method uses the batch API, the tag may take between 1 and 3 minutes to appear in the system.

Returns true if the event was successfully dispatched. Returns false otherwise.

Reference Types: TrackParameters

$bento->V1->track([
  'email' => 'test@bentonow.com',
  'type' => '$custom.event',
  'details' => [
    'fromCustomEvent' => true
  ]
]);

Batch

Batch.importSubscribers(parameters: BatchImportSubscribersParameter): number

This does not trigger automations! - If you wish to trigger automations, please batch import events with the type set to BentoEvents.SUBSCRIBE, or $subscribe. Note that the batch event import cannot attach custom fields and will ignore everything except the email.

Creates a batch job to import subscribers into the system. You can pass in between 1 and 1,000 subscribers to import. Each subscriber must have an email, and may optionally have any additional fields. The additional fields are added as custom fields on the subscriber.

This method is processed by the Bento import queues and it may take between 1 and 5 minutes for the results to appear in your dashboard.

Returns the number of subscribers that were imported.

Reference Types: BatchImportSubscribersParameter

$bento->V1->Batch->importSubscribers([
  'subscribers' => [
    ['email' => 'test@bentonow.com', 'age' => 21],
    ['email' => 'test2@bentonow.com'],
    ['email' => 'test3@bentonow.com', 'name' => 'Test User']
  ]
]);

Batch.importEvents(parameters: BatchImportEventsParameter): number

Creates a batch job to import events into the system. You can pass in between 1 and 1,000 events to import. Each event must have an email and a type. In addition to this, you my pass in additional data in the details property,

Returns the number of events that were imported.

Reference Types: BatchImportEventsParameter

use bentonow\Bento\SDK\Batch\BentoEvents;

$bento->V1->Batch->importEvents([
  'events' => [
    ['email' => 'test@bentonow.com', 'type' => BentoEvents::SUBSCRIBE],
    ['email' => 'test@bentonow.com', 'type' => BentoEvents::UNSUBSCRIBE],
    [
      'email' => 'test@bentonow.com',
      'details' => [
        'customData' => 'Used internally.'
      ],
      'type' => '$custom.myEvent'
    ]
  ]
]);

Commands

Commands.addTag(parameters: AddTagParameters): Subscriber | null

This does not trigger automations! - If you wish to trigger automations, please use the core module's tagSubscriber method.

Adds a tag to the subscriber with the matching email.

Note that both the tag and the subscriber will be created if either is missing from system.

Reference Types: AddTagParameters, Subscriber

$bento->V1->Commands->addTag([
  'email' => 'test@bentonow.com',
  'tagName' => 'Test Tag'
]);

Commands.removeTag(parameters: RemoveTagParameters): Subscriber | null

Removes the specified tag from the subscriber with the matching email.

Reference Types: RemoveTagParameters, Subscriber

$bento->V1->Commands->removeTag([
  'email' => 'test@bentonow.com',
  'tagName' => 'Test Tag'
]);

Commands.addField(parameters: AddFieldParameters): Subscriber | null

This does not trigger automations! - If you wish to trigger automations, please use the core module's updateFields method.

Adds a field to the subscriber with the matching email.

Note that both the field and the subscriber will be created if either is missing from system.

Reference Types: AddFieldParameters, Subscriber

$bento->V1->Commands->addField([
  'email' => 'test@bentonow.com',
  'field' => [
    'key' => 'testKey',
    'value' => 'testValue'
  ]
]);

Commands.removeField(parameters: RemoveFieldParameters): Subscriber | null

Removes a field to the subscriber with the matching email.

Reference Types: RemoveFieldParameters, Subscriber

$bento->V1->Commands->removeField([
  'email' => 'test@bentonow.com',
  'fieldName' => 'testField'
]);

Commands.subscribe(parameters: SubscribeParameters): Subscriber | null

This does not trigger automations! - If you wish to trigger automations, please use the core module's addSubscriber method.

Subscribes the supplied email to Bento. If the email does not exist, it is created.

If the subscriber had previously unsubscribed, they will be re-subscribed.

Reference Types: SubscribeParameters, Subscriber

$bento->V1->Commands->subscribe([
  'email' => 'test@bentonow.com'
]);

Commands.unsubscribe(parameters: UnsubscribeParameters): Subscriber | null

This does not trigger automations! - If you wish to trigger automations, please use the core module's removeSubscriber method.

Unsubscribes the supplied email to Bento. If the email does not exist, it is created and immediately unsubscribed. If they had already unsubscribed, the unsubscribed_at property is updated.

Reference Types: UnsubscribeParameters, Subscriber

$bento->V1->Commands->unsubscribe([
  'email' => 'test@bentonow.com',
]);

Experimental

Experimental.validateEmail(parameters: ValidateEmailParameters): boolean

EXPERIMENTAL - This functionality is experimental and may change or stop working at any time.

Attempts to validate the email. You can provide additional information to further refine the validation.

If a name is provided, it compares it against the US Census Data, and so the results may be biased.

Reference Types: ValidateEmailParameters

$bento->V1->Experimental->validateEmail([
  'email' => 'test@bentonow.com',
]);

Experimental.guessGender(parameters: GuessGenderParameters): GuessGenderResponse

EXPERIMENTAL - This functionality is experimental and may change or stop working at any time.

Attempts to guess the gender of the person given a provided name. It compares the name against the US Census Data, and so the results may be biased.

It is possible for the gender to be unknown if the system cannot confidently conclude what gender it may be.

Reference Types: GuessGenderParameters, GuessGenderResponse

$bento->V1->Experimental->guessGender([
  'name' => 'Jesse',
]);

Experimental.geolocate(parameters: GeolocateParameters): LocationData | null

EXPERIMENTAL - This functionality is experimental and may change or stop working at any time.

Attempts to provide location data given a provided IP address.

Reference Types: GeolocateParameters, LocationData

$bento->V1->Experimental->geolocate([
  'ip' => '127.0.0.1',
]);

Experimental.checkBlacklist(parameters: BlacklistParameters): BlacklistResponse

EXPERIMENTAL - This functionality is experimental and may change or stop working at any time.

Looks up the provided URL or IP Address against various blacklists to see if the site has been blacklisted anywhere.

Reference Types: BlacklistParameters, BlacklistResponse

$bento->V1->Experimental->checkBlacklist([
  'domain' => 'bentonow.com',
]);

Fields

Fields.getFields(): Field[] | null

Returns all of the fields for the site.

Reference Types: Field

$bento->V1->Fields->getFields();

Fields.createField(parameters: CreateFieldParameters): Field[] | null

Creates a field inside of Bento. The name of the field is automatically generated from the key that is passed in upon creation. For example:

Key Name
'thisIsAKey' 'This Is A Key'
'this is a key' 'This Is A Key'
'this-is-a-key' 'This Is A Key'
'this_is_a_key' 'This Is A Key'

Reference Types: CreateFieldParameters, Field

$bento->V1->Fields->createField([
  'key' => 'testKey'
]);

Forms

Forms.getResponses(formIdentifier: string): FormResponse[] | null

Returns all of the responses for the form with the specified identifier.

Reference Types: FormResponse

$bento->V1->Forms->getResponses('test-formid-1234');

Subscribers

Subscribers.getSubscribers(parameters?: GetSubscribersParameters): Subscriber | null

Returns the subscriber with the specified email or UUID.

Reference Types: GetSubscribersParameters, Subscriber

$bento->V1->Subscribers->getSubscribers([
  'uuid' => '1234'
]);

$bento->V1->Subscribers->getSubscribers([
  'email' => 'test@bentonow.com'
]);

Subscribers.createSubscriber(parameters: CreateSubscriberParameters): Subscriber | null

Creates a subscriber inside of Bento.

Reference Types: CreateSubscriberParameters, Subscriber

$bento->V1->Subscribers->createSubscriber([
  'email' => 'test@bentonow.com'
]);

Tags

Tags.getTags(): Tag[] | null

Returns all of the fields for the site.

Reference Types: Tag

$bento->V1->Tags->getTags();

Tags.createTag(parameters: CreateTagParameters): Tag[] | null

Creates a tag inside of Bento.

Reference Types: Tag

$bento->V1->Tags->createTag([
  'name' => 'test tag'
]);

Types Reference

AddFieldParameters

Property Type Default Required
email string none ✔️
field mixed none ✔️

AddSubscriberParameters

Property Type Default Required
date Date none
email string none ✔️
fields mixed none

AddTagParameters

Property Type Default Required
email string none ✔️
tagName string none ✔️

BatchImportEventsParameter

Property Type Default Required
events BentoEvent[] none ✔️

BatchImportSubscribersParameter

Property Type Default Required
subscribers ({ email: string } & mixed)[] none ✔️

BentoEvent

This type is a discriminated union of a few different types. Each of these types are documented below:

BaseEvent

Property Type Default Required
date Date none
details mixed none ✔️
email string none ✔️
type string none ✔️

PurchaseEvent

Property Type Default Required
date Date none
details PurchaseDetails none ✔️
email string none ✔️
type BentoEvents.PURCHASE | '$purchase' none ✔️

SubscribeEvent

Property Type Default Required
date Date none
email string none ✔️
fields mixed none
type BentoEvents.SUBSCRIBE | '$subscribe' none ✔️

TagEvent

Property Type Default Required
date Date none
details { tag: string } none ✔️
email string none ✔️
type BentoEvents.TAG | '$tag' none ✔️

UnsubscribeEvent

Property Type Default Required
date Date none
email string none ✔️
type BentoEvents.UNSUBSCRIBE | '$unsubscribe' none ✔️

UpdateFieldsEvent

Property Type Default Required
date Date none
email string none ✔️
type BentoEvents.UPDATE_FIELDS | '$update_fields' none ✔️
fields mixed none ✔️

BlacklistParameters

Note that this takes either domain or ip, but never both.

Property Type Default Required
domain string none ✔️
Property Type Default Required
ip string none ✔️

BlacklistResponse

The results is an object where the key is the name of the blacklist that was checked, and the value is whether or not the domain/IP appeared on that blacklist.

Property Type Default Required
description string none ✔️
query string none ✔️
results mixed none ✔️

BrowserData

Property Type Default Required
height string none ✔️
user_agent string none ✔️
width string none ✔️

CreateFieldParameters

Property Type Default Required
key string none ✔️

CreateSubscriberParameters

Property Type Default Required
email string none ✔️

CreateTagParameters

Property Type Default Required
name string none ✔️

EntityType

This is an enum with the following values:

Name Value
EVENTS 'events'
TAGS 'tags'
VISITORS 'visitors'
VISITORS_FIELDS 'visitors-fields'

Field

Property Type Default Required
attributes FieldAttributes none ✔️
id string none ✔️
type EntityType.VISITORS_FIELDS none ✔️

FieldAttributes

Property Type Default Required
created_at string none ✔️
key string none ✔️
name string none ✔️
whitelisted boolean | null none ✔️

FormResponse

Property Type Default Required
attributes FormResponseAttributes none ✔️
id string none ✔️
type EntityType.EVENTS none ✔️

FormResponseAttributes

Property Type Default Required
data FormResponseData none ✔️
uuid string none ✔️

FormResponseData

Property Type Default Required
browser BrowserData none ✔️
date string none ✔️
details mixed none ✔️
fields mixed none ✔️
id string none ✔️
identity IdentityData none ✔️
ip string none ✔️
location LocationData none ✔️
page PageData none ✔️
site string none ✔️
type string none ✔️
visit string none ✔️
visitor string none ✔️

GetSubscribersParameters

Note that this takes either email or uuid, but never both.

Property Type Default Required
email string none ✔️
Property Type Default Required
uuid string none ✔️

GeolocateParameters

Property Type Default Required
ip string none ✔️

GuessGenderParameters

Property Type Default Required
name string none ✔️

GuessGenderResponse

Property Type Default Required
confidence number | null none ✔️
gender string | null none ✔️

IdentityData

Property Type Default Required
email string none ✔️

LocationData

Property Type Default Required
city_name string none
continent_code string none
country_code2 string none
country_code3 string none
country_name string none
ip string none
latitude number none
longitude number none
postal_code string none
real_region_name string none
region_name string none
request string none

PageData

Property Type Default Required
host string none ✔️
path string none ✔️
protocol string none ✔️
referrer string none ✔️
url string none ✔️

PurchaseCart

Property Type Default Required
abandoned_checkout_url string none
items PurchaseItem[] none

PurchaseDetails

Property Type Default Required
unique { key: string | number; } none ✔️
value { currency: string; amount: number; } none ✔️
cart PurchaseCart none

PurchaseItem

In addition to the properties below, you can pass any other properties that you want as part of the PurchaseItem.

Property Type Default Required
product_sku string none
product_name string none
quantity number none
product_price number none
product_id string none

RemoveFieldParameters

Property Type Default Required
email string none ✔️
fieldName string none ✔️

RemoveSubscriberParameters

Property Type Default Required
date Date none
email string none ✔️

RemoveTagParameters

Property Type Default Required
email string none ✔️
tagName string none ✔️

SubscribeParameters

Property Type Default Required
email string none ✔️

Subscriber

Property Type Default Required
attributes SubscriberAttributes none ✔️
id string none ✔️
type EntityType.VISITOR none ✔️

SubscriberAttributes

Property Type Default Required
cached_tag_ids string[] none ✔️
email string none ✔️
fields mixed | null none ✔️
unsubscribed_at string none ✔️
uuid string none ✔️

Tag

Property Type Default Required
created_at string none ✔️
discarded_at string | null none ✔️
name string | null none ✔️
site_id string none ✔️

TagAttributes

Property Type Default Required
attributes TagAttributes none ✔️
id string none ✔️
type EntityType.TAG none ✔️

TagSubscriberParameters

Property Type Default Required
date Date none
email string none ✔️
tagName string none ✔️

TrackParameters

Property Type Default Required
email string none ✔️
type string none ✔️
details mixed none

TrackPurchaseParameters

Property Type Default Required
date Date none
email string none ✔️
purchaseDetails PurchaseDetails none ✔️

UnsubscribeParameters

Property Type Default Required
email string none ✔️

UpdateFieldsParameters

Property Type Default Required
date Date none
email string none ✔️
fields mixed none ✔️

ValidateEmailParameters

Property Type Default Required
email string none ✔️
ip string none
name string none
userAgent string none

Things to know

  1. Tracking: All events must be identified. Anonymous support coming soon!
  2. Tracking: Most events and indexed inside Bento within a few seconds.
  3. If you need support, just let us know!

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/bentonow/bento-php-sdk. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The package is available as open source under the terms of the MIT License.