Use PHP to query the Mimecast API

Mimecast has fairly detailed documentation and code examples for their API but nothing for PHP.

Here’s a basic PHP code example for their “Get Account” API endpoint. I used their Python sample code as a starting point. You’ll need to update the base URL and the keys to use it.

<?php

// Setup required variables
$baseUrl = 'https://xx-api.mimecast.com';
$uri = '/api/account/get-account';
$url = $baseUrl.$uri;
$accessKey = 'YOUR ACCESS KEY';
$secretKey = 'YOUR SECRET KEY';
$appId = 'YOUR APPLICATION ID';
$appKey = 'YOUR APPLICATION KEY';

// Generate request header values
$requestId = uniqid();
$hdrDate = gmdate('r');

// DataToSign is used in hmac_sha1
$dataToSign = implode(':', array($hdrDate, $requestId, $uri, $appKey));

// Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
$hmacSha1 = hash_hmac('sha1', $dataToSign, base64_decode($secretKey), true);

// Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
$sig = base64_encode($hmacSha1);

// Create request headers
$headers = array(
    'Authorization: MC '.$accessKey.':'.$sig,
    'x-mc-req-id: '.$requestId,
    'x-mc-app-id: '.$appId,
    'x-mc-date: '.$hdrDate,
    'Content-Type: application/json',
    'Accept: application/json',
);

$payload = json_encode(array('data' => array()));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

print_r(json_decode(curl_exec($ch)));

curl_close($ch);

Leave a Reply

Your email address will not be published.