Created
August 26, 2023 09:15
-
-
Save nguyen-tam/a158bfb45d36c449bd73d29c4370178d to your computer and use it in GitHub Desktop.
Postmarkapp open tracking example in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Define Postmark API endpoint, token | |
$baseEndpoint = "https://api.postmarkapp.com/messages/outbound/opens"; | |
$serverToken = "YOUR_TOKEN"; // Replace with your actual server token | |
$headers = [ | |
"Accept: application/json", | |
"X-Postmark-Server-Token: $serverToken" | |
]; | |
$offset = 0; | |
$count = 500; // Maximum allowed by Postmark API | |
$results = []; | |
$totalCount = 0; | |
do { | |
// Set up the parameters for your query | |
$params = [ | |
"count" => $count, | |
"offset" => $offset | |
]; | |
// Construct the full endpoint with parameters | |
$endpoint = $baseEndpoint . "?" . http_build_query($params); | |
// Set up the cURL request | |
$ch = curl_init($endpoint); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); | |
// Execute the request | |
$response = curl_exec($ch); | |
// Error handling | |
if (curl_errno($ch)) { | |
echo 'Error:' . curl_error($ch); | |
exit; | |
} | |
// Parse the response | |
$data = json_decode($response); | |
// Check the total count | |
if (!$totalCount) { | |
$totalCount = $data->TotalCount; | |
} | |
// Extract the required data and group by MessageStream | |
foreach ($data->Opens as $open) { | |
$key = $open->MessageStream; | |
$results[$key][] = [ | |
'MessageID' => $open->MessageID, | |
'MessageStream' => $open->MessageStream, | |
'Recipient' => $open->Recipient | |
]; | |
} | |
$offset += $count; | |
} while ($offset < $totalCount); | |
// Close the cURL session | |
curl_close($ch); | |
// Output the grouped results | |
echo json_encode($results, JSON_PRETTY_PRINT); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment