Plugin development

From pmusers
Jump to: navigation, search

Access tokens for REST in plugins in PM 3.2.2+

To obtain an access token to be able to call REST endpoints inside a plugin, the following PHP code can be used in ProcessMaker 3.2.2 and later:

require_once PATH_CONTROLLERS . 'designer.php';
$designer = new \Designer();
$credentials = $designer->getCredentials();
$accessToken = $credentials['access_token'];
$refreshToken = $credentials['refresh_token'];

Where $credentials will be an array like the following:

array( 
   'access_token'  => '8bd11f036a5b5eb9e98eb20d8c7375e29bc05fcc', 
   'expires_in'    => 86400,
   'token_type'    => 'bearer', 
   'scope'         => 'view_processes edit_processes *', 
   'refresh_token' => '4e2b737f675a5a3a8b9a79b11ba8af40fd4e02e2', 
   'client_id'     => 'JTDKCULEFPWLSPFSWDDUVZYEBWXYPIGZ',
   'client_secret' => '3608275195c63906273a615093613817'
)

Access tokens for REST in plugins in PM 3.2.1 and earlier

If using ProcessMaker 3.2.1 or earlier, then the following PHP code can used to obtain the access token:

if (!isset($_SESSION['USER_LOGGED'])) {
	header("Location: ../login/login");
}
$userId = $_SESSION['USER_LOGGED'];
$sql = "SELECT * FROM OAUTH_REFRESH_TOKENS WHERE USER_ID='$userId' ORDER BY EXPIRES DESC";
\G::loadClass('pmFunctions');
$result = executeQuery($sql);
if (empty($result)) {
	header("Location: ../login/login");
}
	
$refreshToken = $result[1]['REFRESH_TOKEN'];

//Universal Client ID and Client Secret from workflow/engine/methods/oauth2/grant.php
$clientId = 'x-pm-local-client';
$clientSecret = '179ad45c6ce2cb97cf1029e212046e81';
$pmServer = (\G::is_https() ? 'https://' : 'http://').$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT']; 

$aVars = array(
      'grant_type'    => 'refresh_token',
      'client_id'     => $clientId,
      'client_secret' => $clientSecret,
      'refresh_token' => $refreshToken
);
 
$ch = curl_init($pmServer.'/'.SYS_SYS.'/oauth2/token');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $aVars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
$oToken = json_decode(curl_exec($ch));
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
 
if ($httpStatus != 200) {
    print "Error in HTTP status code: $httpStatus\n";
}
elseif (isset($oToken->error)) {
    print "Error logging into $pmServer:\n" .
         "Error:       {$oToken->error}\n" .
         "Description: {$oToken->description}\n";
}
else {
      $accessToken = $oToken->access_token;
      $refreshToken = $oToken->refresh_token;
		   
      //Now the access token can be used for REST calls or saved as a cookie. 
      //Save access token as a cookie that expires in 86400 seconds:
      //setcookie("access_token",  $oToken->access_token, time() + 86400);
}