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
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ There is no `master`. **`2.x`** is the default branch and the next major: BC bre

The core abstraction is the serialization pipeline in `src/Event/Parameters.php`. Everything sent to Meta flows through it.

**`Parameters` (abstract base)** — each subclass implements `getMapping(string $context): array`, returning Meta's snake_case field names mapped to the object's (camelCase) PHP property values. `getPayload()` runs that mapping through `normalize()`, which recursively:
**`Parameters` (abstract base)** — each subclass implements `getMapping(PayloadContext $context): array`, returning Meta's snake_case field names mapped to the object's (camelCase) PHP property values. `getPayload()` runs that mapping through `normalize()`, which recursively:
1. formats `DateTimeInterface` as `Ymd` and casts `Stringable` to string,
2. normalizes fields listed in `getNormalizedFields()` via `FacebookAds\Object\ServerSide\Normalizer`,
3. hashes fields listed in `getHashedFields()` via `FacebookAds\Object\ServerSide\Util::hash` (SHA-256 — this is how PII like email/phone is protected),
Expand All @@ -50,7 +50,7 @@ The core abstraction is the serialization pipeline in `src/Event/Parameters.php`

So to add a field: add the public property, map it in `getMapping()`, and register it in `getNormalizedFields()`/`getHashedFields()` if Meta requires it. The lists of which fields normalize/hash mirror the corresponding `FacebookAds\Object\ServerSide\*` classes (see the `@see` annotations) — keep them in sync with that SDK.

**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.
**Two payload contexts** (the `PayloadContext` enum: `Server`, the default, and `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. `getPayload()` passes the context on to nested `Parameters`, so the browser payload of an `Event` never contains the server-only fields of its `User`. `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), `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`.

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,15 +198,15 @@ To get the best match quality Meta recommends sending events both server-side (t
the same `eventId` so they are deduplicated. `FbqGenerator` produces the matching JavaScript:

```php
use Setono\MetaConversionsApi\Event\Parameters;
use Setono\MetaConversionsApi\Event\PayloadContext;
use Setono\MetaConversionsApi\Generator\FbqGenerator;

$generator = new FbqGenerator();

// In your <head>: initialise the pixel(s) and send a PageView
echo $generator->generateInit(
$event->pixels,
$event->userData->getPayload(Parameters::PAYLOAD_CONTEXT_BROWSER),
$event->userData->getPayload(PayloadContext::Browser),
);

// Where the conversion happens: fire the same event in the browser.
Expand Down
21 changes: 21 additions & 0 deletions UPGRADE-2.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,27 @@ What to change:
- `ErrorResponse` is no longer `@internal`. Its properties are now readonly, and `ErrorResponse::fromJson()` throws
`InvalidArgumentException` instead of `ClientException`.

## The payload context is an enum

`Parameters::PAYLOAD_CONTEXT_SERVER` and `Parameters::PAYLOAD_CONTEXT_BROWSER` are replaced by the
`Setono\MetaConversionsApi\Event\PayloadContext` enum. With a string, a typo silently gave you the server payload, IP
address, user agent, `fbc` and `fbp` included, which is exactly what must not be printed into a page.

```php
// 1.x
$event->userData->getPayload(Parameters::PAYLOAD_CONTEXT_BROWSER);

// 2.0
$event->userData->getPayload(PayloadContext::Browser);
```

If you subclass `Event` and override `getMapping()`, change its signature from `getMapping(string $context)` to
`getMapping(PayloadContext $context)`. A subclass that only overrides the constructor is not affected.

The context is now also passed on to nested objects. In 1.x, `$event->getPayload(Parameters::PAYLOAD_CONTEXT_BROWSER)`
still serialized the user data in the server context. `FbqGenerator` was not affected, since it asks the user data and
the custom data directly.

## `FbqGenerator::generateTrack()` no longer throws a `\JsonException`

When the custom data cannot be encoded as JSON, it now logs an error and returns an empty string, which is what
Expand Down
2 changes: 1 addition & 1 deletion src/Event/Content.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function __construct(
$this->deliveryCategory = $deliveryCategory;
}

protected function getMapping(string $context): array
protected function getMapping(PayloadContext $context): array
{
return [
'id' => $this->id,
Expand Down
2 changes: 1 addition & 1 deletion src/Event/Custom.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ final class Custom extends Parameters
*/
public array $customProperties = [];

protected function getMapping(string $context): array
protected function getMapping(PayloadContext $context): array
{
return array_merge($this->customProperties, [
'content_category' => $this->contentCategory,
Expand Down
2 changes: 1 addition & 1 deletion src/Event/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ public static function getEvents(): array
];
}

protected function getMapping(string $context): array
protected function getMapping(PayloadContext $context): array
{
return [
'event_name' => $this->eventName,
Expand Down
19 changes: 8 additions & 11 deletions src/Event/Parameters.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,21 @@

abstract class Parameters
{
public const PAYLOAD_CONTEXT_BROWSER = 'browser';

public const PAYLOAD_CONTEXT_SERVER = 'server';

/**
* This method returns an array representation of the object ready
* to be sent to Meta/Facebook, i.e. it's both normalized and hashed
* to be sent to Meta/Facebook, i.e. it's both normalized and hashed.
* The context is passed on to the nested objects
*
* @return array<string, mixed>
*/
public function getPayload(string $context = self::PAYLOAD_CONTEXT_SERVER): array
public function getPayload(PayloadContext $context = PayloadContext::Server): array
{
// The mapping keys are field names (strings), so iterating here lets the return type stay the precise
// array<string, mixed> that consumers like FbqGenerator::generateInit() rely on. The recursive normalize()
// below works on values of unknown key type, hence it can only yield array<array-key, mixed>.
$payload = [];
foreach ($this->getMapping($context) as $field => $value) {
$payload[$field] = $value instanceof self ? $value->getPayload() : self::normalize($value, $field);
$payload[$field] = $value instanceof self ? $value->getPayload($context) : self::normalize($value, $context, $field);
}

return self::filterEmptyValues($payload);
Expand All @@ -39,7 +36,7 @@
*
* @return array<string, mixed>
*/
abstract protected function getMapping(string $context): array;
abstract protected function getMapping(PayloadContext $context): array;

/**
* Returns a list of Meta/Facebook field names that must be normalized by \FacebookAds\Object\ServerSide\Normalizer::normalize
Expand All @@ -53,7 +50,7 @@
*
* @return list<string>
*/
protected static function getHashedFields(): array

Check warning on line 53 in src/Event/Parameters.php

View workflow job for this annotation

GitHub Actions / Mutation tests (8.3, highest)

Escaped Mutant for Mutator "ProtectedVisibility": @@ @@ * * @return list<string> */ - protected static function getHashedFields(): array + private static function getHashedFields(): array { return []; }
{
return [];
}
Expand All @@ -63,7 +60,7 @@
*
* @return array<array-key, mixed>|string|float|int|bool|null
*/
private static function normalize($data, ?string $field = null)
private static function normalize($data, PayloadContext $context, ?string $field = null)
{
if (null === $data) {
return null;
Expand All @@ -78,7 +75,7 @@
}

if (is_string($data)) {
Assert::notNull($field);

Check warning on line 78 in src/Event/Parameters.php

View workflow job for this annotation

GitHub Actions / Mutation tests (8.3, highest)

Escaped Mutant for Mutator "MethodCallRemoval": @@ @@ $data = (string) $data; } if (is_string($data)) { - Assert::notNull($field); + if (in_array($field, static::getNormalizedFields(), true)) { try { $data = Normalizer::normalize($field, $data);
if (in_array($field, static::getNormalizedFields(), true)) {
try {
$data = Normalizer::normalize($field, $data);
Expand All @@ -98,14 +95,14 @@
return $data;
}

Assert::isArray($data);

Check warning on line 98 in src/Event/Parameters.php

View workflow job for this annotation

GitHub Actions / Mutation tests (8.3, highest)

Escaped Mutant for Mutator "MethodCallRemoval": @@ @@ if (is_int($data) || is_float($data) || is_bool($data)) { return $data; } - Assert::isArray($data); + /** @var mixed $datum */ foreach ($data as $key => &$datum) { if ($datum instanceof self) {

/** @var mixed $datum */
foreach ($data as $key => &$datum) {
if ($datum instanceof self) {
$datum = $datum->getPayload();
$datum = $datum->getPayload($context);
} else {
$datum = self::normalize($datum, is_string($key) ? $key : $field);
$datum = self::normalize($datum, $context, is_string($key) ? $key : $field);
}
}
unset($datum);
Expand Down
22 changes: 22 additions & 0 deletions src/Event/PayloadContext.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Setono\MetaConversionsApi\Event;

/**
* The same objects serialize differently depending on where the payload is going
*/
enum PayloadContext
{
/**
* The payload is sent to the Conversions API
*/
case Server;

/**
* The payload is rendered into a page, e.g. in an fbq() call, so it must not contain the fields
* that are only meant for the server: the IP address, the user agent, fbc and fbp
*/
case Browser;
}
4 changes: 2 additions & 2 deletions src/Event/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ final class User extends Parameters

public ?int $leadId = null;

protected function getMapping(string $context): array
protected function getMapping(PayloadContext $context): array
{
$mapping = [
'em' => $this->email,
Expand All @@ -81,7 +81,7 @@ protected function getMapping(string $context): array
'lead_id' => $this->leadId,
];

if (self::PAYLOAD_CONTEXT_BROWSER === $context) {
if (PayloadContext::Browser === $context) {
unset(
$mapping['client_ip_address'],
$mapping['client_user_agent'],
Expand Down
4 changes: 2 additions & 2 deletions src/Generator/FbqGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Setono\MetaConversionsApi\Event\Event;
use Setono\MetaConversionsApi\Event\Parameters;
use Setono\MetaConversionsApi\Event\PayloadContext;
use Setono\MetaConversionsApi\Pixel\Pixel;

final class FbqGenerator implements FbqGeneratorInterface, LoggerAwareInterface
Expand Down Expand Up @@ -58,7 +58,7 @@ public function generateInit(
public function generateTrack(Event $event, bool $includeScriptTag = true): string
{
try {
$json = json_encode($event->customData->getPayload(Parameters::PAYLOAD_CONTEXT_BROWSER), \JSON_THROW_ON_ERROR);
$json = json_encode($event->customData->getPayload(PayloadContext::Browser), \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this->logger->error($e->getMessage());

Expand Down
26 changes: 26 additions & 0 deletions tests/Event/EventTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,30 @@ public function it_prepares_a_snapshot(): void
$event->pixels[0]->accessToken = 'changed on the event';
self::assertSame('changed on the prepared event', $preparedPixel->accessToken);
}

/**
* @test
*/
public function it_passes_the_context_on_to_the_user_data(): void
{
$event = new Event(Event::EVENT_PURCHASE);
$event->userData->email[] = 'johndoe@example.com';
$event->userData->clientIpAddress = '192.168.0.1';
$event->userData->clientUserAgent = 'Chrome';
$event->userData->fbc = 'fb.1.1657051589577.ClickId';
$event->userData->fbp = 'fb.1.1656874832584.1088522659';

$hashedEmail = ['55e79200c1635b37ad31a378c39feb12f120f116625093a19bc32fff15041149'];

// the fields that are only meant for the server must not end up in a page
self::assertSame(['em' => $hashedEmail], $event->getPayload(PayloadContext::Browser)['user_data']);

self::assertSame([
'em' => $hashedEmail,
'client_ip_address' => '192.168.0.1',
'client_user_agent' => 'Chrome',
'fbc' => 'fb.1.1657051589577.ClickId',
'fbp' => 'fb.1.1656874832584.1088522659',
], $event->getPayload()['user_data']);
}
}
63 changes: 63 additions & 0 deletions tests/Event/ParametersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

declare(strict_types=1);

namespace Setono\MetaConversionsApi\Event;

use PHPUnit\Framework\TestCase;

final class ParametersTest extends TestCase
{
/**
* @test
*/
public function it_uses_the_server_context_by_default(): void
{
self::assertSame(['context' => 'Server'], (new ContextAwareParameters())->getPayload());
}

/**
* @test
*/
public function it_passes_the_context_on_to_nested_parameters(): void
{
$parameters = new ContextAwareParameters();
$parameters->child = new ContextAwareParameters();
$parameters->child->child = new ContextAwareParameters();
$parameters->children = [new ContextAwareParameters(), new ContextAwareParameters()];

self::assertSame([
'context' => 'Browser',
'child' => [
'context' => 'Browser',
'child' => ['context' => 'Browser'],
],
'children' => [
['context' => 'Browser'],
['context' => 'Browser'],
],
], $parameters->getPayload(PayloadContext::Browser));
}
}

final class ContextAwareParameters extends Parameters
{
public ?self $child = null;

/** @var list<self> */
public array $children = [];

protected function getMapping(PayloadContext $context): array
{
return [
'context' => $context->name,
'child' => $this->child,
'children' => $this->children,
];
}

protected static function getNormalizedFields(): array
{
return [];
}
}
6 changes: 3 additions & 3 deletions tests/Generator/FbqGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use PHPUnit\Framework\TestCase;
use Setono\MetaConversionsApi\Event\Event;
use Setono\MetaConversionsApi\Event\Parameters;
use Setono\MetaConversionsApi\Event\PayloadContext;
use Setono\MetaConversionsApi\Pixel\Pixel;
use Setono\MetaConversionsApi\TestLogger;

Expand All @@ -31,12 +31,12 @@ public function it_generates_init(): void
self::assertSame(<<<EXPECTED
fbq('init', '111', {"db":["cccd631dbe89ae6c982a960f248fabab8a4ae7f899853a3ea5bceef8ca1d6585"]});fbq('init', '222', {"db":["cccd631dbe89ae6c982a960f248fabab8a4ae7f899853a3ea5bceef8ca1d6585"]});fbq('track', 'PageView');
EXPECTED
, $generator->generateInit($event->pixels, $event->userData->getPayload(Parameters::PAYLOAD_CONTEXT_BROWSER), true, false));
, $generator->generateInit($event->pixels, $event->userData->getPayload(PayloadContext::Browser), true, false));

self::assertSame(<<<EXPECTED
<script>fbq('init', '111', {"db":["cccd631dbe89ae6c982a960f248fabab8a4ae7f899853a3ea5bceef8ca1d6585"]});fbq('init', '222', {"db":["cccd631dbe89ae6c982a960f248fabab8a4ae7f899853a3ea5bceef8ca1d6585"]});fbq('track', 'PageView');</script>
EXPECTED
, $generator->generateInit($event->pixels, $event->userData->getPayload(Parameters::PAYLOAD_CONTEXT_BROWSER)));
, $generator->generateInit($event->pixels, $event->userData->getPayload(PayloadContext::Browser)));
}

/**
Expand Down
Loading