Home > PHP Framework > ThinkPHP > body text

tp5 uses DingTalk for workflow approval

发呆的路
Release: 2020-05-07 14:55:56
Original
6659 people have browsed it

In the development process of various management platforms, approval is an unavoidable problem. Approval issues must not only consider technical implementation, but also consider the frequency of use and ease of use by users. If a company using software uses DingTalk for approval and assessment, the approval management system can be considered to be directly connected to DingTalk. Without further ado, let’s get straight into the implementation process.

DingTalk permission settings

Create an application. If you are not doing outsourcing business, just choose internal development of the company. Select the mini program and fill in the steps

tp5 uses DingTalk for workflow approvaltp5 uses DingTalk for workflow approval

It is worth noting that you need to fill in the legal IP address as the service address. This address will be used in your post request and callback request

tp5 uses DingTalk for workflow approval

After the creation is successful, you can set up a secure domain name and activate the required interface permissions. DingTalk includes advanced permissions for micro-applications. It depends on your development needs, so I won’t go into details.

tp5 uses DingTalk for workflow approval

Acquisition of ACCESS_TOKEN

After your applet is created, you can view the AppKey and AppSecret, and we can easily obtain them using curl's get request. to ACCESS_TOKEN. ACCESS_TOKEN is valid for 7200 seconds and can be used as server cache to reduce repeated requests.

  /**
    * 钉钉access_token获取
    * @param  
    * @return access_token
    */
    public static function getAccessToken(){
        if(empty(cache('dd_access_token'))){
            $AppKey = config('ding_app_key');
            $AppSecret = config('ding_app_secret');
            $url = "https://oapi.dingtalk.com/gettoken?appkey=".$AppKey."&appsecret=".$AppSecret;
            $re = file_get_contents($url);
            $obj=json_decode($re);
            //dump($obj);
            $access_token = $obj->access_token;
            cache('dd_access_token', $access_token,7200);
        }else{
            $access_token = cache('dd_access_token');
        }
        return $access_token;
    }
Copy after login

Initiate approval

Before initiating the approval flow, we need to go to the DingTalk workbench to create a new approval

tp5 uses DingTalk for workflow approval

The approval content follows the process It prompts you to complete the form and fill in the approval process. This process can also be completed directly by relying on DingTalk's development interface. Friends in need can learn from DingTalk's development documentation. After the creation is completed, you can obtain the two key information of the approval processCode and corpId in the URL, which are used for background operations of the approval.

tp5 uses DingTalk for workflow approval

Create a post request for DingTalk approval as follows,

 public function index()
    {
        $access_token = ApiService::getAccessToken();
        //通过审批创建的url获得
        $data['process_code'] = 'PROC-VFYJYF2V-84X3UYTT455XP7KENI603-0EWMMGTJ-I';
        $data['originator_user_id'] = '093208556229304103';
        //部门id
        $data['dept_id'] = '105672100';
        $form_component_values=array();
        $form_component_values[]=['name'=>'单行输入框','value'=>'123']
        $form_component_values[]=['name'=>['开始时间','结束时间'],'value'=>['2019-02-19','2019-02-25']];
        $form_component_values[]=['name'=>'图片','value'=>['http://pic.58pic.com/58pic/15/68/59/71X58PICNjx_1024.jpg','http://img.juimg.com/tuku/yulantu/140218/330598-14021R23A410.jpg']];
        $data['form_component_values'] = $form_component_values;
        $data= json_encode($data);
        $timeout = 5000;
        $http_header = [
                'Content-Type: application/json;'
        ];
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $token);
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt ($ch, CURLOPT_HEADER, false);
        curl_setopt ($ch, CURLOPT_HTTPHEADER,$http_header);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        if (false === $result) {
            $result =  curl_errno($ch);
        }
        curl_close($ch);
        return $result;
    }
Copy after login

form (form_component_values) pay attention to the

form control It adopts the form of key/value, where key is the name corresponding to each control, and value can be an ordinary string or a json string. http_header selects 'Content-Type: application/json;' When you need to fill in the department, you can use DingTalk's own department drop-down component and pass the department id (dept_id) by value. You can use the get department id interface to obtain it

Callback changes

Configuring and writing callback interfaces is an important method to achieve synchronization of local data and DingTalk approval data. You must return to registration to use it. When registering the event callback interface, the DingTalk server will initiate a POST request to the URL (the URL that receives the callback) set when you "register the callback interface" to test the legitimacy of the URL. After receiving the message, you need to return the encrypted json data of the string "success", otherwise the DingTalk server will think that the URL is illegal. The actual implementation will be mentioned later.

    /**
    * 注册回调
    * 
    * @param  
    * @return 
    */
    public static function register_call_back(){
        $token = config('ding_token');
        $aes_key = config('ding_aes_key');
        //获取access_token
        $token = self::getAccessToken();
        //注册url
        $url = "https://oapi.dingtalk.com/call_back/register_call_back?access_token=".$token;
        // call_back_tag:需要注册的内容
        // token:加解密需要用到的token,自定义
        // aes_key:数据加密密钥。用于回调数据的加密,长度固定为43个字符,从a-z, A-Z, 0-9共62个字符中选取,您可以随机生成
        // url:你本地的回调地址,必须是可以外网访问
        $data = array('call_back_tag'=>['bpms_task_change','bpms_instance_change'],'token'=> $token,'aes_key'=> $aes_key,'url'=>config('ding_callback'));
        return self::curl_post($url,$data);
    } 
类似的,你还可以进行回调地址注册的查询和内容
    /**
    * 查询回调
    * 
    * @param  
    * @return 
    */
    public static function get_call_back(){
        $token = self::getAccessToken();
        $url = "https://oapi.dingtalk.com/call_back/get_call_back?access_token=".$token;
        $re = file_get_contents($url);
        return $re;
    } 
    /**
    * 更新回调
    * 
    * @param  
    * @return 
    */
    public static function update_call_back(){
        $token = self::getAccessToken();
        $url = "https://oapi.dingtalk.com/call_back/update_call_back?access_token=".$token;
        $data = array('call_back_tag'=>['bpms_instance_change'],'token'=>'123456','aes_key'=>'lfqrojwt31jnvdb5li2arj0f1qz4g8g6eqw45swgyak','url'=>config('ding_callback'));
        return self::curl_post($url,$data);
    }
Copy after login

After completing the registration, DingTalk will access the URL address we set during the approval process event. Backend developers can complete local server approval data synchronization by parsing and filtering the pushed content.

The process of parsing data requires the use of encryption and decryption libraries. DingTalk official download address is as follows https://github.com/injekt/openapi-demo-php/tree/master/isv/crypto

Callback address implementation

 public function callback(){
            //token和aes_key就是你注册地址的时填写的内容
            $token = config('ding_token');
            $aes_key = config('ding_aes_key');
            //suite_key在内部应用使用CorpId即可,官方文档没有明确说明
            $suite_key = config('ding_suite_key');
            $signature = $_GET["signature"];
            $timeStamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $postdata = file_get_contents("php://input");
            $postList = json_decode($postdata,true);
            $encrypt = $postList['encrypt'];
            //使用官方提供的加解密
            $crypt = new DingtalkCrypt();
            $crypt->DingtalkCrypt($token, $aes_key, $suite_key);
            $msg = "";
            $errCode = $crypt->DecryptMsg($signature, $timeStamp, $nonce, $encrypt, $msg);
            if ($errCode != 0){
            }else{
                /**
                 * 创建成功后的回调推送
                 */
                $eventMsg = json_decode($msg);
                $eventType = $eventMsg->EventType;
                /**
                 * 工作流变动
                 */
                if("bpms_instance_change" === $eventType){
                    /**
                     * 编写你需要的内容
                     */ 
                }           
                $res = "success";
                $encryptMsg = "";
                $errCode = $crypt->EncryptMsg($res, $timeStamp, $nonce, $encryptMsg);
                if ($errCode == 0){
                    echo $encryptMsg;
                } 
            }
        }
Copy after login

The return data received from DingTalk is as follows:

tp5 uses DingTalk for workflow approval

encrypt is the encrypted content .

Summary

In this way, we can easily complete the synchronization of data and DingTalk. DingTalk also provides many other personnel management, attendance and other functions. If you are interested, you can browse the official documentation to learn. It is worth mentioning that the official documentation does not clearly explain the specific implementation of the secondary development of interfaces for many functions. However, the sdk is provided in the appendix, and friends who need it can download and learn to use it.

The above is the detailed content of tp5 uses DingTalk for workflow approval. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
tp5
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!