Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,15 @@ vendor/bin/phpunit --filter it_sends_event

Tests use the `@test` annotation with `snake_case` method names (no `test` prefix).

CI (`.github/workflows/build.yaml`) runs coding standards, dependency analysis, PHPStan, and PHPUnit against PHP 8.1–8.4 on both `lowest` and `highest` dependency versions, so check lowest-version compatibility when touching dependencies. A separate workflow runs Roave's backwards-compatibility check on PRs — this is a public library, so avoid BC breaks to the public API.
CI (`.github/workflows/build.yaml`) runs coding standards, dependency analysis, PHPStan, and PHPUnit against PHP 8.1–8.4 on both `lowest` and `highest` dependency versions, so check lowest-version compatibility when touching dependencies. A separate workflow runs Roave's backwards-compatibility check on PRs, comparing against the PR's base branch.

### Branches

There is no `master`. **`1.x`** is the default branch and holds the released 1.x line: bug fixes and additive changes only, and the BC check must stay green — this is a public library. **`2.x`** is the next major: BC breaks are allowed there, but every one must be documented in `UPGRADE-2.0.md`. Because the BC check compares against the PR's base, it is expected to be red on `2.x` PRs that break BC; its output should match what `UPGRADE-2.0.md` lists. Always pass `--base` to `gh pr create`. `Closes #123` only auto-closes issues when merged into the default branch, so issues fixed on `2.x` have to be closed by hand.

### LiveClientTest

`tests/Client/LiveClientTest.php` hits the real Meta API. It self-skips unless the env vars in `phpunit.xml.dist` are set (`PIXEL_ID`, `ACCESS_TOKEN`, `TEST_EVENT_CODE`, `URL`, `EMAIL`). Copy `phpunit.xml.dist` to `phpunit.xml` and fill them in to run it.
`tests/Client/LiveClientTest.php` hits the real Meta API. It self-skips unless the env vars in `phpunit.xml.dist` are set (`PIXEL_ID`, `ACCESS_TOKEN`, `TEST_EVENT_CODE`, `URL`, `EMAIL`). Copy `phpunit.xml.dist` to `phpunit.xml` and fill them in to run it. With a filled-in `phpunit.xml`, every full `phpunit` run sends a real test event and Infection replays it for every mutant it covers — move `phpunit.xml` aside before running Infection.

## Architecture

Expand All @@ -48,12 +52,12 @@ So to add a field: add the public property, map it in `getMapping()`, and regist

**Two payload contexts** (`PAYLOAD_CONTEXT_SERVER` vs `PAYLOAD_CONTEXT_BROWSER`). The same objects serialize differently depending on whether they're sent server-side via the Conversions API or rendered into a client-side `fbq()` call. `User::getMapping()` strips server-only fields (IP, user agent, fbc, fbp) in browser context.

**`Parameters` subclasses:** `Event` (the aggregate root — holds `User $userData`, `Custom $customData`, a list of `Pixel`, plus `metadata` for app-internal use that is never sent), `User` (customer matching data), `Custom` (event-specific data like value/currency/contents). `Event` auto-generates `eventId` (random, for [deduplication](https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event#event-id)) and `eventTime` in its constructor. `Event` is intentionally **not** `final` so consumers can subclass it into domain-specific events; the other data objects are `final`.
**`Parameters` subclasses:** `Event` (the aggregate root — holds `User $userData`, `Custom $customData`, a list of `Pixel`, plus `metadata` for app-internal use that is never sent), `User` (customer matching data), `Custom` (event-specific data like value/currency/contents), `Content` (a single item in `Custom::$contents`). `Event` auto-generates `eventId` (random, for [deduplication](https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event#event-id)) and `eventTime` in its constructor. `Event` is intentionally **not** `final` so consumers can subclass it into domain-specific events; the other data objects are `final`.

**`Client` (`src/Client/Client.php`)** — `sendEvent()` serializes the event once, then POSTs it (form-encoded) to `graph.facebook.com/v{ApiConfig::APIVersion}/{pixelId}/events` once per associated pixel (each pixel carries its own access token). Non-200 responses throw `ClientException` built from `ErrorResponse`. HTTP is fully PSR-based: PSR-18 client and PSR-17 factories are auto-discovered via `php-http/discovery` but can be injected with `setHttpClient()` / `setRequestFactory()` / etc. The client is `LoggerAware` and defaults to `NullLogger`.
**`Client` (`src/Client/Client.php`)** — `sendEvent()` delegates to `sendPreparedEvent($event->prepare())`. `Event::prepare()` returns a `PreparedEvent` (`src/Event/PreparedEvent.php`): the `getPayload()` array plus the delivery information (event name and id, pixels, test event code), made of scalars/arrays/`Pixel` only so consumers can hash at capture time and queue it. The pixels are cloned so it is a snapshot, and `withoutAccessTokens()`/`withAccessTokens()` (immutable) keep the tokens out of the queue and restore them by pixel id before sending. `sendPreparedEvent()` POSTs the payload (form-encoded) to `graph.facebook.com/v{ApiConfig::APIVersion}/{pixelId}/events` once per pixel (each pixel carries its own access token). Non-200 responses throw `ClientException` built from `ErrorResponse`. HTTP is fully PSR-based: PSR-18 client and PSR-17 factories are auto-discovered via `php-http/discovery` but can be injected with `setHttpClient()` / `setRequestFactory()` / etc. The client is `LoggerAware` and defaults to `NullLogger`.

**`FbqGenerator` (`src/Generator/FbqGenerator.php`)** — the client-side counterpart. Generates the `fbq('init', ...)` / `fbq('track', ...)` JavaScript snippets, using the browser-context payload and reusing the same `eventId` so server and browser events deduplicate. `Event::isCustom()` decides between `track` and `trackCustom`.

**Value objects (`src/ValueObject/`)** — `Fbc`/`Fbp` (extending `Fb`) model the `_fbc`/`_fbp` cookie values with `fromString()` validation and `value()` serialization; assignable to `User::$fbc`/`$fbp` as either the typed object or a raw string.
**Value objects (`src/ValueObject/`)** — `Fbc`/`Fbp` (extending `Fb`) model the `_fbc`/`_fbp` cookie values with `fromString()` validation and `value()` serialization; assignable to `User::$fbc`/`$fbp` as either the typed object or a raw string. Both accept the optional trailing appendix segment that Meta's parameter builder writes (`getAppendix()`/`withAppendix()`) and write it back unchanged, so a cookie value round-trips byte for byte.

The `facebook/php-business-sdk` dependency is used only for `Normalizer`, `Util::hash`, and `ApiConfig::APIVersion` (the API version is pinned to whatever that package ships).
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
[![Code Coverage][ico-code-coverage]][link-code-coverage]
[![Mutation testing][ico-infection]][link-infection]

> [!NOTE]
> This is the documentation for **2.x**, which is in development. The stable release lives on the
> [`1.x` branch](https://github.com/Setono/meta-conversions-api-php-sdk/tree/1.x). If you are upgrading, see
> [UPGRADE-2.0.md](UPGRADE-2.0.md).

A small, typed PHP library for sending server-side events to Meta's (Facebook's)
[Conversions API](https://developers.facebook.com/docs/marketing-api/conversions-api), and for generating the
matching browser-side `fbq()` snippets.
Expand All @@ -32,6 +37,9 @@ way is to install it together with an implementation:
composer require setono/meta-conversions-api-php-sdk kriswallsmith/buzz nyholm/psr7
```

2.0 is in pre-release. Until it is stable, ask for it explicitly, e.g.
`composer require setono/meta-conversions-api-php-sdk:^2.0@alpha`.

`symfony/http-client` works just as well if you prefer it:

```bash
Expand Down Expand Up @@ -121,7 +129,7 @@ $event->testEventCode = 'TEST12345';

### Error handling

`sendEvent()` throws a `ClientException` if Meta returns a non-2xx response. The message contains Meta's error message,
`sendEvent()` and `sendPreparedEvent()` throw a `ClientException` if Meta returns a non-2xx response. The message contains Meta's error message,
code, trace id and the raw response (including the user-facing explanation when Meta provides one):

```php
Expand All @@ -134,6 +142,28 @@ try {
}
```

## Sending events later, e.g. through a queue

`User` holds the raw email addresses, phone numbers and names until the payload is built, so an `Event` should not be
queued as is. `Event::prepare()` returns a `PreparedEvent` instead: the payload, already normalized and hashed, together
with the pixels and the test event code. It is made of scalars, arrays and `Pixel` objects only, so it serializes with
the PHP serializer or the Symfony serializer without any tricks. Hash at capture time, send later:

```php
// at capture time
$queue->push($event->prepare()->withoutAccessTokens());

// at send time
$preparedEvent = $queue->pop();
$client->sendPreparedEvent($preparedEvent->withAccessTokens([
'your_pixel_id' => 'your_access_token',
]));
```

`withoutAccessTokens()` keeps the access tokens out of the queue and of any failure storage behind it, and
`withAccessTokens()` takes the tokens indexed by pixel id and leaves pixels that are not in the list as they are. Both
return a new instance. If your queue is trusted with the access tokens, you can skip both calls.

## Browser-side tracking with deduplication

To get the best match quality Meta recommends sending events both server-side (this SDK) *and* from the browser, using
Expand Down
30 changes: 30 additions & 0 deletions UPGRADE-2.0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Upgrade from 1.x to 2.0

The requirements are unchanged: PHP 8.1+ and the same dependencies as 1.x.

## `ClientInterface` has a second method, `sendPreparedEvent()`

This is the only backwards-compatibility break, and it only affects you if you implement `ClientInterface` yourself,
for instance in a decorator or a test double. Add:

```php
use Setono\MetaConversionsApi\Event\PreparedEvent;

public function sendPreparedEvent(PreparedEvent $preparedEvent): void;
```

It sends an event that was prepared earlier with `Event::prepare()`, i.e. with the payload already normalized and
hashed. `Client` implements it, and a decorator can simply forward the call.

## Behaviour change in `Client::sendEvent()`

`sendEvent()` now delegates to `sendPreparedEvent($event->prepare())`, so the payload is built before the client checks
whether the event has any pixels. The request that is sent is byte for byte the same as in 1.x. There is one observable
difference: an event without pixels whose data is invalid, an unknown `action_source` for instance, now throws when the
payload is built. In 1.x the client logged the missing pixels and returned without ever building the payload.

## New in 2.0

Nothing you have to change, but worth knowing about: `Event::prepare()` returns a `PreparedEvent` that holds no raw
personal data and can be stored or queued, and `PreparedEvent::withoutAccessTokens()` / `withAccessTokens()` keep the
access tokens out of that storage. See "Sending events later, e.g. through a queue" in the README.
16 changes: 11 additions & 5 deletions src/Client/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Setono\MetaConversionsApi\Event\Event;
use Setono\MetaConversionsApi\Event\PreparedEvent;
use Setono\MetaConversionsApi\Exception\ClientException;

final class Client implements ClientInterface, LoggerAwareInterface
Expand All @@ -33,7 +34,12 @@ public function __construct()

public function sendEvent(Event $event): void
{
if (!$event->hasPixels()) {
$this->sendPreparedEvent($event->prepare());
}

public function sendPreparedEvent(PreparedEvent $preparedEvent): void
{
if ([] === $preparedEvent->pixels) {
$this->logger->error('You are trying to send events to Meta/Facebook, but you haven\'n associated any pixels with your event. This is most likely an error.');

return;
Expand All @@ -42,16 +48,16 @@ public function sendEvent(Event $event): void
$httpClient = $this->getHttpClient();
$requestFactory = $this->getRequestFactory();

$data = json_encode([$event->getPayload()], \JSON_THROW_ON_ERROR);
$data = json_encode([$preparedEvent->payload], \JSON_THROW_ON_ERROR);

foreach ($event->pixels as $pixel) {
foreach ($preparedEvent->pixels as $pixel) {
$body = [
'access_token' => $pixel->accessToken,
'data' => $data,
];

if (null !== $event->testEventCode) {
$body['test_event_code'] = $event->testEventCode;
if (null !== $preparedEvent->testEventCode) {
$body['test_event_code'] = $preparedEvent->testEventCode;
}

$request = $requestFactory->createRequest(
Expand Down
9 changes: 9 additions & 0 deletions src/Client/ClientInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Setono\MetaConversionsApi\Client;

use Setono\MetaConversionsApi\Event\Event;
use Setono\MetaConversionsApi\Event\PreparedEvent;
use Setono\MetaConversionsApi\Exception\ClientException;

/**
Expand All @@ -16,4 +17,12 @@ interface ClientInterface
* @throws ClientException if the request failed in any way
*/
public function sendEvent(Event $event): void;

/**
* Sends an event that was prepared earlier with Event::prepare(). Use this when the personal data is hashed
* at capture time and the event is sent later, for instance through a queue
*
* @throws ClientException if the request failed in any way
*/
public function sendPreparedEvent(PreparedEvent $preparedEvent): void;
}
16 changes: 16 additions & 0 deletions src/Event/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,22 @@ public function hasPixels(): bool
return [] !== $this->pixels;
}

/**
* Returns this event in its ready-to-send form: the payload is built, i.e. normalized and hashed, so the result
* holds no raw personal data and is safe to store or queue. Send it later with ClientInterface::sendPreparedEvent()
*/
public function prepare(): PreparedEvent
{
return new PreparedEvent(
$this->eventName,
$this->eventId,
$this->getPayload(),
// cloned so the prepared event is a snapshot: changing a pixel on either side must not change the other
array_map(static fn (Pixel $pixel): Pixel => clone $pixel, $this->pixels),
$this->testEventCode,
);
}

/**
* @return list<string>
*/
Expand Down
66 changes: 66 additions & 0 deletions src/Event/PreparedEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

declare(strict_types=1);

namespace Setono\MetaConversionsApi\Event;

use Setono\MetaConversionsApi\Pixel\Pixel;

/**
* An event that is ready to be sent: the payload (normalized and hashed) together with the delivery information,
* i.e. the pixels and the test event code. It holds no raw personal data, and everything in it is a scalar,
* an array or a Pixel, so it serializes without any tricks.
*
* The pixels still carry their access tokens. Call withoutAccessTokens() before you store or queue the prepared event
* if the storage should not hold them, and withAccessTokens() to add them back before sending
*
* @see Event::prepare()
*/
final class PreparedEvent
{
/**
* @param array<string, mixed> $payload the result of Event::getPayload()
* @param list<Pixel> $pixels the pixels the event should be sent to
*/
public function __construct(
public readonly string $eventName,
public readonly string $eventId,
public readonly array $payload,
public readonly array $pixels,
public readonly ?string $testEventCode = null,
) {
}

/**
* Returns a copy where the pixels carry no access tokens
*/
public function withoutAccessTokens(): self
{
return new self(
$this->eventName,
$this->eventId,
$this->payload,
array_map(static fn (Pixel $pixel): Pixel => new Pixel($pixel->id), $this->pixels),
$this->testEventCode,
);
}

/**
* Returns a copy where the pixels carry the given access tokens. Pixels that are not in the list are left as they are
*
* @param array<array-key, string> $accessTokens the access tokens indexed by pixel id
*/
public function withAccessTokens(array $accessTokens): self
{
return new self(
$this->eventName,
$this->eventId,
$this->payload,
array_map(
static fn (Pixel $pixel): Pixel => new Pixel($pixel->id, $accessTokens[$pixel->id] ?? $pixel->accessToken),
$this->pixels,
),
$this->testEventCode,
);
}
}
Loading
Loading