From e6a33ed852378a86724ee490b8e1780efe60bdb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joachim=20L=C3=B8vgaard?= Date: Mon, 21 Sep 2026 14:47:30 +0200 Subject: [PATCH] Make the payload context an enum and pass it on to nested objects The context was a string with two constants on Parameters. A typo such as getPayload('brwoser') did not fail: it silently returned the server payload, IP address, user agent, fbc and fbp included, which is exactly what must not be printed into a page by FbqGenerator::generateInit(). PayloadContext is an enum with the cases Server and Browser. getPayload() and getMapping() take it instead of a string, and the two constants are gone. The context is now also passed on to nested Parameters. Before, $event->getPayload(BROWSER) still serialized the user data in the server context. It never showed, because FbqGenerator asks the user data and the custom data directly. Subclasses of Event that override getMapping() have to change its signature. See UPGRADE-2.0.md. --- CLAUDE.md | 4 +- README.md | 4 +- UPGRADE-2.0.md | 21 ++++++++++ src/Event/Content.php | 2 +- src/Event/Custom.php | 2 +- src/Event/Event.php | 2 +- src/Event/Parameters.php | 19 ++++----- src/Event/PayloadContext.php | 22 ++++++++++ src/Event/User.php | 4 +- src/Generator/FbqGenerator.php | 4 +- tests/Event/EventTest.php | 26 ++++++++++++ tests/Event/ParametersTest.php | 63 ++++++++++++++++++++++++++++ tests/Generator/FbqGeneratorTest.php | 6 +-- 13 files changed, 154 insertions(+), 25 deletions(-) create mode 100644 src/Event/PayloadContext.php create mode 100644 tests/Event/ParametersTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 72db8d3..512658b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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), @@ -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`. diff --git a/README.md b/README.md index 2063ae9..3190cca 100644 --- a/README.md +++ b/README.md @@ -198,7 +198,7 @@ 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(); @@ -206,7 +206,7 @@ $generator = new FbqGenerator(); // In your : 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. diff --git a/UPGRADE-2.0.md b/UPGRADE-2.0.md index f684e18..c365e36 100644 --- a/UPGRADE-2.0.md +++ b/UPGRADE-2.0.md @@ -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 diff --git a/src/Event/Content.php b/src/Event/Content.php index e1e6407..d5350a6 100644 --- a/src/Event/Content.php +++ b/src/Event/Content.php @@ -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, diff --git a/src/Event/Custom.php b/src/Event/Custom.php index afcf854..da332fd 100644 --- a/src/Event/Custom.php +++ b/src/Event/Custom.php @@ -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, diff --git a/src/Event/Event.php b/src/Event/Event.php index c32a5a9..9f964d8 100644 --- a/src/Event/Event.php +++ b/src/Event/Event.php @@ -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, diff --git a/src/Event/Parameters.php b/src/Event/Parameters.php index dddf770..d7796b8 100644 --- a/src/Event/Parameters.php +++ b/src/Event/Parameters.php @@ -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 */ - 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 that consumers like FbqGenerator::generateInit() rely on. The recursive normalize() // below works on values of unknown key type, hence it can only yield array. $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); @@ -39,7 +36,7 @@ public function getPayload(string $context = self::PAYLOAD_CONTEXT_SERVER): arra * * @return array */ - 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 @@ -63,7 +60,7 @@ protected static function getHashedFields(): array * * @return array|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; @@ -103,9 +100,9 @@ private static function normalize($data, ?string $field = null) /** @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); diff --git a/src/Event/PayloadContext.php b/src/Event/PayloadContext.php new file mode 100644 index 0000000..ffbc8fc --- /dev/null +++ b/src/Event/PayloadContext.php @@ -0,0 +1,22 @@ + $this->email, @@ -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'], diff --git a/src/Generator/FbqGenerator.php b/src/Generator/FbqGenerator.php index 6a38651..f929c78 100644 --- a/src/Generator/FbqGenerator.php +++ b/src/Generator/FbqGenerator.php @@ -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 @@ -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()); diff --git a/tests/Event/EventTest.php b/tests/Event/EventTest.php index 33fc719..3b62625 100644 --- a/tests/Event/EventTest.php +++ b/tests/Event/EventTest.php @@ -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']); + } } diff --git a/tests/Event/ParametersTest.php b/tests/Event/ParametersTest.php new file mode 100644 index 0000000..3fd465a --- /dev/null +++ b/tests/Event/ParametersTest.php @@ -0,0 +1,63 @@ + '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 */ + 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 []; + } +} diff --git a/tests/Generator/FbqGeneratorTest.php b/tests/Generator/FbqGeneratorTest.php index c24c769..520beb8 100644 --- a/tests/Generator/FbqGeneratorTest.php +++ b/tests/Generator/FbqGeneratorTest.php @@ -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; @@ -31,12 +31,12 @@ public function it_generates_init(): void self::assertSame(<<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(<<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))); + , $generator->generateInit($event->pixels, $event->userData->getPayload(PayloadContext::Browser))); } /**