From 35dca370f30cc37b10b2ab3be6be6df41ba86496 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:45:52 +0200 Subject: [PATCH 1/4] feat(http): per-request headers on HttpClient::request() --- src/Http/HttpClient.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Http/HttpClient.php b/src/Http/HttpClient.php index 2dd42f8..7ed3ae9 100644 --- a/src/Http/HttpClient.php +++ b/src/Http/HttpClient.php @@ -118,13 +118,19 @@ public function url(string $path, ?array $params = null): string * Send a request, retrying on 429, and return the decoded body. * * @param array|null $params + * @param array $headers extra request headers, such as Idempotency-Key */ - public function request(string $method, string $path, mixed $json = null, ?array $params = null): mixed - { + public function request( + string $method, + string $path, + mixed $json = null, + ?array $params = null, + array $headers = [], + ): mixed { $url = $this->url($path, $params); $payload = $json === null ? null : self::encode($json); - return $this->sendWithRetry($method, $url, $this->headers(), $payload); + return $this->sendWithRetry($method, $url, $headers + $this->headers(), $payload); } /** From 7f92192605898d7a6720acac4a9dac0353a4ee37 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:45:52 +0200 Subject: [PATCH 2/4] feat(ads): pixels, conversions API and custom conversions --- src/Model/AdPixel.php | 24 +++ src/Model/AdPixelDetail.php | 38 ++++ src/Model/AdPixelEventCount.php | 24 +++ src/Model/AdPixelStats.php | 31 +++ src/Model/ConversionBatch.php | 45 +++++ src/Model/ConversionBatchEvent.php | 44 +++++ src/Model/ConversionUploadResult.php | 32 ++++ src/Model/CustomConversion.php | 47 +++++ src/Model/CustomConversionRule.php | 30 +++ src/Model/EventMatchKey.php | 28 +++ src/Model/EventMatchQuality.php | 31 +++ src/Resource/AdsResource.php | 276 ++++++++++++++++++++++++++- 12 files changed, 642 insertions(+), 8 deletions(-) create mode 100644 src/Model/AdPixel.php create mode 100644 src/Model/AdPixelDetail.php create mode 100644 src/Model/AdPixelEventCount.php create mode 100644 src/Model/AdPixelStats.php create mode 100644 src/Model/ConversionBatch.php create mode 100644 src/Model/ConversionBatchEvent.php create mode 100644 src/Model/ConversionUploadResult.php create mode 100644 src/Model/CustomConversion.php create mode 100644 src/Model/CustomConversionRule.php create mode 100644 src/Model/EventMatchKey.php create mode 100644 src/Model/EventMatchQuality.php diff --git a/src/Model/AdPixel.php b/src/Model/AdPixel.php new file mode 100644 index 0000000..0c29dbf --- /dev/null +++ b/src/Model/AdPixel.php @@ -0,0 +1,24 @@ + $events */ + private function __construct( + array $raw, + public readonly string $since, + public readonly string $until, + public readonly array $events, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'since'), + self::requiredStr($data, 'until'), + AdPixelEventCount::listFrom(self::seq($data, 'events')), + ); + } +} diff --git a/src/Model/ConversionBatch.php b/src/Model/ConversionBatch.php new file mode 100644 index 0000000..b3965d9 --- /dev/null +++ b/src/Model/ConversionBatch.php @@ -0,0 +1,45 @@ + $events */ + private function __construct( + array $raw, + public readonly string $id, + public readonly string $workspaceId, + public readonly string $connectionId, + public readonly string $adAccountId, + public readonly string $pixelId, + public readonly ?string $idempotencyKey, + public readonly int $eventCount, + public readonly int $accepted, + public readonly array $events, + public readonly string $createdAt, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'id'), + self::requiredStr($data, 'workspace_id'), + self::requiredStr($data, 'connection_id'), + self::requiredStr($data, 'ad_account_id'), + self::requiredStr($data, 'pixel_id'), + self::str($data, 'idempotency_key'), + self::int($data, 'event_count') ?? 0, + self::int($data, 'accepted') ?? 0, + ConversionBatchEvent::listFrom(self::seq($data, 'events')), + self::requiredStr($data, 'created_at'), + ); + } +} diff --git a/src/Model/ConversionBatchEvent.php b/src/Model/ConversionBatchEvent.php new file mode 100644 index 0000000..295ca2c --- /dev/null +++ b/src/Model/ConversionBatchEvent.php @@ -0,0 +1,44 @@ + $matchKeys */ + private function __construct( + array $raw, + public readonly string $eventName, + public readonly ?float $score, + public readonly array $matchKeys, + ) { + parent::__construct($raw); + } + + public static function fromArray(mixed $data): static + { + $data = is_array($data) ? $data : []; + + return new self( + $data, + self::requiredStr($data, 'event_name'), + self::float($data, 'score'), + EventMatchKey::listFrom(self::seq($data, 'match_keys')), + ); + } +} diff --git a/src/Resource/AdsResource.php b/src/Resource/AdsResource.php index 830f3df..cfe0bc6 100644 --- a/src/Resource/AdsResource.php +++ b/src/Resource/AdsResource.php @@ -18,6 +18,9 @@ use Fopost\Sdk\Model\AdLibraryPage; use Fopost\Sdk\Model\AdProvider; use Fopost\Sdk\Model\AdLabel; +use Fopost\Sdk\Model\AdPixel; +use Fopost\Sdk\Model\AdPixelDetail; +use Fopost\Sdk\Model\AdPixelStats; use Fopost\Sdk\Model\AdSet; use Fopost\Sdk\Model\AdSource; use Fopost\Sdk\Model\AdStudy; @@ -26,11 +29,15 @@ use Fopost\Sdk\Model\BoostablePost; use Fopost\Sdk\Model\BidPricing; use Fopost\Sdk\Model\BulkAdStatusResult; +use Fopost\Sdk\Model\ConversionBatch; use Fopost\Sdk\Model\ConversionMetrics; use Fopost\Sdk\Model\ConversionRule; +use Fopost\Sdk\Model\ConversionUploadResult; +use Fopost\Sdk\Model\CustomConversion; use Fopost\Sdk\Model\CatalogBatchResult; use Fopost\Sdk\Model\CatalogProductsPage; use Fopost\Sdk\Model\CreatedAudience; +use Fopost\Sdk\Model\EventMatchQuality; use Fopost\Sdk\Model\ExternalAd; use Fopost\Sdk\Model\HighDemandPeriod; use Fopost\Sdk\Model\IosCampaignLimits; @@ -432,11 +439,13 @@ public function sparkPosts( } /** - * Offline conversions. Identifiers are hashed before they leave FoPost. + * Conversions API. Identifiers (email, phone, externalId) are hashed before + * they leave FoPost. Each event needs eventName and occurredAt (ISO 8601); + * eventId, actionSource, sourceUrl, clientIpAddress, clientUserAgent, + * clickId, browserId, valueMinor, currency, orderId, contentIds are optional. * * @param array> $events up to 1000 per call - * - * @return int the number the network accepted + * @param string|null $idempotencyKey replays answer `replayed` instead of sending twice */ public function uploadConversions( string $workspaceId, @@ -444,16 +453,243 @@ public function uploadConversions( string $adAccountId, string $pixelId, array $events, - ): int { - $result = self::unwrap($this->http->post('/ads/conversions', [ + ?string $idempotencyKey = null, + ): ConversionUploadResult { + return $this->postConversions( + '/ads/conversions', + $workspaceId, + $connectionId, + $adAccountId, + $pixelId, + $events, + $idempotencyKey, + ); + } + + /** + * Like uploadConversions(), but the Idempotency-Key is required: a second + * call with the same key sends nothing and answers `replayed: true`. + * + * @param array> $events up to 1000 per call + */ + public function sendConversions( + string $workspaceId, + string $connectionId, + string $adAccountId, + string $pixelId, + array $events, + string $idempotencyKey, + ): ConversionUploadResult { + return $this->postConversions( + '/ads/conversions/events', + $workspaceId, + $connectionId, + $adAccountId, + $pixelId, + $events, + $idempotencyKey, + ); + } + + /** + * Stored batches, newest first, with identifiers as hashes only. + * + * @return array + */ + public function listConversionEvents( + ?string $workspaceId = null, + ?string $connectionId = null, + ?int $limit = null, + ): array { + return ConversionBatch::listFrom(self::unwrap($this->http->get('/ads/conversions/events', [ + 'workspace_id' => $workspaceId, + 'connection_id' => $connectionId, + 'limit' => $limit, + ]))); + } + + // ── Pixels ── + + /** @return array */ + public function pixels(?string $workspaceId, string $connectionId, string $adAccountId): array + { + return AdPixel::listFrom(self::unwrap($this->http->get( + '/ads/pixels', + self::account($workspaceId, $connectionId, $adAccountId), + ))); + } + + public function createPixel( + string $workspaceId, + string $connectionId, + string $adAccountId, + string $name, + ): AdPixelDetail { + return AdPixelDetail::fromArray(self::unwrap($this->http->post('/ads/pixels', [ + 'workspaceId' => $workspaceId, + 'connectionId' => $connectionId, + 'adAccountId' => $adAccountId, + 'name' => $name, + ]))); + } + + public function pixel( + string $pixelId, + ?string $workspaceId, + string $connectionId, + string $adAccountId, + ): AdPixelDetail { + return AdPixelDetail::fromArray(self::unwrap($this->http->get( + "/ads/pixels/{$pixelId}", + self::account($workspaceId, $connectionId, $adAccountId), + ))); + } + + /** @param string|null $dataUseSetting advertising_and_analytics or analytics_only */ + public function updatePixel( + string $pixelId, + string $workspaceId, + string $connectionId, + string $adAccountId, + ?string $name = null, + ?string $dataUseSetting = null, + ): AdPixelDetail { + return AdPixelDetail::fromArray(self::unwrap($this->http->patch("/ads/pixels/{$pixelId}", self::compact([ + 'workspaceId' => $workspaceId, + 'connectionId' => $connectionId, + 'adAccountId' => $adAccountId, + 'name' => $name, + 'dataUseSetting' => $dataUseSetting, + ])))); + } + + /** Share the pixel with another ad account under the same business portfolio. */ + public function sharePixel( + string $pixelId, + string $workspaceId, + string $connectionId, + string $adAccountId, + string $targetAdAccountId, + ): void { + $this->http->post("/ads/pixels/{$pixelId}/share", [ + 'workspaceId' => $workspaceId, + 'connectionId' => $connectionId, + 'adAccountId' => $adAccountId, + 'targetAdAccountId' => $targetAdAccountId, + ]); + } + + /** Event counts over the last 28 days. */ + public function pixelStats( + string $pixelId, + ?string $workspaceId, + string $connectionId, + string $adAccountId, + ): AdPixelStats { + return AdPixelStats::fromArray(self::unwrap($this->http->get( + "/ads/pixels/{$pixelId}/stats", + self::account($workspaceId, $connectionId, $adAccountId), + ))); + } + + /** @return array */ + public function eventMatchQuality( + string $pixelId, + ?string $workspaceId, + string $connectionId, + string $adAccountId, + ): array { + return EventMatchQuality::listFrom(self::unwrap($this->http->get( + "/ads/pixels/{$pixelId}/match-quality", + self::account($workspaceId, $connectionId, $adAccountId), + ))); + } + + // ── Custom conversions ── + + /** @return array */ + public function customConversions(?string $workspaceId, string $connectionId, string $adAccountId): array + { + return CustomConversion::listFrom(self::unwrap($this->http->get( + '/ads/custom-conversions', + self::account($workspaceId, $connectionId, $adAccountId), + ))); + } + + /** + * @param string $eventType one of the network's standard types, such as PURCHASE or LEAD + * @param array $rule eventName (PageView when omitted) plus one of urlContains, urlEquals + */ + public function createCustomConversion( + string $workspaceId, + string $connectionId, + string $adAccountId, + string $pixelId, + string $name, + string $eventType, + array $rule, + ?string $description = null, + ?int $defaultValueMinor = null, + ): CustomConversion { + return CustomConversion::fromArray(self::unwrap($this->http->post('/ads/custom-conversions', self::compact([ 'workspaceId' => $workspaceId, 'connectionId' => $connectionId, 'adAccountId' => $adAccountId, 'pixelId' => $pixelId, - 'events' => $events, - ])); + 'name' => $name, + 'eventType' => $eventType, + 'rule' => $rule, + 'description' => $description, + 'defaultValueMinor' => $defaultValueMinor, + ])))); + } + + public function customConversion( + string $customConversionId, + ?string $workspaceId, + string $connectionId, + string $adAccountId, + ): CustomConversion { + return CustomConversion::fromArray(self::unwrap($this->http->get( + "/ads/custom-conversions/{$customConversionId}", + self::account($workspaceId, $connectionId, $adAccountId), + ))); + } - return is_array($result) && isset($result['accepted']) ? (int) $result['accepted'] : 0; + public function updateCustomConversion( + string $customConversionId, + string $workspaceId, + string $connectionId, + string $adAccountId, + ?string $name = null, + ?string $description = null, + ?int $defaultValueMinor = null, + ): CustomConversion { + return CustomConversion::fromArray(self::unwrap($this->http->patch( + "/ads/custom-conversions/{$customConversionId}", + self::compact([ + 'workspaceId' => $workspaceId, + 'connectionId' => $connectionId, + 'adAccountId' => $adAccountId, + 'name' => $name, + 'description' => $description, + 'defaultValueMinor' => $defaultValueMinor, + ]), + ))); + } + + /** Archives it on the network; the ids travel in the body. */ + public function deleteCustomConversion( + string $customConversionId, + string $workspaceId, + string $connectionId, + string $adAccountId, + ): void { + $this->http->delete("/ads/custom-conversions/{$customConversionId}", [ + 'workspaceId' => $workspaceId, + 'connectionId' => $connectionId, + 'adAccountId' => $adAccountId, + ]); } /** One page of an ad's comments; pass `nextCursor` back as $after. */ @@ -1926,6 +2162,30 @@ private static function scope(?string $workspaceId, string $connectionId): array return ['workspace_id' => $workspaceId, 'connection_id' => $connectionId]; } + /** @param array> $events */ + private function postConversions( + string $path, + string $workspaceId, + string $connectionId, + string $adAccountId, + string $pixelId, + array $events, + ?string $idempotencyKey, + ): ConversionUploadResult { + $body = [ + 'workspaceId' => $workspaceId, + 'connectionId' => $connectionId, + 'adAccountId' => $adAccountId, + 'pixelId' => $pixelId, + 'events' => array_values($events), + ]; + $headers = $idempotencyKey === null ? [] : ['Idempotency-Key' => $idempotencyKey]; + + return ConversionUploadResult::fromArray(self::unwrap( + $this->http->request('POST', $path, $body, null, $headers), + )); + } + private function association( string $method, string $ruleId, From 92c46add178a0cb6836bbaa1a15a74ac30798b2b Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:45:52 +0200 Subject: [PATCH 3/4] test(ads): idempotent send, pixel reads, custom conversion create --- tests/AdsTikTokTest.php | 10 +- tests/AdsTrackingTest.php | 220 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 227 insertions(+), 3 deletions(-) create mode 100644 tests/AdsTrackingTest.php diff --git a/tests/AdsTikTokTest.php b/tests/AdsTikTokTest.php index 8908b93..6be2c3b 100644 --- a/tests/AdsTikTokTest.php +++ b/tests/AdsTikTokTest.php @@ -61,14 +61,18 @@ public function testSparkPostIdAndSmartPlusTravelInTheBody(): void public function testConversionsReportWhatTheNetworkAccepted(): void { - $this->transport->push(202, ['data' => ['accepted' => 2]]); + $this->transport->push(202, [ + 'data' => ['id' => 'cb_1', 'accepted' => 2, 'eventCount' => 2, 'replayed' => false], + ]); - $accepted = $this->client()->ads()->uploadConversions('w_1', 'conn_1', '7011', 'px_1', [ + $result = $this->client()->ads()->uploadConversions('w_1', 'conn_1', '7011', 'px_1', [ ['eventName' => 'CompletePayment', 'occurredAt' => '2026-09-18T10:04:00Z'], ['eventName' => 'CompletePayment', 'occurredAt' => '2026-09-18T11:04:00Z'], ]); - $this->assertSame(2, $accepted); + $this->assertSame(2, $result->accepted); + $this->assertFalse($result->replayed); + $this->assertArrayNotHasKey('Idempotency-Key', $this->transport->last()['headers']); $this->assertSame('https://api.fopost.com/v1/ads/conversions', $this->transport->last()['url']); $this->assertSame('px_1', $this->transport->lastJson()['pixelId']); } diff --git a/tests/AdsTrackingTest.php b/tests/AdsTrackingTest.php new file mode 100644 index 0000000..e003596 --- /dev/null +++ b/tests/AdsTrackingTest.php @@ -0,0 +1,220 @@ +transport->push(202, [ + 'data' => ['id' => 'cb_1', 'accepted' => 1, 'eventCount' => 1, 'replayed' => false], + ]); + $result = $this->client()->ads()->sendConversions('w_1', 'conn_1', 'act_1', 'px_1', [[ + 'eventName' => 'Purchase', + 'occurredAt' => '2026-10-18T10:04:00Z', + 'eventId' => 'order_77', + 'actionSource' => 'website', + 'email' => 'buyer@example.test', + 'valueMinor' => 4999, + 'currency' => 'USD', + ]], 'order_77'); + + $this->assertSame('cb_1', $result->id); + $this->assertSame(1, $result->accepted); + $this->assertFalse($result->replayed); + $request = $this->transport->last(); + $this->assertSame('https://api.fopost.com/v1/ads/conversions/events', $request['url']); + $this->assertSame('order_77', $request['headers']['Idempotency-Key']); + $this->assertSame('fop_test_key', $request['headers']['X-API-Key']); + $this->assertSame('order_77', $this->transport->lastJson()['events'][0]['eventId']); + + $this->transport->push( + 202, + ['data' => ['id' => 'cb_1', 'accepted' => 1, 'eventCount' => 1, 'replayed' => true]], + ['idempotency-replayed' => 'true'], + ); + $replay = $this->client()->ads()->sendConversions('w_1', 'conn_1', 'act_1', 'px_1', [[ + 'eventName' => 'Purchase', + 'occurredAt' => '2026-10-18T10:04:00Z', + ]], 'order_77'); + $this->assertTrue($replay->replayed); + + $this->transport->push(202, [ + 'data' => ['id' => 'cb_2', 'accepted' => 1, 'eventCount' => 1, 'replayed' => false], + ]); + $this->client()->ads()->uploadConversions('w_1', 'conn_1', 'act_1', 'px_1', [[ + 'eventName' => 'Lead', + 'occurredAt' => '2026-10-18T10:04:00Z', + ]], 'lead_3'); + $this->assertSame('lead_3', $this->transport->last()['headers']['Idempotency-Key']); + $this->assertSame('https://api.fopost.com/v1/ads/conversions', $this->transport->last()['url']); + } + + public function testStoredBatchesKeepIdentifiersAsHashes(): void + { + $this->transport->push(200, ['data' => [[ + 'id' => 'cb_1', + 'workspaceId' => 'w_1', + 'connectionId' => 'conn_1', + 'adAccountId' => 'act_1', + 'pixelId' => 'px_1', + 'idempotencyKey' => 'order_77', + 'eventCount' => 1, + 'accepted' => 1, + 'events' => [[ + 'eventName' => 'Purchase', + 'occurredAt' => '2026-10-18T10:04:00Z', + 'eventId' => 'order_77', + 'actionSource' => 'website', + 'emailHash' => 'ab12', + 'phoneHash' => null, + 'externalIdHash' => null, + 'valueMinor' => 4999, + 'currency' => 'USD', + 'orderId' => null, + ]], + 'createdAt' => '2026-10-18T10:04:01Z', + ]]]); + $batches = $this->client()->ads()->listConversionEvents('w_1', 'conn_1', 10); + + $this->assertSame('order_77', $batches[0]->idempotencyKey); + $this->assertSame('ab12', $batches[0]->events[0]->emailHash); + $this->assertNull($batches[0]->events[0]->phoneHash); + $this->assertSame(4999, $batches[0]->events[0]->valueMinor); + $this->assertSame( + 'https://api.fopost.com/v1/ads/conversions/events?workspace_id=w_1&connection_id=conn_1&limit=10', + $this->transport->last()['url'], + ); + } + + public function testPixelReadsCarryTheAccountOnTheQueryString(): void + { + $this->transport->push(200, ['data' => [['id' => 'px_1', 'name' => 'Site']]]); + $pixels = $this->client()->ads()->pixels('w_1', 'conn_1', 'act_1'); + $this->assertSame('Site', $pixels[0]->name); + $this->assertSame( + 'https://api.fopost.com/v1/ads/pixels?workspace_id=w_1&connection_id=conn_1&ad_account_id=act_1', + $this->transport->last()['url'], + ); + + $this->transport->push(200, ['data' => [ + 'id' => 'px_1', + 'name' => 'Site', + 'code' => '', + 'createdAt' => '2026-01-01T00:00:00Z', + 'lastFiredAt' => null, + 'isUnavailable' => false, + 'dataUseSetting' => 'advertising_and_analytics', + ]]); + $pixel = $this->client()->ads()->pixel('px_1', 'w_1', 'conn_1', 'act_1'); + $this->assertSame('', $pixel->code); + $this->assertSame('advertising_and_analytics', $pixel->dataUseSetting); + $this->assertFalse($pixel->isUnavailable); + $this->assertNull($pixel->lastFiredAt); + $this->assertStringContainsString('/ads/pixels/px_1?workspace_id=w_1', $this->transport->last()['url']); + + $this->transport->push(200, ['data' => [ + 'since' => '2026-09-20', + 'until' => '2026-10-18', + 'events' => [['eventName' => 'PageView', 'count' => 120]], + ]]); + $stats = $this->client()->ads()->pixelStats('px_1', 'w_1', 'conn_1', 'act_1'); + $this->assertSame(120, $stats->events[0]->count); + $this->assertStringContainsString('/ads/pixels/px_1/stats?', $this->transport->last()['url']); + + $this->transport->push(200, ['data' => [[ + 'eventName' => 'Purchase', + 'score' => 6.5, + 'matchKeys' => [['identifier' => 'em', 'coveragePercent' => 80]], + ]]]); + $quality = $this->client()->ads()->eventMatchQuality('px_1', 'w_1', 'conn_1', 'act_1'); + $this->assertSame(6.5, $quality[0]->score); + $this->assertSame(80.0, $quality[0]->matchKeys[0]->coveragePercent); + $this->assertStringContainsString('/ads/pixels/px_1/match-quality?', $this->transport->last()['url']); + } + + public function testPixelWrites(): void + { + $this->transport->push(201, ['data' => ['id' => 'px_2', 'name' => 'Shop', 'isUnavailable' => false]]); + $created = $this->client()->ads()->createPixel('w_1', 'conn_1', 'act_1', 'Shop'); + $this->assertSame('px_2', $created->id); + $this->assertSame('Shop', $this->transport->lastJson()['name']); + + $this->transport->push(200, [ + 'data' => ['id' => 'px_2', 'name' => 'Shop', 'dataUseSetting' => 'analytics_only'], + ]); + $this->client()->ads()->updatePixel('px_2', 'w_1', 'conn_1', 'act_1', dataUseSetting: 'analytics_only'); + $this->assertSame('PATCH', $this->transport->last()['method']); + $this->assertArrayNotHasKey('name', $this->transport->lastJson()); + $this->assertSame('analytics_only', $this->transport->lastJson()['dataUseSetting']); + + $this->transport->push(204, null); + $this->client()->ads()->sharePixel('px_2', 'w_1', 'conn_1', 'act_1', 'act_2'); + $this->assertSame('https://api.fopost.com/v1/ads/pixels/px_2/share', $this->transport->last()['url']); + $this->assertSame('act_2', $this->transport->lastJson()['targetAdAccountId']); + } + + public function testCustomConversionCreateSendsTheRuleAndReadsItBack(): void + { + $this->transport->push(201, ['data' => [ + 'id' => 'cc_1', + 'name' => 'Checkout', + 'pixelId' => 'px_1', + 'eventType' => 'PURCHASE', + 'rule' => ['eventName' => 'PageView', 'urlContains' => '/thank-you'], + 'description' => null, + 'defaultValueMinor' => 2500, + 'isArchived' => false, + 'isUnavailable' => false, + 'createdAt' => '2026-10-18T10:00:00Z', + 'lastFiredAt' => null, + ]]); + $conversion = $this->client()->ads()->createCustomConversion( + 'w_1', + 'conn_1', + 'act_1', + 'px_1', + 'Checkout', + 'PURCHASE', + ['urlContains' => '/thank-you'], + defaultValueMinor: 2500, + ); + + $this->assertSame('cc_1', $conversion->id); + $this->assertSame('PURCHASE', $conversion->eventType); + $this->assertSame('/thank-you', $conversion->rule?->urlContains); + $this->assertNull($conversion->rule?->urlEquals); + $this->assertSame(2500, $conversion->defaultValueMinor); + $this->assertFalse($conversion->isArchived); + $body = $this->transport->lastJson(); + $this->assertSame('https://api.fopost.com/v1/ads/custom-conversions', $this->transport->last()['url']); + $this->assertSame(['urlContains' => '/thank-you'], $body['rule']); + $this->assertArrayNotHasKey('description', $body); + + $this->transport->push(200, [ + 'data' => [['id' => 'cc_1', 'name' => 'Checkout', 'eventType' => 'PURCHASE', 'rule' => null]], + ]); + $list = $this->client()->ads()->customConversions('w_1', 'conn_1', 'act_1'); + $this->assertNull($list[0]->rule); + $this->assertStringContainsString('/ads/custom-conversions?workspace_id=w_1', $this->transport->last()['url']); + + $this->transport->push(200, ['data' => ['id' => 'cc_1', 'name' => 'Checkout', 'eventType' => 'PURCHASE']]); + $this->client()->ads()->customConversion('cc_1', 'w_1', 'conn_1', 'act_1'); + $this->assertStringContainsString('/ads/custom-conversions/cc_1?', $this->transport->last()['url']); + + $this->transport->push(200, ['data' => ['id' => 'cc_1', 'name' => 'Checkout 2', 'eventType' => 'PURCHASE']]); + $updated = $this->client()->ads()->updateCustomConversion('cc_1', 'w_1', 'conn_1', 'act_1', name: 'Checkout 2'); + $this->assertSame('Checkout 2', $updated->name); + $this->assertSame( + ['workspaceId', 'connectionId', 'adAccountId', 'name'], + array_keys($this->transport->lastJson()), + ); + + $this->transport->push(204, null); + $this->client()->ads()->deleteCustomConversion('cc_1', 'w_1', 'conn_1', 'act_1'); + $this->assertSame('DELETE', $this->transport->last()['method']); + $this->assertSame('act_1', $this->transport->lastJson()['adAccountId']); + } +} From 142d301d9aaaa8432a14c779e539fc2267229a82 Mon Sep 17 00:00:00 2001 From: Ali Hesari Date: Sun, 18 Oct 2026 20:45:52 +0200 Subject: [PATCH 4/4] docs: ads tracking in README, CHANGELOG and CLAUDE.md --- CHANGELOG.md | 23 +++++++++++++++++++++++ CLAUDE.md | 7 ++++++- README.md | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b198668..6e6eff8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,29 @@ All notable changes to `fopost/sdk` are documented here. +## Unreleased + +### Changed + +- **Breaking:** `$client->ads()->uploadConversions()` returns a `ConversionUploadResult` + (`id`, `accepted`, `eventCount`, `replayed`) instead of the accepted count, and takes an + optional `$idempotencyKey` sent as the `Idempotency-Key` header. Each event also accepts + `eventId`, `actionSource`, `sourceUrl`, `externalId`, `clientIpAddress`, `clientUserAgent`, + `clickId`, `browserId` and `contentIds`. +- `HttpClient::request()` takes a fifth `$headers` argument merged over the defaults. + +### Added + +- `$client->ads()->sendConversions()` posts to `/ads/conversions/events` with a required + `Idempotency-Key`; a replay answers `replayed: true`. `listConversionEvents()` reads the + stored batches as `ConversionBatch` rows whose events carry identifiers as hashes only. +- Pixels: `pixels()`, `createPixel()`, `pixel()`, `updatePixel()`, `sharePixel()`, + `pixelStats()` and `eventMatchQuality()`, with `AdPixel`, `AdPixelDetail`, `AdPixelStats`, + `AdPixelEventCount`, `EventMatchQuality` and `EventMatchKey`. +- Custom conversions: `customConversions()`, `createCustomConversion()`, `customConversion()`, + `updateCustomConversion()` and `deleteCustomConversion()`, with `CustomConversion` and + `CustomConversionRule`. + ## 0.3.0 - 2026-10-18 ### Removed diff --git a/CLAUDE.md b/CLAUDE.md index 5a3056a..f3b0d15 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -69,6 +69,8 @@ src/ LeadForm.php LeadFormSource.php Lead.php LeadsPage.php LeadFormDetail.php FeedLead.php LeadsFeedPage.php LeadPage.php AdAccountTree.php AdCampaign.php AdSet.php NetworkAd.php AdCreative.php BulkAdStatusResult.php AdInsightsReport.php InsightsMetrics.php InsightsRow.php ReachEstimate.php + AdPixel.php AdPixelDetail.php AdPixelStats.php AdPixelEventCount.php EventMatchQuality.php EventMatchKey.php + ConversionUploadResult.php ConversionBatch.php ConversionBatchEvent.php CustomConversion.php CustomConversionRule.php PostValidation.php LengthValidation.php MediaValidation.php (+ per-platform rows, ValidationSignal) Exception/ FopostException.php ErrorFactory.php + one subclass per status @@ -117,7 +119,10 @@ is added. connections (+ Meta authorize), sources, boost, create, refresh, status, delete, audiences, targeting search, lead forms and leads, plus the campaign tree (campaigns, ad sets, network ads, duplicate, bulk status), creatives, audience detail and users, reach, insights, and the stored leads - feed with Page subscriptions. `boost()`, `create()`, `setStatus()`, `delete()`, `bulkSetStatus()` and + feed with Page subscriptions, plus pixels (`pixels`, `createPixel`, `pixel`, `updatePixel`, `sharePixel`, + `pixelStats`, `eventMatchQuality`), the Conversions API (`uploadConversions`, `sendConversions` with a required + `Idempotency-Key`, `listConversionEvents`) and custom conversions. `sendConversionEvents()` is the older + LinkedIn conversion-rule send, hence the different name. `boost()`, `create()`, `setStatus()`, `delete()`, `bulkSetStatus()` and every campaign, ad set and network ad write also need the `publish` scope, and anything created starts paused unless `paused` is `false`. Campaign-tree objects take Meta ids plus `connection_id` and are read live. An empty update or duplicate body goes out as `{}` because the API rejects none. Request diff --git a/README.md b/README.md index 6a2ad3c..adb52a0 100644 --- a/README.md +++ b/README.md @@ -631,6 +631,44 @@ $client->ads()->sendConversionEvents($ruleId, $workspaceId, $connectionId, $even $page = $client->ads()->adLibrary($workspaceId, $connectionId, keyword: 'crm', countries: ['US']); ``` +### Pixels, the Conversions API and custom conversions + +Every call needs the `ads` scope. Amounts are minor units; email, phone and externalId are +hashed before they leave FoPost and stored only as hashes. + +```php +$pixels = $client->ads()->pixels($workspaceId, $connectionId, $adAccountId); // AdPixel[] +$pixel = $client->ads()->createPixel($workspaceId, $connectionId, $adAccountId, 'Site'); // ->code is the install script +$client->ads()->updatePixel($pixel->id, $workspaceId, $connectionId, $adAccountId, dataUseSetting: 'analytics_only'); +$client->ads()->sharePixel($pixel->id, $workspaceId, $connectionId, $adAccountId, $otherAdAccountId); +$stats = $client->ads()->pixelStats($pixel->id, $workspaceId, $connectionId, $adAccountId); // last 28 days +$quality = $client->ads()->eventMatchQuality($pixel->id, $workspaceId, $connectionId, $adAccountId); // score out of 10 + +$events = [[ + 'eventName' => 'Purchase', + 'occurredAt' => '2026-10-18T10:04:00Z', + 'eventId' => 'order_77', // dedupes a browser and server pair + 'actionSource' => 'website', + 'email' => 'buyer@example.test', + 'valueMinor' => 4999, + 'currency' => 'USD', +]]; +// Idempotency-Key required: a repeat with the same key sends nothing and answers replayed = true. +$result = $client->ads()->sendConversions($workspaceId, $connectionId, $adAccountId, $pixel->id, $events, 'order_77'); +$result->accepted; $result->replayed; +// The older upload keeps working; the key is optional there. +$client->ads()->uploadConversions($workspaceId, $connectionId, $adAccountId, $pixel->id, $events); +$batches = $client->ads()->listConversionEvents($workspaceId, $connectionId, limit: 20); // ConversionBatch[] + +$conversion = $client->ads()->createCustomConversion( + $workspaceId, $connectionId, $adAccountId, $pixel->id, 'Checkout', 'PURCHASE', + ['urlContains' => '/thank-you'], defaultValueMinor: 2500, +); +$client->ads()->customConversions($workspaceId, $connectionId, $adAccountId); +$client->ads()->updateCustomConversion($conversion->id, $workspaceId, $connectionId, $adAccountId, name: 'Checkout 2'); +$client->ads()->deleteCustomConversion($conversion->id, $workspaceId, $connectionId, $adAccountId); +``` + ### Audiences, reach and insights ```php