当前位置: 首页 > 工具软件 > ProcessMaker > 使用案例 >

电子表单DynaForm访问ProcessMaker REST API

包沈义
2023-12-01

电子表单DynaForm访问ProcessMaker REST API 获取登录用户ID

通过DynaForm的javscript访问ProcessMaker REST API 获取登录用户ID。

1 、运行环境

  • ProcessMaker 版本 :3.2.2 社区版
  • workspace:workflow
  • 操作系统:Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018 x86_64 x86_64 x86_64 GNU/Linu

2、操作步骤

2-1、登记访问REST API外部程序,获取Client ID和Client secret

参考OAuth 2.0登记访问REST API外部程序,获取:

  • Client ID: HWAYUEGWRMWNVLSTKPXAJDZGUQKAXKSF
  • Client secret: 28060566356f0b9db4f0429090515303

2-2、编写访问REST API的通用函数pmRestRequest

pmRestRequest用到两个子程序:

  • cookie获取access_token,getCookie(name)
  • 取访问REST API的access_token,并设置到cookie中:pmRestLogin()

pmRestRequest执行的结果放在两个外部变量中:

  • oResponse,返回的结果,已被JSON.parse(),可直接使用
  • httpStatus,HTTP返回的状态码

函数pmRestRequest(method, endpoint, asynchronous, oVars, func)代码:

//JavaScript pmRestRequest() Function
//The best way to avoid code duplication is to create a generic JavaScript function called pmRestRequest() 
//that can handle ProcessMaker REST requests. 
//This function will set the HTTP headers depending on the HTTP method and 
//then execute the call using XMLHttpRequest(). If an error occurs, it will display the error to the user.

var pmServer = "http://xx.xx.xx.xx"; //set to IP address of ProcessMaker server
 
//Global variables set by synchronous call to last REST endpoint:
var oResponse  = null; //response object returned by REST endpoint and decoded with JSON.parse():
var httpStatus = null; //HTTP status code of call to REST endpoint
 
/*function to call a ProcessMaker endpoint. If a synchronous call, it sets the global variables 
httpStatus to the HTTP status code and oResponse to the decoded JSON response string. 
Parameters:
 method:        HTTP method: "GET", "POST", "PUT" or "DELETE"
 endpoint:      The PM endpoint, not including the server's address and port number. 
                Ex: "/api/1.0/workflow/cases"
 asynchronous:  Optional. Set to true if asynchronous request. If false (the default value), then
                processing waits until the HTTP request completes, which means the browser freezes.
 oVars:         Optional. Object containing variables to use in the request if "POST" or "PUT" method.
 func:          Optional. Custom function to be called after the endpoint request, whose first parameter 
                is the response object and the second parameter is the HTTP status code. */
function pmRestRequest(method, endpoint, asynchronous, oVars, func) {
   console.log('pmRestRequest(method, endpoint, asynchronous, oVars, func) called');
   //set optional parameters:
   asynchronous = (typeof asynchronous === 'undefined') ? false : asynchronous;
   oParams      = (typeof oParams === 'undefined')      ? null  : oParams;
   func         = (typeof func === 'undefined')         ? null  : func;
 
   while (!getCookie("access_token")) {
       pmRestLogin();
   }  
 
   if (typeof XMLHttpRequest != "undefined") {
      var req = new XMLHttpRequest();
   }
   else { 
      try {  //for IE 5, 5.5 & 6:
         var req = new ActiveXObject("Microsoft.XMLHTTP"); 
      }
      catch (e) {
         alert ("Error: This browser does not support XMLHttpRequest.");
         return;
      } 
   } 
 
   req.open(method, pmServer + endpoint, asynchronous);
   req.setRequestHeader("Authorization", "Bearer " + getCookie("access_token"));
   sVars = null;
   method = method.toUpperCase().trim();
 
   switch (method) {
      case "GET":
      case "DELETE":
         break;
      case "PUT":
         //URL encode the values of any variables in oVars:
         if (oVars) {
            for (var v in oVars) {
               if (oVars.hasOwnProperty(v)) 
                  oVars[v] = encodeURIComponent(oVars[v]);
            }
         }    
      case "POST":
         var sVars = JSON.stringify(oVars);   
         req.setRequestHeader('Content-type','application/json; charset=utf-8');
         req.setRequestHeader('Content-length', sVars.length); 
         break;
      default:
         alert("Error: Invalid HTTP method '" + url + "'.");
         return;
   }
 
   req.onreadystatechange = function() {
      if (req.readyState == 4) { //the request is completed
         var status = req.status;
         var oResp = null;
 
         if (req.responseText) {
            //use JSON.parse() to decode response text if the web browser supports it:
            oResp = (JSON) ? JSON.parse(req.responseText) : eval(req.responseText);
         }
 
         if (!asynchronous) {
            httpStatus = status;
            oResponse = oResp;
         }
         if (status == 401) {
            window.location.href = "login.html";
            return;
         }
         else if (oResp && oResp.error) {
            var msg = "Error code: " + oResp.error.code + "\nMessage: " + oResp.error.message;
            alert(msg);
            //throw error if wanting to handle it:
            //throw new Error(msg);
         }
         else if (status != 200 && status != 201) {  
            alert("HTTP status error: " + req.status);
            //throw error if wanting to handle it:
            //throw new Error("HTTP status error: " + req.status);
         }
 
         if (func) {  //call custom function to handle response:
            func(oResp, status);      
         }
      }
   };
 
   if (asynchronous) {
      req.timeout   = 20000;   //timeout after 20 seconds
      req.ontimeout = function() { alert("Timed out calling " + $endpoint); };
   }
   req.send(sVars);
}

函数getCookie(name)代码:

//function to read cookie by name. If it returns false, then the cookie doesn't exist.
//if it returns "", then the cookie exists, but has no value.
function getCookie(name) {
   function escape(s) { 
      return s.replace(/([.*+?\^${}()|\[\]\/\\])/g, '\\$1'); 
   };
   var match = document.cookie.match(RegExp('(?:^|;\\s*)' + escape(name) + '=([^;]*)'));
   return match ? match[1] : null;
}

函数pmRestLogin()代码:

function pmRestLogin() {
   console.log('pmRestLogin() called');
   //change to the address and workspace of your ProcessMaker server: 
   var restServer = "http://xx.xx.xx.xx/workflow/";
 
   var jqxhr = $.ajax({
      async: false,
      type: "POST",
      url:  restServer + "oauth2/token",
      dataType: 'json',
      // insecure example of data to obtain access token and login:
      data: {
         grant_type   : 'password',
         scope        : '*',
         client_id    : 'JOQGBLFCGNGGFIWUEVWXUBCLDYLHDQWN',
         client_secret: '1710959485b5726f80b9575005124487',
         username     : 'admin',
         password     : 'xxxxxxxx'         
      }
   })
   .done( function(data) { 
      if (data.error) {
         alert("Error in login!\nError: " + data.error + "\nDescription: " + data.error_description);
      }
      else if (data.access_token) {
         //Can call REST endpoints here using the data.access_token.
 
         //To call REST endpoints later, save the access_token and refresh_token
         //as cookies that expire in one hour     
         var d = new Date();
         d.setTime(d.getTime() + 24*60*60*1000);
         document.cookie = "access_token="  + data.access_token  + "; expires=" + d.toUTCString();
         document.cookie = "refresh_token=" + data.refresh_token; //refresh token doesn't expire
         console.log('access_token = ' + data.access_token);
         console.log('refresh_token = ' + data.refresh_token);
      }
      else {
         alert(JSON.stringify(data, null, 4)); //for debug
      } 
   })
   .fail(function(data, statusText, xhr) {
      alert("Failed to connect.\nHTTP status code: " + xhr.status + ' ' + statusText);
   });
}

2-3、编写获取登录用户ID函数pmGetLoggedInUserId() 

函数pmGetLoggedInUserId() 代码:

//获取当前登录用户ID
function pmGetLoggedInUserId() {
  console.log('pmGetLoggedInUserId() called');
  pmRestRequest('GET', '/api/1.0/workflow/loggeduserid', false); 
  var sUserId = null;
  if (httpStatus == 200 && oResponse) {
    sUserId = oResponse.id;
    console.log('loggeduserid = ' + sUserId);
  } else {
    console.log('loggeduserid = ' + 'null');
  }
  return sUserId;
}

2-4、运行函数pmGetLoggedInUserId() ,获取登录用户ID 

将pmGetLoggedInUserId()设为为在电子表单DyanForm装载之后运行:

$("form").first().attr("onload", pmGetLoggedInUserId);

如果以系统安装时创建的管理员用户admin登录,那么获取的登录用户ID是:

loggeduserid = 00000000000000000000000000000001

3、通过前端电子表单DynaForm访问定制开发的REST API,获得登录用户ID

通过前后端的配合,我们获得了ProcessMaker电子表单DynaForm和后端REST API 的全部能力,可以用于开发超级酷的流程管理系统。

参考资料:

 类似资料: