2. PHP implementation
This is a self contained example. You can also use the postalsys/emailengine-php Composer library to generate the authentication URL (look for the get_authentication_url
method).
<?php
// "Service secret" value from the Service configuration page
$service_secret = 'a23da152f5b88543f52420a0de0e0eb6';
// URL to EmailEngine
$email_engine_base_url = 'http://127.0.0.1:3000/';
$account_data = array(
// optional account ID, autogenerated if not set
'account' => 'account_id',
// optional name of the user, can be changed by the user
'name' => 'Full Name',
// optional email address of the user, can be changed by the user
'email' => 'user@example.com',
// required URL where to redirect once account has been added
'redirectUrl' => 'https://my.app.example.com/account/added',
);
/**
* Encode a string value into the url-safe base64 encoding
* @param {String} $val Value to be encoded
* @return {String} Url-safe base64 encoded value
*/
function base64_encode_urlsafe($val)
{
return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($val));
}
/**
* Decode a url-safe base64 encoded value to a binary string
* @param {String} $val Url-safe base64 encoded value
* @return {String} Decoded string value
*/
function base64_decode_urlsafe($val)
{
$data = str_replace(array('-', '_'), array('+', '/'), $val);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
/**
* Sign a value
* @param {String} $value String value to be signed
* @param {String} $secret Service secret
* @return {String} url-safe base64 encoded signature
*/
function sign_request($val, $secret)
{
$hmac = hash_hmac("sha256", $val, $secret, true);
return base64_encode_urlsafe($hmac);
}
/**
* Build the hosted authentication form URL
* @param {String} $baseUrl Base URL for EmailEngine
* @param {Object} $data Account data to be signed
* @param {String} $secret Service secret
* @return {String} URL to hosted authentication page
*/
function get_authentication_url($email_engine_base_url, $data, $secret)
{
$data_json = json_encode($data);
$signature = sign_request($data_json, $secret);
return preg_replace('{/$}', '', $email_engine_base_url) .
'/accounts/new?data=' . base64_encode_urlsafe($data_json) . '&sig=' . ($signature);
}
// Form URL is now ready to be used
echo get_authentication_url($email_engine_base_url, $account_data, $service_secret);
echo "\n";