Giter Club home page Giter Club logo

php-klaviyo's Introduction

php-klaviyo - RETIRED

Deprecation Notice

This SDK and its associated pip package are set to be deprecated on 2024-06-30 and will not receive further updates.

We recommend migrating over to our newest SDK.

You can read more about our SDK release history and support here

For a comparison between our old and new APIs, check out this guide.

Migration Instructions

NOTE: this change is not backwards compatible; migrating to the new SDK requires completing the following steps:

Install New SDK

composer require klaviyo/sdk

Update Import

From:

use Klaviyo\Klaviyo as Klaviyo;

To:

use Klaviyo\Client;

Update Client Instantiation

From:

$client = new Klaviyo( 'PRIVATE_API_KEY', 'PUBLIC_API_KEY' );

To:

$client = new Client('YOUR_API_KEY');

Updating SDK Calls

The new SDK has many changes to namespace (resource and function names), parameters (names, types, and format), and error handling. Additionally, the new SDK sticks to just standard/built-in PHP types (int, string, array, etc), and does not make use of custom Models, as this legacy one does. Please reference this section of the new SDK repo for details on how to update each operation.

Multistore limitation

The new SDK currently sets API keys at a global environment level. This means that if you manage multiple stores, each store's client must be running in a different environment. We plan to update this behavior to better support multistore applications.

What is Klaviyo?

Klaviyo is a real-time service for understanding your customers by aggregating all your customer data, identifying important groups of customers and then taking action. http://www.klaviyo.com/

What does this package do?

  • Track customers and events directly from your backend.

How to install?

composer require klaviyo/php-sdk

API Examples

After installing the Klaviyo package you can initiate it using your public token which is for track events or identifying profiles and/or your private api key to utilize the metrics and list apis.

use Klaviyo\Klaviyo as Klaviyo;

$client = new Klaviyo( 'PRIVATE_API_KEY', 'PUBLIC_API_KEY' );

You can then easily use Klaviyo to track events or identify people. Note, track and identify requests take your public token.

Track an event

use Klaviyo\Model\EventModel as KlaviyoEvent;

$event = new KlaviyoEvent(
    array(
        'event' => 'Filled out Profile',
        'customer_properties' => array(
            '$email' => '[email protected]'
        ),
        'properties' => array(
            'Added Social Accounts' => False
        )
    )
);

$client->publicAPI->track( $event, true );

You can also add profile properties to the 'customer properties' attribute in the Event model

use Klaviyo\Model\EventModel as KlaviyoEvent;

$event = new KlaviyoEvent(
    array(
        'event' => 'Filled out Profile',
        'customer_properties' => array(
            '$email' => '[email protected]',
            '$first_name' => 'Thomas',
            '$last_name' => 'Jefferson'
        ),
        'properties' => array(
            'Added Social Accounts' => False
        )
    )
);

$client->publicAPI->track( $event, true );

or just add a property to someone

use Klaviyo\Model\ProfileModel as KlaviyoProfile;

$profile = new KlaviyoProfile(
    array(
        '$email' => '[email protected]',
        '$first_name' => 'Thomas',
        '$last_name' => 'Jefferson',
        'Plan' => 'Premium'
    )
);

$client->publicAPI->identify( $profile, true );

You can get metrics, a timeline of events and export analytics for a metric. See here for more https://www.klaviyo.com/docs/api/metrics

#return a list of all metrics in your Klaviyo account
$client->metrics->getMetrics();

#return a timeline of all metrics
$client->metrics->getMetricsTimeline();

#return a specific metric timeline using its metric ID
$client->metrics->getMetricTimelineById( 'METRICID' );

#export metric specific values
$client->metrics->getMetricExport( 'METRICID' );

You can create, update, read, and delete lists. See here for more information https://www.klaviyo.com/docs/api/v2/lists

#create a list
$client->lists->createList( 'List Name' );

#Get all lists in your Klaviyo account
$client->lists->getLists();

#Get information about a list
$client->lists->getListById( 'ListId' );

#update a lists properties
$client->lists->updateListNameById( 'ListId', 'ListName' );

#Delete a list from account
$client->lists->deleteList( 'ListId' );

#Subscribe or re-subscribe profiles to a list
$client->lists->addSubscribersToList( 'ListId', array $arrayOfProfiles );

#Check if profiles are on a list and not suppressed
$client->lists->checkListSubscriptions( 'ListId', array $emails, array $phoneNumbers, array $pushTokens );

#Unsubscribe and remove profiles from a list
$client->lists->deleteSubscribersFromList( 'ListId', array $emails );

#Add members to list without affecting consent status
$client->lists->addMembersToList( 'ListId', array $arrayOfProfiles );

#Check if profiles are on a list
$client->lists->checkListMembership( 'ListId', array $emails, array $phoneNumbers, array $pushTokens );

#Remove members from a list without changing their consent status
$client->lists->removeMembersFromList( 'ListId', array $emails );

#Get all exclusions on a list
$client->lists->getListExclusions( 'ListId' );

#Get all of the emails, phone numbers and push tokens for profiles in a given list or segment
$client->lists->getAllMembers( 'GroupId', $marker = $marker_value );

You can fetch profile information given the profile ID, See here for more information https://www.klaviyo.com/docs/api/people

#Get profile by profileId
$client->profiles->getProfile( 'ProfileId' );

#Update a profile
$client->profiles->updateProfile( 'ProfileId', array $properties );

#Get all metrics for a profile
$client->profiles->getAllProfileMetricsTimeline( 'ProfileId' );

#Get a specific metric for a profile
$client->profiles->getProfileMetricTimeline( 'ProfileId', 'MetricId' );

#Get a profile's ID by its email address
$client->profiles->getProfileIdByEmail('[email protected]');

You can request a privacy-compliant profile deletion given an identifying property

#Request profile deletion by email
$client->dataPrivacy->requestProfileDeletion('[email protected]');

#Request profile deletion by phone number
$client->dataPrivacy->requestProfileDeletion('1-234-567-8910', 'phone_number');

#Request profile deletion by person ID
$client->dataPrivacy->requestProfileDeletion('abc123', 'person_id');

Exceptions

Klaviyo\Exception\KlaviyoApiException

Thrown when there is an issue making an API request. After you catch this exception, you can use getMessage() and it will return a string containing more details about the issue that occurred.

Klaviyo\Exception\KlaviyoRateLimitException

If a rate limit happens it will throw a Klaviyo\Exception\KlaviyoRateLimitException. After you catch this exception you can use getMessage() and it will return a JSON encoded array: {"detail":"Request was throttled. Expected available in 26.0 seconds.","retryAfter":26}

Klaviyo\Exception\KlaviyoAuthenticationException

Thrown when there is an authentication error when making an API request, usually caused by an invalid API key.

Klaviyo\Exception\KlaviyoResourceNotFoundException

Thrown when the system attempts to update a property that doesn't exist. For example, attempting to update a list that doesn't exist on the account.

php-klaviyo's People

Contributors

bialecki avatar bradleymellen avatar chris-ware avatar cykolln avatar dano-klaviyo avatar etienneroudeix avatar invertedfjord avatar jon-batscha avatar kamil-klasicki avatar loevgaard avatar mangoceylon2 avatar ogsmith avatar remstone7 avatar siddwarkhedkar avatar smoucka avatar syammohanmp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-klaviyo's Issues

400 status code does not show details

In "handleResponse" an exception is thrown when the status code is !=200, but that exception only contains the status code and does not include any details from the response.
The 400 status may be due to different reasons and it would be nice if the exception contains the exact reason returned in the response.

Rate limiting gives fatal exception

When rate limiting happens it is suppose to throw an exception of type KlaviyoRateLimitException but because of incorrect parameters passed when initializing the exception, it fails and throws a fatal regular Exception instead.

Exception:
Uncaught Error: Wrong parameters for Klaviyo\Exception\KlaviyoRateLimitException([string $message [, long $code [, Throwable $previous = NULL]]]) in /klaviyo/php-sdk/src/KlaviyoAPI.php:182

Cause of error:
KlaviyoRateLimitException is expecting a string as the first parameter but the KlaviyoAPI class attempts to pass an Array.

Exception When Time Isn't Provided

The change to EventModel in commit 8d73402 in PR #19 removes the check for $config['time'] being empty. Per the documentation, time is not a required parameter so I believe this change creates a new bug. I am getting an exception when attempting to track an event because I am not providing time, and the call to is_int($config['time']) is throwing an undefined index PHP error.

A way to get list pages

Klaviyo API provides a 'marker' variable to retrieve additional pages when there are more than 1000 members on a list, but I don't see a way to use it in this package.

Is this possible?

Thank you!

PHP version

PHP version is missing from composer. Might be useful especially in legacy projects.

Minimum Stability

Are there any plans to update this package to meet minimum stability?

[InvalidArgumentException] Could not find package klaviyo/php-sdk[dev-master] at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

"YOUR_TOKEN"

What is "YOUR_TOKEN" ? Is this the public Api key, private api key...or other?

Does it work with Laravel 5.*???

Hi, I'm trying to make it works though a Laravel 5.* project, But something is not working. Do you know if its possible to work in that version? Thanks!

POST vs GET - Track Endpoint

So I'm currently trying to implement this SDK and ran into some issues because I'm pushing far too much data that can be in a URL.

My snippet looked like:

    public function invitedUserEvent(User $user): void
    {
        $event = new EventModel([
            'event' => EventType::INVITED_USER,
            'customer_properties' => [
                '$email' => $user->email
            ],
            'properties' => [
              // email properties
            ]
        ]);

        $this->publicAPI->track($event);
    }

The docs say the GET version of this track method is not recommend, instead using the POST https://apidocs.klaviyo.com/reference/track-identify. However, outside of manually constructing the KlaviyoAPI class and passing in all parameters/configs to manually make the POST call - I'm not sure how to use the POST iteration of this.

Data Privacy API Name Needs to be CamelCased to Avoid "Sorry, dataprivacy is not a valid Klaviyo API"

The docs say that the data privacy API can be used like this:

#Request profile deletion by email
$client->dataprivacy->requestProfileDeletion('[email protected]');

#Request profile deletion by phone number
$client->dataprivacy->requestProfileDeletion('1-234-567-8910', 'phone_number');

#Request profile deletion by person ID
$client->dataprivacy->requestProfileDeletion('abc123', 'person_id');

However, this leads to inconsistent behavior on different systems depending upon whether PHP is running on a case-sensitive filesystem. If the filesystem is case sensitive, using the above examples will yield this error:

Klaviyo\Exception\KlaviyoException: Sorry, dataprivacy is not a valid Klaviyo API. in Klaviyo\Klaviyo->__get() (line 72 of /code/vendor/klaviyo/php-sdk/src/Klaviyo.php).

The following seems more reliable:

#Request profile deletion by email
$client->dataPrivacy->requestProfileDeletion('[email protected]');

#Request profile deletion by phone number
$client->dataPrivacy->requestProfileDeletion('1-234-567-8910', 'phone_number');

#Request profile deletion by person ID
$client->dataPrivacy->requestProfileDeletion('abc123', 'person_id');

It looks like this has to do with the way that the pseudo-fields are transformed into class names using ucwords, which only affects the first letter of the class name; meanwhile, the name of the actual API class is DataPrivacy so the name going in needs to be lower-camel for the file to be found by the auto-loader.

Integrating the product feed for other ecommerce platforms

We are trying to implement the Product Feed as described here (https://help.klaviyo.com/hc/en-us/articles/115005082787-Product-Feeds-and-Recommendations) for one of our customers (coronacigar.com). The online documentation doesn’t give a detailed procedure of how to get this done with third party shopping cart.

As far as I understand, the feed is meant to be pulled by Shopify from the retailer’s webstore. However, I think this feed should follow a specific format as well as being returned in a specific format (JSON or XML).

Can't get Profile ID when creating a new Profile w/ "publicApi->identify"

When creating a new profile it doesn't seem like it's possible to get the Profile ID (or any of the response object for that matter), so I can't make subsequent calls using the newly created Profile. There's also no API to retrieve profile via email, so I can't see how I can ever know the correct Profile ID associated w/an email.

Example:

$res = $this->client->publicAPI->identify( $profile );
return $res;

$res is just the number 1 every time it's called

400 responses cause spurious PHP notices if response was blank

I'm encountering an issue when Klaviyo returns a 400 (Bad Request) but does not provide any response body. The change from issue #40 assumes that the response contains some details and tries to provide them, but since the response is empty, it causes a PHP notice since it's looking for a "detail" element that doesn't exist:

Notice: Undefined index: detail in Klaviyo\KlaviyoAPI->handleResponse() (line 185 of /var/www/www.highlights.com/webroot/sites/www.highlights.com/modules/hfc_comm_pref/vendor/klaviyo/php-sdk/src/KlaviyoAPI.php).

This happens, for instance, when I attempt to check whether a profile belongs to a list, but the list ID I passed is invalid. Of course the obvious response in this case might be "so don't pass invalid list IDs", but given that there exists any situation where Klaviyo might choose to reply with an empty 400 response, it would be nice if handleResponse was prepared for that situation and didn't clutter the logs with PHP notices.

compose install issue

klaviyo git:(master) ✗ composer require klaviyo/php-sdk
Using version ^2.1 for klaviyo/php-sdk
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)

Installation failed, deleting ./composer.json.

[ErrorException]
"continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

require [--dev] [--prefer-source] [--prefer-dist] [--no-progress] [--no-suggest] [--no-update] [--no-scripts] [--update-no-dev] [--update-with-dependencies] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--] []...

Exception When Time Is Provided

If a time is provided in the $config array, an error is thrown on line 56 of EventModel:

Cannot use object of type DateTime as array

56 $this->time = !empty($config['time']) ? strtotime( $time['date'] ) : null;

You cannot access the 'date' property of a DateTime object directly, it needs to be changed to

56 $this->time = !empty($config['time']) ? strtotime( $time->format('Y-m-d H:i:s') : null;

How can track multiple products

I have to tract multiple product purchase to Klaviyo. given example with only one SKU.

$tracker = new Klaviyo("YOUR_TOKEN");
$tracker->track(
    'Purchased item',
    array('$email' => '[email protected]', '$first_name' => 'Bill', '$last_name' => 'Shakespeare'),
    array('Item SKU' => 'ABC123', 'Payment Method' => 'Credit Card'),
    1354913220
);

I have multiple SKU with single order. How can I achieve this ?

Adding $consent for SMS

I've tried adding the following to the customer_properties and email seems like it consents correctly in Klaviyo by showing up the green checkmark next to the email, but phone number does not.

The phone number shows up in Klaviyo just fine, but I can't get the consent to turn on.

$event = new KlaviyoEvent(
            array(
                'event' => 'Lead',
                'customer_properties' => array(
                    '$email' => $this->email,
                    '$consent' => ['sms', 'email'],
                    'sms_consent' => true,
                    'email_consent' => true,
                    '$first_name' => $first_name,
                    '$last_name' => $last_name,
                    '$phone_number' => '+1' . $this->phone_number
                ),
                'properties' => array()
            )
        );

I've followed couple of Klaviyo tutorials but no luck.

https://apidocs.klaviyo.com/reference/track-identify#track-identify-overview
https://help.klaviyo.com/hc/en-us/articles/360054803711-Guide-to-Collecting-SMS-Consent-via-API

Property value as array

Passing an array (defined as a string) as a property value and encountering this issue:

Output in klaviyo:
testing = [\"jon\",\"doe\"]

This is the code I'm using to create this
$this->klaviyo->updateProfile($klaviyoProfile["id"], ['testing' => '["jon","doe"]' ])

Could not scan for classes inside "src"

I'm getting this error.
[RuntimeException] Could not scan for classes inside "src" which does not appear to be a file nor a folder

I have used given default composer.json file with this command composer install

{
    "name": "klaviyo/php-sdk",
    "description": "Klaviyo PHP SDK",
    "keywords": ["klaviyo", "sdk"],
    "type": "library",
    "homepage": "http://github.com/klaviyo",
    "license": "Apache2",
    "authors": [
        {
            "name": "Klaviyo",
            "homepage": "https://github.com/klaviyo"
        }
    ],
    "require": {
        "php": ">=5.2.0",
        "ext-json": "*"
    },
    "autoload": {
        "classmap": ["src"]
    }
}

I'm able to install using this command but I'm not sure about it's reliability.
composer require klaviyo/php-sdk @dev

Is this project auto generated?

Is this project auto generated? If not I will add some PRs improving the overall quality and developer experience if that would be okay?

PHP 8.1 support - Klaviyo\Model\ProfileModel::jsonSerialize()

👋🏻 Hello,

I have a deprecation warning :

Deprecated: Return type of Klaviyo\Model\ProfileModel::jsonSerialize() should either be compatible with JsonSerializable::jsonSerialize(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in xxxx/xxxxx/vendor/klaviyo/php-sdk/src/Model/ProfileModel.php on line 164

In order to reproduce :

namespace App\Client;

use Klaviyo\Klaviyo as KlaviyoSDK;
use Klaviyo\Model\ProfileModel as KlaviyoProfile;

class Klaviyo
{
    public function __construct(
        protected KlaviyoSDK $client
    ) {
    }

    public function create($args): void
    {

        $profile = new KlaviyoProfile($args);

        /* @phpstan-ignore-next-line */
        $this->client->publicAPI->identify($profile, true);
    }
}

Thanks 🙏🏼
/Sam

When is the next release coming out?

Hello,

At the moment I am using 2.2.5 tag, but I am going to use Data Privacy API V2 due to GDPR. I see that support for the deletion requests was added into the master but it still isn't released. I don't want to use an unstable master code. So, just have a question, when is the next release coming out?

Thanks in advance!

Event "Ordered Product" not all product items tracked

I have 4 items in my order and not all products are tracked when sending the event "Ordered Product". only 2 events are sent to Klaviyo regarding "Ordered Product" when checking through the Klaviyo backend inside my customer profile.
I checked the eventdata during checkout and they are correct for all 4 items.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.