TimeTrex API usage examples for PHP:
TimeTrex uses an API-first development model, therefore it offers full 100% API coverage of all actions and operations that it performs. In fact the TimeTrex web interface actually utilizes the API itself in the background, so any operation that you can do from the UI can be easily done through the API too.
To help developers get started, the TimeTrex web UI offers API tracing functionality to log the exact API requests that it sends as you navigate through it, and displays them in the web browser developer console. Therefore you can perform any action through the UI, then copy the raw API request that it uses into your own program.
To enable API tracing, simply go to the TimeTrex login screen then press CTRL+ALT+SHIFT+F11, a message should appear stating that API tracing is enabled, then bring up your web browser console by pressing F12 to view the API requests.
Additionally, basic examples are published for Postman.
See the full API manual for detailed functions and arguments.
*NOTE: If you simply need to import or export data (ie: employees, timesheets, or reports), consider the easy to use remote command line tools.
PHP Examples using the REST / JSON protocol:
To get started, you'll need to register a permanent API key/Session ID to use for all API requests. Follow these steps:
- Login to TimeTrex as the employee that the API calls will be executed as.
- In the blue header bar at the top right, click your profile to expand the Profile menu.
- Select Passwords / Security.
- Click the More (...) button at the top right of the inset page.
- Select "Register API Key".
- Take note of the provided API key/Session ID for use below.
Next define a couple helper functions to do most of the heavy lifting for us:
//Build URL given a Class and Method to call.
//Format is: http://demo.timetrex.com/api/json/api.php?Class=&Method=&SessionID=
function buildURL( $class, $method ) {
global $TIMETREX_URL;
$url = $TIMETREX_URL . '?Class=' . $class . '&Method=' . $method;
return $url;
}
//Handle complex result.
function handleResult( $result, $raw = false ) {
if ( is_array( $result ) && isset( $result['api_retval'] ) ) {
if ( $raw === true ) {
return $result;
} else {
if ( $result['api_retval'] === false ) {
if ( php_sapi_name() == 'cli' ) {
$eol = "\n";
$space = " ";
} else {
$eol = "<br>\n";
$space = "-";
}
//Display any error messages that might be returned.
$output[] = 'Returned:';
$output[] = ( $result['api_retval'] === true ) ? ' IsValid: YES' : ' IsValid: NO';
if ( $result['api_retval'] === true ) {
$output[] = ' Return Value: ' . $result['api_retval'];
} else {
$output[] = ' Code: ' . $result['api_details']['code'];
$output[] = ' Description: ' . $result['api_details']['description'];
$output[] = ' Details: ';
$details = $result['api_details']['details'];
if ( is_array( $details ) ) {
foreach ( $details as $row => $row_details ) {
if ( isset( $row_details['error'] ) ) { //When importing data, each row has its own validation object, which could contain the "error" sub-element.
$tmp_row_details = $row_details['error'];
} else {
$tmp_row_details = $row_details;
}
$output[] = ' Row: ' . $row;
foreach ( $tmp_row_details as $field => $msgs ) {
$output[] = str_repeat( $space, 2 ) .'Field: ' . $field;
foreach ( $msgs as $msg ) {
$output[] = str_repeat( $space, 4 ) .'Message: ' . $msg;
}
}
}
}
}
$output[] = '==============================================================';
$output[] = '';
echo implode( $eol, $output );
}
return $result['api_retval'];
}
}
return $result;
}
//Post data (array of arguments) to URL
function postToURL( $url, $data = null, $raw_result = false ) {
$curl_connection = curl_init();
curl_setopt( $curl_connection, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 );
curl_setopt( $curl_connection, CURLOPT_URL, $url );
curl_setopt( $curl_connection, CURLOPT_REFERER, $url ); //**IMPORTANT: Referer should always be sent to avoid requests being rejected due to CSRF security checks.
curl_setopt( $curl_connection, CURLOPT_CONNECTTIMEOUT, 600 );
curl_setopt( $curl_connection, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl_connection, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $curl_connection, CURLOPT_SSL_VERIFYHOST, false );
curl_setopt( $curl_connection, CURLOPT_FOLLOWLOCATION, 0 );
global $TIMETREX_API_KEY;
curl_setopt( $curl_connection, CURLOPT_HTTPHEADER, [ 'Cookie: SessionID='. $TIMETREX_API_KEY ] ); //Send API Key as a cookie.
//When sending JSON data to POST, it must be sent as: json=
// should be an associative array with the first level being the number of arguments, where each argument can be of mixed type. ie:
// array(
// 0 => ,
// 1 => ,
// 2 => ,
// ...
// )
echo "==============================================================\n";
echo "Posting data to URL: " . $url . "\n";
if ( $data !== null ) {
$post_data = 'json=' . urlencode( json_encode( $data ) );
curl_setopt( $curl_connection, CURLOPT_POSTFIELDS, $post_data );
echo " POST Data: " . $post_data . "\n";
}
echo "--------------------------------------------------------------\n";
$result = curl_exec( $curl_connection );
curl_close( $curl_connection );
return handleResult( json_decode( $result, true ), $raw_result );
}
Next define some global variables that point to our TimeTrex server API end-point and initialize our API Key/Session ID:
/*
Global variables
*/
$TIMETREX_URL = 'https://demo.timetrex.com/api/json/api.php';
$TIMETREX_SESSION_ID = 'API216a7c8871dfb45c43c2bc2d23f086d1ab74e0d8'; //**IMPORTANT** Use the registered API key/Session ID from above.
Our connection is setup now, lets grab an employee record by UUID:
$arguments = array( 'filter_data' => array(
'id' => '0b8030ad-7c17-4fe4-b517-63f7a221b253'
//'user_name' => 'john.doe567',
)
);
$user_data = postToURL( buildURL( 'APIUser', 'getUser' ), array( $arguments ) );
The $user_data variable will now look something like this:
Array
(
[0] => Array
(
[id] => 0b8030ad-7c17-4fe4-b517-63f7a221b253
[company_id] => 1001
[status_id] => 10
[status] => Active
[group_id] => 0
[group] =>
[user_name] => demoadmin1
[phone_id] => 12345
[phone_password] => 12345
[employee_number] => 10
[title_id] => 0
[title] =>
[default_branch_id] => 0
[default_branch] =>
[default_department_id] => e2482b34-3d0e-4d76-b66a-52c8da59bc22
[default_department] => Administration
[permission_control_id] => 8b82daba-8a35-47ed-9603-43b634cd9a3c
[permission_control] => Administrator (92) #1
[pay_period_schedule_id] => 02e42b4a-c638-4893-b936-e4614c94f400
[pay_period_schedule] => USBiWeekly
[policy_group_id] => b75ba3c3-305b-41d4-9c80-ea4eb51d39ac
[policy_group] => Default
[first_name] => Demo
[middle_name] => J
[last_name] => Admin
[second_last_name] =>
[sex_id] => 10
[sex] => MALE
[address1] => Blah
[address2] =>
[city] => Kelowna
[country] => CA
[province] => BC
[postal_code] => V4T1E3
[work_phone] => 555-555-5555
[work_phone_ext] =>
[home_phone] => 555-555-5555
[mobile_phone] => 555-555-5555
[fax_phone] =>
[home_email] => test@democo.com
[work_email] => test@democo.com
[birth_date] => 07-Nov-04
[hire_date] => 07-Nov-04
[termination_date] =>
[currency_id] => 6533a1ab-8f61-4e3c-afee-e773941359c2
[currency] => CAD
[sin] => 1XXXXX789
[note] =>
[deleted] =>
[created_by_id] => 0b8030ad-7c17-4fe4-b517-63f7a221b253
[created_by] =>
[created_date] => 08-Nov-04 11:18 AM
[updated_by_id] => 0b8030ad-7c17-4fe4-b517-63f7a221b253
[updated_by] => Demo Admin
[updated_date] => 01-Oct-08 12:49 PM
)
If you would prefer to get multiple employee records at once, you can send an array of arguments like this instead:
$arguments = array( 'filter_data' => array(
'id' => array('0b8030ad-7c17-4fe4-b517-63f7a221b253', 'c06df44c-6c59-496c-a6b3-dfba0ddb9882'),
//'user_name' => array('john.doe567', 'jane.doe890'),
)
);
Now lets update the above employee record and set their status to terminated:
$user_data[0]['status_id'] = 20; //Terminated
$user_data[0]['termination_date'] = '01-Jul-09';
$result = postToURL( buildURL( 'APIUser', 'setUser' ), array( $user_data[1] ) );
if ( $result === TRUE ) {
echo "Employee data saved successfully.\n";
} else {
echo "Employee save failed.\n";
print $result; //Show error messages
}
If you prefer to update an employee record without first getting it, just specify the 'id' field along with the ones you want to change like this:
$user_data = array(
'id' => '0b8030ad-7c17-4fe4-b517-63f7a221b253',
'termination_date' => '02-Jul-09'
);
$result = postToURL( buildURL( 'APIUser', 'setUser' ), array( $user_data ) );
if ( $result === TRUE ) {
echo "Employee data saved successfully.\n";
} else {
echo "Employee save failed.\n";
print $result; //Show error messages
}
What about adding a new employee? Just don't specify a 'id' field and TimeTrex will automatically know you want to add a new record:
$user_data = array(
'status_id' => 10, //Active
'first_name' => 'Michael',
'last_name' => 'Jackson',
'employee_number' => rand(10000, 99999),
'user_name' => 'mjackson_'. rand(10000, 99999),
'password' => 'whiteglove123',
'hire_date' => '01-Oct-09',
'currency_id' => 3,
);
$result = postToURL( buildURL( 'APIUser', 'setUser' ), array( $user_data ) );
if ( $result !== FALSE ) {
echo "Employee added successfully.\n";
$insert_id = $result; //Get employees new ID on success.
} else {
echo "Employee save failed.\n";
print $result; //Show error messages
}
Here is how we can add punches for employees:
$punch_data = array(
'user_id' => '0b8030ad-7c17-4fe4-b517-63f7a221b253',
'type_id' => 10, //Normal
'status_id' => 20, //In
'time_stamp' => strtotime('19-Aug-2013 5:50PM'),
'branch_id' => 02e42b4a-c638-4893-b936-e4614c94f400, //Branch
'department_id' => 61f27618-25a2-4b12-b9d7-bf9bc8667e11, //Department
'job_id' => d5f5773c-ce32-47e1-8930-2a78bda8cbe0, //Job
'job_item_id' => 3d15b90b-fd4a-4e9d-b9c1-a273b57da347, //Task
);
$result = postToURL( buildURL( 'APIPunch', 'setPunch' ), array( $punch_data ) );
if ( $result !== FALSE ) {
echo "Punch added successfully.\n";
$insert_id = $result; //Get employees new ID on success.
} else {
echo "Punch save failed.\n";
print $result; //Show error messages
}
Getting report data, by first getting the report config data, then downloading the data in 'raw' (array) format:
$config = postToURL( buildURL( 'APITimesheetSummaryReport', 'getTemplate' ), array( 'by_employee+regular+overtime+premium+absence' ) );
$result = postToURL( buildURL( 'APITimesheetSummaryReport', 'getTimesheetSummaryReport' ), array( $config, 'raw' ) );
echo "Report Data:\n";
var_dump($result);