Hey there, fellow developer! Ready to supercharge your PHP project with some Klaviyo magic? You're in the right place. Klaviyo's API is a powerhouse for email marketing and customer data, and we're about to dive into integrating it with PHP. Buckle up!
Before we jump in, make sure you've got:
First things first, let's get our project structure sorted:
composer require guzzlehttp/guzzle
This'll bring in Guzzle for our HTTP requests. Trust me, it'll make our lives easier.
Create a simple KlaviyoAPI.php
file. This'll be our home base.
Alright, security first! Let's handle that API key:
class KlaviyoAPI { private $apiKey; public function __construct($apiKey) { $this->apiKey = $apiKey; } }
Simple, right? We'll use this in all our requests.
Time to get our hands dirty. Let's start with a GET request:
public function getLists() { $client = new \GuzzleHttp\Client(); $response = $client->request('GET', 'https://a.klaviyo.com/api/v2/lists', [ 'headers' => [ 'Authorization' => 'Klaviyo-API-Key ' . $this->apiKey ] ]); return json_decode($response->getBody(), true); }
See how we're using that $apiKey
? Smooth.
Always expect the unexpected. Let's add some error handling:
try { $lists = $this->getLists(); } catch (\GuzzleHttp\Exception\RequestException $e) { // Handle error echo "Oops! " . $e->getMessage(); }
Now for the fun part. Let's add a subscriber to a list:
public function addSubscriber($listId, $email) { $client = new \GuzzleHttp\Client(); $response = $client->request('POST', "https://a.klaviyo.com/api/v2/list/{$listId}/members", [ 'headers' => [ 'Authorization' => 'Klaviyo-API-Key ' . $this->apiKey ], 'form_params' => [ 'email' => $email ] ]); return json_decode($response->getBody(), true); }
Remember, with great power comes great responsibility:
Time to put on your QA hat. Here's a quick test:
$klaviyo = new KlaviyoAPI('your-api-key'); $lists = $klaviyo->getLists(); print_r($lists);
If you see your lists, you're golden!
And there you have it! You've just built a Klaviyo API integration in PHP. Pretty cool, huh? Remember, this is just the tip of the iceberg. There's a whole world of Klaviyo API endpoints to explore.
Keep coding, keep learning, and most importantly, have fun with it!
Need more? Check out Klaviyo's API docs for the full scoop.
Happy coding!