Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
Captain Up User Integration - Signing a User Object in PHP
// Signs a user object with your API secret.
// See:
// @param secret - {String} Your Captain Up API secret
// @param user - {Associative Array} the user dictionary
// @return {String} the signed user string
function sign_user($secret, $user) {
// Remove all `null`, `undefined`, arrays and objects from the object
foreach($user as $key => $value) {
if(empty($value) || $value == '') {
// Sort the array alphabetically by the key names
ksort($user, SORT_LOCALE_STRING);
// Join each key-value pair with a '='...
$signed_user = array();
foreach ($user as $key => $value) {
array_push($signed_user, $key."=".$value);
// ... and join each pair with '&'
$signed_user = implode("&",$signed_user);
// Sign the serialized object with SHA-512 in lowercase hexadecimal digits
$signed_user = hash_hmac('sha512', $signed_user, $secret);
// Encode it as Base64
$signed_user = base64_encode($signed_user);
// remove new lines and and the '=' part at the end, and return
return preg_replace('/(\n|=+\n?$)/', '', $signed_user);
// Example Usage:
$user = array(
"id" => "guid-in-your-site",
"name" => "Almog Melamed",
"avatar" => "",
"empty" => null // Just a test, to see that empty values are removed properly
// Remember to use your own API secret below
echo sign_user('YOUR-API-SECRET', $user)."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment