Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active October 30, 2016 17:40
Show Gist options
  • Save surferxo3/5a0e0fadb57d1b4ab1f9688af2004aae to your computer and use it in GitHub Desktop.
Save surferxo3/5a0e0fadb57d1b4ab1f9688af2004aae to your computer and use it in GitHub Desktop.
A class to consume Emarsys API. Demonstrates the use of Web Services Security (WS-Security, WSS).
<?php
/*
* Developer: Mohammad Sharaf Ali
* Version: 1.0
* Description: Class to consume Emarsys Api. Documentation: http://documentation.emarsys.com/resource/developers/endpoints/
* Dated: 30-10-2016
*/
namespace MSharaf;
class MEmarsys
{
private $username;
private $secret;
private $suiteApiUrl;
public function __construct($username, $secret, $suiteApiUrl = 'https://api.emarsys.net/api/v2/')
{
$this->username = $username;
$this->secret = $secret;
$this->suiteApiUrl = $suiteApiUrl;
}
public function encodeData($data)
{
#return data as plain (without unicodes)
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
private function initCurlRequest($reqType, $reqURL, $reqBody = '')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $reqURL);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $reqType);
curl_setopt($ch, CURLOPT_POSTFIELDS, $reqBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
$this->prepareWSSEHeader(),
'Content-type: application/json;charset="utf-8"',
'Content-Length: '. strlen($reqBody)));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
private function prepareWSSEHeader()
{
/* Solution from: https://gist.github.com/borisguery/3792855 (not working)
$nonce = hash_hmac('sha512', uniqid(null, true), uniqid(), true);
$timestamp = new \DateTime('now', new \DateTimezone('UTC'));
$timestamp = $timestamp->format(\DateTime::ISO8601);
$passwordDigest = sha1($nonce. $timestamp. $this->secret, true);
$nonce = base64_encode($nonce);
$passwordDigest = base64_encode($passwordDigest);
*/
$nonce = 'd36e316282959a9ed4c89851497a717f';
$timestamp = gmdate('c');
$passwordDigest = base64_encode(sha1($nonce. $timestamp. $this->secret, false));
$wsseHeader =
'X-WSSE: UsernameToken '.
'Username="'. $this->username. '", '.
'PasswordDigest="'. $passwordDigest. '", '.
'Nonce="'. $nonce. '", '.
'Created="'. $timestamp. '"';
return $wsseHeader;
}
public function send($requestType, $endPoint, $requestBody = '')
{
if (!in_array($requestType, array('GET', 'POST', 'PUT', 'DELETE'))) {
throw new Exception('Send first parameter must be "GET", "POST", "PUT" or "DELETE"');
}
$reqURL = $this->suiteApiUrl. $endPoint;
return $this->initCurlRequest($requestType, $reqURL, $requestBody);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment