Skip to content

Instantly share code, notes, and snippets.

@Radagaisus
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Radagaisus/c2ee5666a8d5ccccf10b to your computer and use it in GitHub Desktop.
Save Radagaisus/c2ee5666a8d5ccccf10b to your computer and use it in GitHub Desktop.
Captain Up User Integration - Signing a User Object in PHP
<?php
// Signs a user object with your API secret.
// See: https://captainup.com/help/javascript/user-integration
//
// @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 == '') {
unset($user[$key]);
}
}
// 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" => "https://example.com/user-profile-picture.png",
"empty" => null // Just a test, to see that empty values are removed properly
);
// Remember to use your own API secret below
// This will output:: "NzFjMWRhM2VhMDcyZDQyYzBhNGE4Yjk3MDdjNTQ0ZTU4NDg2N2EzYjc0Nzg4NmIzMjhkODA1YTJkOWFiZGY3ZjI0YzU3NGY3YjcwYzFiMGM1MzlhYzVjOGE0Mjg5ZmNkYzVhOGI0MDQyZTRkYTAzOTRlM2RjNzFmZTdmNTVkMGI"
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