In this example we'll show you how can you implement recognition of your subscribers in WordPress as regular customers in LiveAgent. As result, your subscribers can visit LiveAgent Knowledgebase and see their own tickets and interact with them.
Goal:
Each subscriber will be registered also in LiveAgent with his email. As result, after login in WordPress he can move freely to LiveAgent Knowledgebase and play with his tickets.
Requirements:
- your WordPress installation and your LiveAgent installation are on the same domain. For example shop.mydomain.com and support.mydomain.com
WordPress plugin code:
<?php
/*
Plugin Name: LiveAgent example
Plugin URI: https://www.qualityunit.com/liveagent
Description: Example 3 - How to authenticate subscriber from Wordpress into LiveAgent (on the same domain) as registered visitor
Author: QualityUnit
Version: 1.0.0
Author URI: https://www.qualityunit.com
License: GPL2
*/
if (!class_exists('liveAgentExampleThree')) {
class liveAgentExampleThree
{
const LIVEAGENT_URL = 'https://mysupport.exmple.com/';
const API_KEY = '2afeca3e74c8c8ff60fed782053ec44a';
//we will use login/logout wordpress hooks
public function __construct()
{
add_action('wp_login', array(
$this,
'handleLogin'
));
add_action('wp_logout', array(
$this,
'handleLogout'
));
add_action('user_register', array(
$this,
'handleSignup'
));
}
public function handleLogin($login)
{
$user = get_user_by('login', $login);
if ($user == null) {
return;
}
if (!in_array('subscriber', $user->roles)) {
//in case i'm not subscriber - end
return;
}
$laUser = $this->getVisitorInfo($user->get('user_email'));
if ($laUser == null) {
return;
}
/* if I retrive valid response from LiveAgent, I can register "remember me" cookie.
* Wordpress and LiveAgent are on the same domain so one cookie is enough
*/
setcookie($laUser->browsercookiename, $laUser->authtoken, time() + 60 * 60 * 24 * 356, '/');
}
public function handleSignup($user_id)
{
//let's load newly created user
$user = new WP_User($user_id);
//fill all basic fields - you can find more in complete API reference here: https://support.qualityunit.com/840770-Complete-API-reference
$data = array(
'role' => 'R',
'name' => $user->user_firstname . ' ' . $user->user_lastname,
'email' => $user->user_email,
'apikey' => self::API_KEY
);
//we will create POST call to customers entity
$ch = curl_init(self::LIVEAGENT_URL . 'api/customers');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
//here we can handle error result
}
public function handleLogout()
{
$user = wp_get_current_user();
if ($user == null) {
return;
}
if (!in_array('subscriber', $user->roles)) {
return;
}
$laUser = $this->getVisitorInfo($user->get('user_email'));
if ($laUser == null) {
return;
}
//on logout we must destrou our "remember me" cookie and also our session cookie from LiveAgent.
setcookie($laUser->browsercookiename, '', time() - 3600, '/');
setcookie('visitor_la_sid', '', time() - 3600, '/');
}
private function getVisitorInfo($visitorEmail)
{
//here we use entity customers
$ch = curl_init(self::LIVEAGENT_URL . 'api/customers/' . $visitorEmail . '&apikey=' . self::API_KEY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$rawResult = curl_exec($ch);
if (!$rawResult) {
return null;
}
$result = json_decode($rawResult);
if (!isset($result->response)) {
return null;
}
if (isset($result->response) && isset($result->response->statuscode) && $result->response->statuscode != 0) {
return null;
}
return $result->response;
}
}
}
$liveagent = new liveAgentExampleThree();
?>
/*
Plugin Name: LiveAgent example
Plugin URI: https://www.qualityunit.com/liveagent
Description: Example 3 - How to authenticate subscriber from Wordpress into LiveAgent (on the same domain) as registered visitor
Author: QualityUnit
Version: 1.0.0
Author URI: https://www.qualityunit.com
License: GPL2
*/
if (!class_exists('liveAgentExampleThree')) {
class liveAgentExampleThree
{
const LIVEAGENT_URL = 'https://mysupport.exmple.com/';
const API_KEY = '2afeca3e74c8c8ff60fed782053ec44a';
//we will use login/logout wordpress hooks
public function __construct()
{
add_action('wp_login', array(
$this,
'handleLogin'
));
add_action('wp_logout', array(
$this,
'handleLogout'
));
add_action('user_register', array(
$this,
'handleSignup'
));
}
public function handleLogin($login)
{
$user = get_user_by('login', $login);
if ($user == null) {
return;
}
if (!in_array('subscriber', $user->roles)) {
//in case i'm not subscriber - end
return;
}
$laUser = $this->getVisitorInfo($user->get('user_email'));
if ($laUser == null) {
return;
}
/* if I retrive valid response from LiveAgent, I can register "remember me" cookie.
* Wordpress and LiveAgent are on the same domain so one cookie is enough
*/
setcookie($laUser->browsercookiename, $laUser->authtoken, time() + 60 * 60 * 24 * 356, '/');
}
public function handleSignup($user_id)
{
//let's load newly created user
$user = new WP_User($user_id);
//fill all basic fields - you can find more in complete API reference here: https://support.qualityunit.com/840770-Complete-API-reference
$data = array(
'role' => 'R',
'name' => $user->user_firstname . ' ' . $user->user_lastname,
'email' => $user->user_email,
'apikey' => self::API_KEY
);
//we will create POST call to customers entity
$ch = curl_init(self::LIVEAGENT_URL . 'api/customers');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
//here we can handle error result
}
public function handleLogout()
{
$user = wp_get_current_user();
if ($user == null) {
return;
}
if (!in_array('subscriber', $user->roles)) {
return;
}
$laUser = $this->getVisitorInfo($user->get('user_email'));
if ($laUser == null) {
return;
}
//on logout we must destrou our "remember me" cookie and also our session cookie from LiveAgent.
setcookie($laUser->browsercookiename, '', time() - 3600, '/');
setcookie('visitor_la_sid', '', time() - 3600, '/');
}
private function getVisitorInfo($visitorEmail)
{
//here we use entity customers
$ch = curl_init(self::LIVEAGENT_URL . 'api/customers/' . $visitorEmail . '&apikey=' . self::API_KEY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$rawResult = curl_exec($ch);
if (!$rawResult) {
return null;
}
$result = json_decode($rawResult);
if (!isset($result->response)) {
return null;
}
if (isset($result->response) && isset($result->response->statuscode) && $result->response->statuscode != 0) {
return null;
}
return $result->response;
}
}
}
$liveagent = new liveAgentExampleThree();
?>
Explanation
Most interesting is the method getVisitorInfo. We will ask about specific visitor entity from all customers in LiveAgent: .../customers/specific_visitor@email
$ch = curl_init(self::LIVEAGENT_URL . 'api/?handler=' . 'customers/' . $visitorEmail . '&k=' . self::API_KEY);
We use another API call in handleSignup method, but we must prepare POST data first:
$data = array(
'role' => 'R',
'name' => $user->user_firstname . ' ' . $user->user_lastname,
'email' => $user->user_email,
'apikey' => self::API_KEY
);
$ch = curl_init(self::LIVEAGENT_URL . 'api/customers');
And now we can launch and handle POST request:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
Note: Do not forget to attach apikey to all your API requests.
You can fond out more about this call (complete syntax, mandatory ans optional fields and example results in XML and JSON format) in our API reference.
My LiveAgent and my WordPress are on different domain. What then?
If your two installations are on completely different domains, then above example wont work. You need to extend it a bit. You need to put authentication cookie from your WordPress domain to your LiveAgent domain.
LiveAgent has mechanism for this using JavaScript and frames. Security here is guarantied by sending only security hash through iFrame. Only registered LiveAgent user can be successfully logged in. You must provide his authentication cookie and his email. Also you need setup SSO API key, in your AgentPanel. Let's see this process in extended WordPress example plugin code:
<?php
/*
Plugin Name: LiveAgent example Two
Plugin URI: https://www.qualityunit.com/liveagent
Description: Example 2 - How to authenticate subscriber from Wordpress into LiveAgent (on different domain) as registered visitor
Author: QualityUnit
Version: 1.0.1
Author URI: https://www.qualityunit.com
License: GPL2
*/
if (!class_exists('liveAgentExampleTwo')) {
class liveAgentExampleTwo
{
const LIVEAGENT_URL = 'https://mysupport.exmple.com/';
const API_KEY = '4a46eb8373c39a8d70d496a94b53fe89';
const SSO_KEY = 'a48c6a5d8d70d496a94b5d2a2cfe2a4a';
//processing of the auth - we need to run JavaScript code
public function processAuth()
{
/* we will use LiveAgent standard tracking code
* note: if you already have LiveAgent button on your page, you won't need this peace of code. Just make sure
* that rest of it is above your button code (so trackjs.php can fully load)
*/
echo '<script type="text/javascript" id="la_x2s6df8d" src="'.self::LIVEAGENT_URL.'scripts/track.js"></script>';
$actions = get_option('la_actions');
if ($actions == null) {
return;
}
//now bit magic - we process all actions in queue.
foreach ($actions as $action) {
//if we have logout action here then proceed
if ($action['action'] == 'logout') {
$user = get_user_by('login', $action['user']);
$result = $this->logoutVisitor($user);
if ($result === true) {
$this->clearAction('logout', $action['user']);
break;
}
}
if ($action['action'] == 'login') {
//if we have login action here, lets be sure its really me
$user = wp_get_current_user();
if ($action['user'] != $user->get('user_login')) {
continue;
}
$result = $this->loginVisitor($user);
if ($result === true) {
$this->clearAction('login', $user->get('user_login'));
break;
}
}
}
}
//clear actions queue
private function clearAction($actionName, $login)
{
$actions = get_option('la_actions');
$clearedActions = array();
foreach ($actions as $key => $action) {
if ($action['user'] = !$login && $action['action'] == $actionName) {
$clearedActions[] = $actions[$key];
}
}
update_option('la_actions', $clearedActions);
}
private function createMagicHash($userEmail, $userAuthToken)
{
return md5($userEmail . $userAuthToken . self::SSO_KEY);
}
//logout JavaScript
private function logoutVisitor($user)
{
//load visitor info
$visitorInfo = $this->getVisitorInfo($user->get('user_email'));
//create magic hash
$hash = $this->createMagicHash($user->get('user_email'), $visitorInfo->authtoken);
//call logout function from our tracking JavaScript
echo '<script type="text/javascript">
LiveAgentTracker.logoutUserOnServer(\'' . $hash . '\');
</script>';
return true;
}
//login JavaScript
private function loginVisitor($user)
{
//load visitor info
$visitorInfo = $this->getVisitorInfo($user->get('user_email'));
//create magic hash
$hash = $this->createMagicHash($user->get('user_email'), $visitorInfo->authtoken);
//call login function from our tracking JavaScript
echo '<script type="text/javascript">
LiveAgentTracker.loginUserOnServer(\'' . $hash . '\');
</script>';
return true;
}
//add new action to action queue
private function addAction($actionName, $login)
{
$actions = get_option('la_actions');
if ($actions == null) {
$actions = array();
}
$actions[] = array(
'action' => $actionName,
'user' => $login
);
update_option('la_actions', $actions);
}
//WP login hook
public function handleLogin($login)
{
$user = get_user_by('login', $login);
if ($user == null) {
return;
}
if (!in_array('subscriber', $user->roles)) {
return;
}
$this->addAction('login', $login);
}
//WP logout hook
public function handleLogout()
{
$user = wp_get_current_user();
$this->addAction('logout', $user->get('user_login'));
}
//API call for getting visitor info
private function getVisitorInfo($visitorEmail)
{
//here we use entity customers
$ch = curl_init(self::LIVEAGENT_URL . 'api/?handler=' . 'customers/' . $visitorEmail . '&apikey=' . self::API_KEY);
/*
Plugin Name: LiveAgent example Two
Plugin URI: https://www.qualityunit.com/liveagent
Description: Example 2 - How to authenticate subscriber from Wordpress into LiveAgent (on different domain) as registered visitor
Author: QualityUnit
Version: 1.0.1
Author URI: https://www.qualityunit.com
License: GPL2
*/
if (!class_exists('liveAgentExampleTwo')) {
class liveAgentExampleTwo
{
const LIVEAGENT_URL = 'https://mysupport.exmple.com/';
const API_KEY = '4a46eb8373c39a8d70d496a94b53fe89';
const SSO_KEY = 'a48c6a5d8d70d496a94b5d2a2cfe2a4a';
//processing of the auth - we need to run JavaScript code
public function processAuth()
{
/* we will use LiveAgent standard tracking code
* note: if you already have LiveAgent button on your page, you won't need this peace of code. Just make sure
* that rest of it is above your button code (so trackjs.php can fully load)
*/
echo '<script type="text/javascript" id="la_x2s6df8d" src="'.self::LIVEAGENT_URL.'scripts/track.js"></script>';
$actions = get_option('la_actions');
if ($actions == null) {
return;
}
//now bit magic - we process all actions in queue.
foreach ($actions as $action) {
//if we have logout action here then proceed
if ($action['action'] == 'logout') {
$user = get_user_by('login', $action['user']);
$result = $this->logoutVisitor($user);
if ($result === true) {
$this->clearAction('logout', $action['user']);
break;
}
}
if ($action['action'] == 'login') {
//if we have login action here, lets be sure its really me
$user = wp_get_current_user();
if ($action['user'] != $user->get('user_login')) {
continue;
}
$result = $this->loginVisitor($user);
if ($result === true) {
$this->clearAction('login', $user->get('user_login'));
break;
}
}
}
}
//clear actions queue
private function clearAction($actionName, $login)
{
$actions = get_option('la_actions');
$clearedActions = array();
foreach ($actions as $key => $action) {
if ($action['user'] = !$login && $action['action'] == $actionName) {
$clearedActions[] = $actions[$key];
}
}
update_option('la_actions', $clearedActions);
}
private function createMagicHash($userEmail, $userAuthToken)
{
return md5($userEmail . $userAuthToken . self::SSO_KEY);
}
//logout JavaScript
private function logoutVisitor($user)
{
//load visitor info
$visitorInfo = $this->getVisitorInfo($user->get('user_email'));
//create magic hash
$hash = $this->createMagicHash($user->get('user_email'), $visitorInfo->authtoken);
//call logout function from our tracking JavaScript
echo '<script type="text/javascript">
LiveAgentTracker.logoutUserOnServer(\'' . $hash . '\');
</script>';
return true;
}
//login JavaScript
private function loginVisitor($user)
{
//load visitor info
$visitorInfo = $this->getVisitorInfo($user->get('user_email'));
//create magic hash
$hash = $this->createMagicHash($user->get('user_email'), $visitorInfo->authtoken);
//call login function from our tracking JavaScript
echo '<script type="text/javascript">
LiveAgentTracker.loginUserOnServer(\'' . $hash . '\');
</script>';
return true;
}
//add new action to action queue
private function addAction($actionName, $login)
{
$actions = get_option('la_actions');
if ($actions == null) {
$actions = array();
}
$actions[] = array(
'action' => $actionName,
'user' => $login
);
update_option('la_actions', $actions);
}
//WP login hook
public function handleLogin($login)
{
$user = get_user_by('login', $login);
if ($user == null) {
return;
}
if (!in_array('subscriber', $user->roles)) {
return;
}
$this->addAction('login', $login);
}
//WP logout hook
public function handleLogout()
{
$user = wp_get_current_user();
$this->addAction('logout', $user->get('user_login'));
}
//API call for getting visitor info
private function getVisitorInfo($visitorEmail)
{
//here we use entity customers
$ch = curl_init(self::LIVEAGENT_URL . 'api/?handler=' . 'customers/' . $visitorEmail . '&apikey=' . self::API_KEY);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$rawResult = curl_exec($ch);
if (!$rawResult) {
$rawResult = curl_exec($ch);
if (!$rawResult) {
echo '<!-- Could not load visitor info: cURL error: '.curl_error($ch).'-->';
return null;
}
$result = json_decode($rawResult);
if (!isset($result->response)) {
return null;
}
if (isset($result->response) && isset($result->response->statuscode) && $result->response->statuscode != 0) {
return null;
}
return $result->response;
}
/*
* WordPress stuff
*/
public function settingsInit()
{
register_setting('la_general', 'la_actions');
}
public function __construct()
{
add_action('admin_init', array(
$this,
'settingsInit'
));
add_action('wp_login', array(
$this,
'handleLogin'
));
add_action('wp_logout', array(
$this,
'handleLogout'
));
add_action('wp_footer', array(
$this,
'processAuth'
), 99);
add_filter('admin_footer_text', array(
$this,
'processAuth'
), 99);
add_filter('logout_url', array(
$this,
'logoutUrl'
));
}
//we need to redirect used after logout right to main page
public function logoutUrl($logout_url)
{
$redir = get_option('siteurl');
return $logout_url . '&redirect_to=' . urlencode($redir);
}
}
}
$liveagent = new liveAgentExampleTwo();
?>
return null;
}
$result = json_decode($rawResult);
if (!isset($result->response)) {
return null;
}
if (isset($result->response) && isset($result->response->statuscode) && $result->response->statuscode != 0) {
return null;
}
return $result->response;
}
/*
* WordPress stuff
*/
public function settingsInit()
{
register_setting('la_general', 'la_actions');
}
public function __construct()
{
add_action('admin_init', array(
$this,
'settingsInit'
));
add_action('wp_login', array(
$this,
'handleLogin'
));
add_action('wp_logout', array(
$this,
'handleLogout'
));
add_action('wp_footer', array(
$this,
'processAuth'
), 99);
add_filter('admin_footer_text', array(
$this,
'processAuth'
), 99);
add_filter('logout_url', array(
$this,
'logoutUrl'
));
}
//we need to redirect used after logout right to main page
public function logoutUrl($logout_url)
{
$redir = get_option('siteurl');
return $logout_url . '&redirect_to=' . urlencode($redir);
}
}
}
$liveagent = new liveAgentExampleTwo();
?>
Explanation
Basically, we need to run JavaScript code (to write auth cookie to another domain) after login/logout in WordPress.
That is bit complicated, and can not be done directly so we created actions queue. Just after login/logout we add action to this queue.
When user Is redirected finally to some WordPress page (or admin panel) we will check this action queue and login (or logout) user to (from) another domain.
We use LiveAgent tracker javascript code to perform login/logout actions:
<script type="text/javascript" id="la_x2s6df8d" src="https://mysupport.exmple.com/scripts/track.js"></script>
Note: If you already have LiveAgent button on your page you don't need this because the code is already there. Just make sure that login/logout javascript calls are bellow your button code.
Login and logout JavaScript code:
<script type="text/javascript">
LiveAgentTracker.loginUserOnServer('magic_hash');
</script>
<script type="text/javascript">
LiveAgentTracker.logoutUserOnServer('magic_hash');
</script>
Magic hash here is an MD5 hash of user email, user auth token and your SSO key - see createMagicHash method in the example above.
NOTE: If you are testing this with your localhost installation of WordPress please make sure your cURL is set to use a certificate (as the communication with the API is through HTTPS).