Retrieving email event data with PHP and Mailgun: Troubleshooting API parameters

I’m stuck trying to fetch email events from Mailgun using their API and PHP curl. Here’s what I’ve got so far:

$eventParams = [
    'startDate' => '2023-05-01 00:00:00',
    'sortOrder' => 'asc',
    'maxResults' => 5,
    'formatOutput' => 'true',
    'targetEmail' => '[email protected]'
];

$apiRequest = curl_init();
curl_setopt_array($apiRequest, [
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    CURLOPT_USERPWD => 'api:SECRET_KEY',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_URL => 'https://api.mailgun.net/v3/mydomain.com/events',
    CURLOPT_POSTFIELDS => $eventParams
]);

$response = curl_exec($apiRequest);
curl_close($apiRequest);
$decodedResponse = json_decode($response);

The API responds with events, but it’s not respecting my parameters in $eventParams. It’s like the CURLOPT_POSTFIELDS setting is being ignored. Any ideas what I’m doing wrong here? Thanks for any help!

I’ve encountered a similar issue when working with Mailgun’s API. The problem lies in how you’re passing the parameters. For GET requests, you need to append the parameters to the URL instead of using CURLOPT_POSTFIELDS.

Try modifying your code like this:

$url = 'https://api.mailgun.net/v3/mydomain.com/events?' . http_build_query($eventParams);

curl_setopt_array($apiRequest, [
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    CURLOPT_USERPWD => 'api:SECRET_KEY',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $url
]);

This should properly include your parameters in the GET request. Also, ensure your API key and domain are correct. If you’re still having issues, double-check Mailgun’s documentation for any recent changes to their API endpoints or parameter names.

hey, i ran into this too. quick fix: ditch CURLOPT_POSTFIELDS and add params to the URL instead. like this:

$url = ‘https://api.mailgun.net/v3/mydomain.com/events?’ . http_build_query($eventParams);

curl_setopt($apiRequest, CURLOPT_URL, $url);

that should do the trick. GET requests need params in the URL, not the body. give it a shot and lemme know if it works!

I’ve dealt with this exact problem before when integrating Mailgun’s API. The issue is that you’re using CURLOPT_POSTFIELDS for a GET request, which doesn’t work as expected. Instead, you need to build the query string into the URL.

Here’s how I fixed it:

$queryString = http_build_query($eventParams);
$url = "https://api.mailgun.net/v3/mydomain.com/events?{$queryString}";

curl_setopt_array($apiRequest, [
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    CURLOPT_USERPWD => 'api:SECRET_KEY',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_URL => $url
]);

This approach ensures your parameters are properly sent with the GET request. Also, double-check that your API key has the necessary permissions to access event data. If you’re still having trouble, Mailgun’s support team is quite responsive and can help troubleshoot further.