Welcome to the LimeSurvey Community Forum

Ask the community, share ideas, and connect with other LimeSurvey users!

Create token on the fly

  • DenisChenu
  • DenisChenu's Avatar
  • Offline
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
6 years 7 months ago #158147 by DenisChenu
Replied by DenisChenu on 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 , plugin development .
I don't answer to private message.
The topic has been locked.
  • tpartner
  • tpartner's Avatar
  • Away
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
6 years 7 months ago - 6 years 7 months ago #158158 by tpartner
Replied by tpartner on 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

Code:
<?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']) &amp;&amp; isset($newToken[0]['token'])) {
    $newURL =  LS_BASEURL.'index.php/'.$iSurveyID.'?lang='.$language.'&amp;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:
Code:
{TEMPLATEURL}api_redirect.php?token={TOKEN:TOKEN}&amp;email={TOKEN:EMAIL}&amp;firstname={TOKEN:FIRSTNAME}&amp;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.
Last edit: 6 years 7 months ago by tpartner.
The topic has been locked.
  • DenisChenu
  • DenisChenu's Avatar
  • Offline
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
6 years 7 months ago #158161 by DenisChenu
Replied by DenisChenu on 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 , plugin development .
I don't answer to private message.
The topic has been locked.
  • badronald
  • badronald's Avatar Topic Author
  • Offline
  • Junior Member
  • Junior Member
More
6 years 7 months ago #158162 by badronald
Replied by badronald on topic Create token on the fly
Thank you. Trying it now. I really appreciate your help.
The topic has been locked.
  • badronald
  • badronald's Avatar Topic Author
  • Offline
  • Junior Member
  • Junior Member
More
6 years 7 months ago #158166 by badronald
Replied by badronald on 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
The topic has been locked.
  • badronald
  • badronald's Avatar Topic Author
  • Offline
  • Junior Member
  • Junior Member
More
6 years 7 months ago #158175 by badronald
Replied by badronald on 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?
The topic has been locked.
  • tpartner
  • tpartner's Avatar
  • Away
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
6 years 7 months ago - 6 years 7 months ago #158184 by tpartner
Replied by tpartner on 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:

Code:
<?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.'&amp;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']) &amp;&amp; isset($newToken[0]['token'])) {
      $newURL =  LS_BASEURL.'index.php/'.$iSurveyID.'?lang='.$language.'&amp;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: 6 years 7 months ago by tpartner.
The topic has been locked.
  • badronald
  • badronald's Avatar Topic Author
  • Offline
  • Junior Member
  • Junior Member
More
6 years 7 months ago #158191 by badronald
Replied by badronald on topic Create token on the fly
Thank you! Works great.
The topic has been locked.
More
5 years 11 months ago #168805 by jinformatique
Replied by jinformatique on 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?
Code:
<?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.
Code:
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) ""
}
The topic has been locked.
  • Joffm
  • Joffm's Avatar
  • Away
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
5 years 11 months ago #168808 by Joffm
Replied by Joffm on 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
Code:
$myJSONRPCClient = new \org\jsonrpcphp\JsonRPCClient(LS_BASEURL . '/admin/remotecontrol');
should be
Code:
$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
The topic has been locked.
  • tpartner
  • tpartner's Avatar
  • Away
  • LimeSurvey Community Team
  • LimeSurvey Community Team
More
5 years 11 months ago - 5 years 11 months ago #168815 by tpartner
Replied by tpartner on 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.

Code:
<?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) &amp;&amp; (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: 5 years 11 months ago by tpartner.
The topic has been locked.
More
5 years 11 months ago #168833 by jinformatique
Replied by jinformatique on 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.

Code:
<?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) &amp;&amp; (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

Code:
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:
Code:
new \org\jsonrpcphp\JsonRPCClient

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


Any ideas?
The topic has been locked.

Lime-years ahead

Online-surveys for every purse and purpose