Create token on the fly

More
1 year 1 month ago #158147 by DenisChenu
DenisChenu replied the topic: Create token on the fly

Assistance on LimeSurvey forum and LimeSurvey core development are on my free time.
I'm not a LimeSurvey GmbH member, professional service on demand (or search sondages pro).
An error happen ? Before make a new topic : remind the Debug mode .

Please Log in or Create an account to join the conversation.

More
1 year 1 month ago - 1 year 1 month ago #158158 by tpartner
tpartner replied the topic: Create token on the fly
@DenisChenu, I think badronald needs to create a token in a second survey.

@badronald, If you need the respondent to register for a first survey, complete it, and then use the API to create the same token in a second survey and redirect the respondent, follow these steps.

1) Add jsonRPCClient.php and jsonRPCServer.php to your template directory.

2) Add a file called api_redirect.php, containing the following code, to your template directory.
- Modify the constants in lines 5-7
- Modify $iSurveyID
- This is just a quick example so you may want to add some validation/security

<?php
 
	require_once 'jsonRPCClient.php';
 
	define( 'LS_BASEURL', 'http://path/to/LimeSurvey/');  
	define( 'LS_USER', 'admin' );
	define( 'LS_PASSWORD', 'yourPassword' );
 
	$iSurveyID = '123456'; // The ID of the second survey
	$token = $_GET["token"];
	$email = $_GET["email"];
	$FirstNameAPI =  $_GET["firstname"];
	$LastNameAPI = $_GET["lastname"];
	$language = 'en';
 
 
	// Instantiate a new RPC client
	$myJSONRPCClient = new jsonRPCClient( LS_BASEURL.'/admin/remotecontrol' );
 
	// Get a session key
	$sSessionKey= $myJSONRPCClient->get_session_key( LS_USER, LS_PASSWORD );
 
	// Define the token params
	$tokenParams = array("email"=>$email,"lastname"=>$LastNameAPI,"firstname"=>$FirstNameAPI,"token"=>$token,"language"=>$language,"emailstatus"=>"OK");
	$aParticipantData=array($tokenParams);
	$bCreateToken = false;
 
	// Create the token in survey 2
	$newToken = $myJSONRPCClient->add_participants( $sSessionKey, $iSurveyID, $aParticipantData, $bCreateToken);
 
	// Release the session key
	$myJSONRPCClient->release_session_key( $sSessionKey );
 
	// If token successfully created, redirect to survey
	if(isset($newToken[0]['tid']) && isset($newToken[0]['token'])) {
		$newURL =  LS_BASEURL.'index.php/'.$iSurveyID.'?lang='.$language.'&token='.$newToken[0]['token'];
		header('Location: '.$newURL);
		die();
	}
	// Otherwise, display errors
	else if (isset($newToken['status'])) {
		echo $newToken['status'];
	}
	else {
		echo '<br />';
		echo 'Error: '.$newToken[0]['errors']['token'][0];
	}
?>

3) Activate and initiate tokens in both surveys.

4) In Survey 1, enable "Automatically load URL when survey complete?" and insert an End URL like this:
{TEMPLATEURL}api_redirect.php?token={TOKEN:TOKEN}&email={TOKEN:EMAIL}&firstname={TOKEN:FIRSTNAME}&lastname={TOKEN:LASTNAME}

Sample template and surveys attached:

File Attachment:

File Name: API_Redire...ey_1.lss
File Size:12 KB

File Attachment:

File Name: API_Redire...ey_2.lss
File Size:13 KB

File Attachment:

File Name: Test_API_Redirect.zip
File Size:92 KB

Cheers,
Tony Partner
Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Attachments:
Last Edit: 1 year 1 month ago by tpartner.

Please Log in or Create an account to join the conversation.

More
1 year 1 month ago #158161 by DenisChenu
DenisChenu replied the topic: Create token on the fly
My english is surely lesser good than yours (and after rereading : i'm sure you're right).

Else, RC is a good idea and your code is great. Personnaly i surely make a plugin for the same purpose (in fact i already have a part of a plugin : creating token if don't exist with beforeSurveyPage event).

Assistance on LimeSurvey forum and LimeSurvey core development are on my free time.
I'm not a LimeSurvey GmbH member, professional service on demand (or search sondages pro).
An error happen ? Before make a new topic : remind the Debug mode .

Please Log in or Create an account to join the conversation.

More
1 year 1 month ago #158162 by badronald
badronald replied the topic: Create token on the fly
Thank you. Trying it now. I really appreciate your help.

Please Log in or Create an account to join the conversation.

More
1 year 1 month ago #158166 by badronald
badronald replied the topic: Create token on the fly
I am getting this error:


Fatal error: Uncaught exception 'Exception' with message 'Incorrect response id (request id: 1, response id: )' in /home/nhs2/public_html/limesurvey206/upload/templates/citronadeNHS3MOD9/jsonRPCClient.php:154 Stack trace: #0 /home/nhs2/public_html/limesurvey206/upload/templates/citronadeNHS3MOD9/api_redirect.php(21): jsonRPCClient->__call('get_session_key', Array) #1 /home/nhs2/public_html/limesurvey206/upload/templates/citronadeNHS3MOD9/api_redirect.php(21): jsonRPCClient->get_session_key('****', '****') #2 {main} thrown in /home/nhs2/public_html/limesurvey206/upload/templates/citronadeNHS3MOD9/jsonRPCClient.php on line 154

Please Log in or Create an account to join the conversation.

More
1 year 1 month ago #158175 by badronald
badronald replied the topic: Create token on the fly
I got it working. Thank you.

Any way to have it check if token exists in second survey and have it resume rather than say token already exists?

Please Log in or Create an account to join the conversation.

More
1 year 1 month ago - 1 year 1 month ago #158184 by tpartner
tpartner replied the topic: Create token on the fly
You should be able to use the list_participants() method to check for a pre-existing token something like this:

<?php
 
	require_once 'jsonRPCClient.php';
 
	define( 'LS_BASEURL', 'http://path/to/LimeSurvey/');  
	define( 'LS_USER', 'admin' );
	define( 'LS_PASSWORD', 'yourPassword' );
 
	$iSurveyID = '123456'; // The ID of the second survey
	$token = $_GET["token"];
	$email = $_GET["email"];
	$FirstNameAPI =  $_GET["firstname"];
	$LastNameAPI = $_GET["lastname"];
	$language = 'en';
 
 
	// Instantiate a new RPC client
	$myJSONRPCClient = new jsonRPCClient( LS_BASEURL.'/admin/remotecontrol' );
 
	// Get a session key
	$sSessionKey= $myJSONRPCClient->get_session_key( LS_USER, LS_PASSWORD );
 
	// Check if token already exists
	$tokenExists = false;
	$aConditions = array("completed"=>"N");
	$listParticipants = $myJSONRPCClient->list_participants($sSessionKey, $iSurveyID, 0, 100000, false, false, $aConditions);
	foreach ($listParticipants as $value) {
		if($value['token'] == $token) {
			$tokenExists = true;
		}
	}
 
	// Token already exists in survey 2, so redirect to survey
	if($tokenExists == true) {
		// Release the session key
		$myJSONRPCClient->release_session_key( $sSessionKey );
 
		// Redirect to survey
		$newURL =  LS_BASEURL.'index.php/'.$iSurveyID.'?lang='.$language.'&token='.$token;
		header('Location: '.$newURL);
		die();
	}
	// No existing token in survey 2, so we'll create one
	else {
 
		// Define the token params
		$tokenParams = array("email"=>$email,"lastname"=>$LastNameAPI,"firstname"=>$FirstNameAPI,"token"=>$token,"language"=>$language,"emailstatus"=>"OK");
		$aParticipantData=array($tokenParams);
		$bCreateToken = false;
 
		// Create the token in survey 2
		$newToken = $myJSONRPCClient->add_participants( $sSessionKey, $iSurveyID, $aParticipantData, $bCreateToken);
 
		// Release the session key
		$myJSONRPCClient->release_session_key( $sSessionKey );
 
		// If token successfully created, redirect to survey
		if(isset($newToken[0]['tid']) && isset($newToken[0]['token'])) {
			$newURL =  LS_BASEURL.'index.php/'.$iSurveyID.'?lang='.$language.'&token='.$newToken[0]['token'];
			header('Location: '.$newURL);
			die();
		}
		// Otherwise, display errors
		else if (isset($newToken['status'])) {
			echo $newToken['status'];
		}
		else {
			echo '<br />';
			echo 'Error: '.$newToken[0]['errors']['token'][0];
		}
	}
?>

Cheers,
Tony Partner
Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Last Edit: 1 year 1 month ago by tpartner.

Please Log in or Create an account to join the conversation.

More
1 year 1 month ago #158191 by badronald
badronald replied the topic: Create token on the fly
Thank you! Works great.

Please Log in or Create an account to join the conversation.

More
4 months 4 weeks ago #168805 by jinformatique
jinformatique replied the topic: Create token on the fly
Hi, I'm trying to connect to the API with limesurvey3.7.3+180516. I activated JSON-RPC in the UI.
What am I missing?
<?php
 
include_once 'vendor/autoload.php';
// include_once '/alfred/vendor/weberhofer/jsonrpcphp/src/org/jsonrpcphp/jsonRPCClient.php';
 
define('LS_BASEURL', 'https://www.fnak.fr/limesurvey/index.php');  // adjust this one to your actual LimeSurvey URL
define('LS_USER', 'user');
define('LS_PASSWORD', 'password');
 
$iSurveyID = 616685;
echo '<pre>';
// Instantiate a new RPC client
$myJSONRPCClient = new \org\jsonrpcphp\JsonRPCClient(LS_BASEURL . '/admin/remotecontrol');
var_dump($myJSONRPCClient);
// Get a session key
$sessionKey = $myJSONRPCClient->get_session_key(LS_USER, LS_PASSWORD);
var_dump($sessionKey);
 
 
// Release the session key
$myJSONRPCClient->release_session_key($sessionKey);
echo '</pre>';


Here is the result I got. It stops at the 1st var_dump and doesn't show the 2nd.
object(org\jsonrpcphp\JsonRPCClient)#3 (6) {
  ["debug":"org\jsonrpcphp\JsonRPCClient":private]=>
  bool(false)
  ["url":"org\jsonrpcphp\JsonRPCClient":private]=>
  string(60) "https://www.fnak.fr/limesurvey/index.php/admin/remotecontrol"
  ["id":"org\jsonrpcphp\JsonRPCClient":private]=>
  int(1)
  ["notification":"org\jsonrpcphp\JsonRPCClient":private]=>
  bool(false)
  ["enableCurl":"org\jsonrpcphp\JsonRPCClient":private]=>
  bool(true)
  ["proxy"]=>
  string(0) ""
}

Please Log in or Create an account to join the conversation.

More
4 months 4 weeks ago #168808 by Joffm
Joffm replied the topic: Create token on the fly
1. Did you include the jsonRPCClient by composer?

// without composer this line can be used
// require_once 'path/to/your/rpcclient/jsonRPCClient.php';
// with composer support just add the autoloader
include_once 'vendor/autoload.php';


Otherwise you have to uncomment the "require_once" and set the correct path.
And comment the "vendor/autoload.php"

2. I think this line
$myJSONRPCClient = new \org\jsonrpcphp\JsonRPCClient(LS_BASEURL . '/admin/remotecontrol');
should be
$myJSONRPCClient = new \org\jsonrpcphp\JsonRPCClient(LS_BASEURL . '/index.php/admin/remotecontrol');

Try and echo this line to see if it is correct.

Joffm


Volunteers are not paid.
Not because they are worthless, but because they are priceless

Please Log in or Create an account to join the conversation.

More
4 months 4 weeks ago - 4 months 4 weeks ago #168815 by tpartner
tpartner replied the topic: Create token on the fly
Here is a very simple example that will return the properties of survey in LS 3.x. In this case, the jsonRPCClient.php file resides in the same directory as the PHP script below.

<?php
 
	require_once 'jsonRPCClient.php';
 
	define( 'LS_BASEURL', 'http://pathTo/LimeSurvey');  
	define( 'LS_USER', 'admin' );
	define( 'LS_PASSWORD', 'password' );
 
	//$iSurveyID = $_GET['surveyID'];
	$iSurveyID = 885886;
 
 
	if(ctype_alnum($iSurveyID) && (strlen($iSurveyID) == 5 || strlen($iSurveyID) == 6)) { // Valid SID format
 
		// Instantiate a new RPC client
		$myJSONRPCClient = new jsonRPCClient( LS_BASEURL.'/index.php/admin/remotecontrol' );
 
		// Get a session key
		$sSessionKey= $myJSONRPCClient->get_session_key( LS_USER, LS_PASSWORD );
 
		if(is_array($sSessionKey)) { // Invalid session
			echo $sSessionKey['status'];
		}
		else if($sSessionKey) { // Valid session
 
			$surveyProperties = $myJSONRPCClient->get_survey_properties($sSessionKey,  $iSurveyID);
 
			foreach($surveyProperties as $key => $value) {
				echo $key . ' => ' . $value . '<br />';
			}
		}
 
		// Release the session key
		$myJSONRPCClient->release_session_key( $sSessionKey );
	}
	else { // Invalid SID format
		die( 'Invalid format!' );
	}
 
?>

Cheers,
Tony Partner
Solutions, code and workarounds presented in these forums are given without any warranty, implied or otherwise.
Last Edit: 4 months 4 weeks ago by tpartner.

Please Log in or Create an account to join the conversation.

More
4 months 4 weeks ago #168833 by jinformatique
jinformatique replied the topic: Create token on the fly
Thank you for your help. I forgot to mention that I did include the jsonRPCClient by composer.
Now I copied the file JsonRPCClient.php in the same directory.


My php file from where I do the calling is on my local computer with PHP 7.1
The limesurvey install is on a hosting with PHP 5.6. Can the error come from this setup?

I took the code from tpartner and changed the connexion values and added a var_dump.

<?php
 
require_once 'JsonRPCClient.php';
 
define('LS_BASEURL', 'https://www.fnak.fr/limesurvey');  // adjust this one to your actual LimeSurvey URL
define('LS_USER', 'user');
define('LS_PASSWORD', 'password');
 
//$iSurveyID = $_GET['surveyID'];
$iSurveyID = 616685;
 
echo '<pre>';
if (ctype_alnum($iSurveyID) && (strlen($iSurveyID) == 5 || strlen($iSurveyID) == 6)) { // Valid SID format
    // Instantiate a new RPC client
    $myJSONRPCClient = new \org\jsonrpcphp\JsonRPCClient(LS_BASEURL . '/index.php/admin/remotecontrol');
    var_dump($myJSONRPCClient);
 
    // Get a session key
    $sSessionKey = $myJSONRPCClient->get_session_key(LS_USER, LS_PASSWORD);
 
    if (is_array($sSessionKey)) { // Invalid session
        echo $sSessionKey['status'];
    } elseif ($sSessionKey) { // Valid session
        $surveyProperties = $myJSONRPCClient->get_survey_properties($sSessionKey, $iSurveyID);
 
        foreach ($surveyProperties as $key => $value) {
            echo $key . ' => ' . $value . '<br />';
        }
    }
 
    // Release the session key
    $myJSONRPCClient->release_session_key($sSessionKey);
} else { // Invalid SID format
    die('Invalid format!');
}
echo '</pre>';


So the result is still the same

object(org\jsonrpcphp\JsonRPCClient)#1 (6) {
  ["debug":"org\jsonrpcphp\JsonRPCClient":private]=>
  bool(false)
  ["url":"org\jsonrpcphp\JsonRPCClient":private]=>
  string(60) "https://www.fnak.fr/limesurvey/index.php/admin/remotecontrol"
  ["id":"org\jsonrpcphp\JsonRPCClient":private]=>
  int(1)
  ["notification":"org\jsonrpcphp\JsonRPCClient":private]=>
  bool(false)
  ["enableCurl":"org\jsonrpcphp\JsonRPCClient":private]=>
  bool(true)
  ["proxy"]=>
  string(0) ""
}


I have to do the new like this:
new \org\jsonrpcphp\JsonRPCClient

Else if I do the new like this
new JsonRPCClient(...
I got a blank page. The JsonRPCClient.php from composer is recent and uses the namespace.


Any ideas?

Please Log in or Create an account to join the conversation.

More
4 months 3 weeks ago #168900 by jinformatique
jinformatique replied the topic: Create token on the fly
Hi,
So I found out that it's because of the PHP version 5.6 of my hosting.
I installed Limesurvey locally on PHP 7.1 and this way the Json RPC is working fine.

Please Log in or Create an account to join the conversation.

Start now!

Just create your account and start using Limesurvey today.

Register now
Join our Newsletter!