# 钉钉 ## 辅助函数 ```php /** * curl 请求 * * @param string $method 请求方法 POST/GET/DELETE/PUT * @param string $url * @param array|string $data 提交数据 * @param array $header 请求头 * @return string|null */ function curl_request($method = 'POST', $url, $data='', $header=[]) { $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_POSTFIELDS => $data, CURLOPT_HTTPHEADER => $header, )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) throw new Exception($err, 1); return $response; } ``` ## 封装代码 file:`application/utils/DingTalk.php` ```php <?php namespace app\utils; use think\Exception; use think\facade\Cache; /** * 应用密钥 */ define('DINGTALK_CORPID', env('DINGTALK.CORPID')); define('DINGTALK_SECRET', env('DINGTALK.SECRET')); /** * 钉钉 */ class DingTalk { /** * 企业开发者消息ID */ const AGENT_ID = ''; /** * 获取access_token * * @return string */ static function getAccessToken() { $access_token = Cache::get('DING_TOKEN'); if ($access_token) { return $access_token; } $corpid = DINGTALK_CORPID; $corpsecret = DINGTALK_SECRET; $response = curl_request('GET', "https://oapi.dingtalk.com/gettoken?corpid={$corpid}&corpsecret={$corpsecret}"); // dump($response); $result = json_decode($response, true); if (!isset($result['access_token'])) throw new Exception($result['errmsg'], 1); $access_token = $result['access_token']; Cache::set('DING_TOKEN', $access_token, 60); // 60秒内用同一个 return $access_token; } /** * 获取用户userid * * @param string $code * @return string */ static function getUserid($code) { $access_token = self::getAccessToken(); $url = "https://oapi.dingtalk.com/user/getuserinfo?access_token={$access_token}&code={$code}"; $response = curl_request('GET', $url); $result = json_decode($response, true); if (!isset($result['userid'])) throw new Exception($result['errmsg'], 1); $userid = $result['userid']; return $userid; } /** * 获取用户信息 * * @param integer $userid * @return array */ static function getUserinfo($userid) { $access_token = self::getAccessToken(); $url = "https://oapi.dingtalk.com/user/get?access_token={$access_token}&userid={$userid}"; $response = curl_request('POST', $url); $result = json_encode($response, true); return $result; } /** * 发送消息 * * @param integer $agent_id 应用agentId 参考常量: DingTalk::AGENT_ID * @param string $user_id 钉钉用户id * @param array $msg 消息格式参考: https://ding-doc.dingtalk.com/doc#/serverapi2/ye8tup * @return array|null array(3) { errcode=>0, task_id=>18988591062, request_id=>6iq4ab1gd7il } */ static function sendMsg($agent_id, $userid = '', $msg) { $access_token = self::getAccessToken(); $url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=$access_token"; $postData["agent_id"] = $agent_id; $postData["userid_list"] = $userid; $postData["msg"] = $msg; $result = json_decode(curl_request('POST', $url, $postData), true); return $result; } /** * 发送文本消息 * * @param integer $agent_id 应用agentId 参考常量: DingTalk::AGENT_ID * @param string $userid 钉钉用户id * @param string $content 发送内容 * @return void */ static function sendTextMsg($agent_id, $userid, $content) { $msgData = [ 'msgtype' => 'text', 'text' => [ 'content' => $content, ], ]; return self::sendMsg($agent_id, $userid, $msgData); } } ``` ## 登录 1. 前端, 通过`corpId`换取`code` ```javascript <scriptsrc="http://g.alicdn.com/dingding/dingtalk-pc-api/2.3.1/index.js"></script> <scriptsrc="https://g.alicdn.com/dingding/open-develop/1.6.9/dingtalk.js"></script> dd.ready(function(){ dd.runtime.permission.requestAuthCode({ corpId:{corpId}, onSuccess:function(result) { // result.code }, }); }); DingTalkPC.runtime.permission.requestAuthCode({ corpId:{corpId}, onSuccess:function(result) { // result.code }, onFail:function(err) { } }); dd.error(function(err){ alert('dd error:'+JSON.stringify(err)); }); ``` 2. 获取`access_token` 3. 通过`code`和`access_token`换取`userid`(钉钉用户id) ```php $access_token = DingTalk::getAccessToken(); if (!$access_token) error("没有成功获取access_token"); // get userid $userid = DingTalk::getUserid($code); if (!$userid) error("授权失败"); // get userinfo $userinfo = DingTalk::getUserinfo($userid); if (!$userinfo) error('授权失败'); ``` **其他:发送消息通知** ``` $msgContent = sprintf('您的学员【%s】提交的资料被驳回了,原因请进入系统查看', '测试'); DingTalk::sendTextMsg(DingTalk::AGENT_ID, 钉钉userid, $msgContent); ```