dingtalk钉钉机器人

  • 使用access_token+[告警级别]关键字

/**
 * 钉钉异常通知
 */
function dingException️($e, $ext_text = '')
{
    // 去掉 Encodes 异常通知
    if (
        strpos($e->getFile(), 'Encodes.php') !== false ||
        strpos($e->getMessage(), '页面不存在') !== false ||
        strpos($e->getMessage(), 'module not exists') !== false
    ) {
        return false;
    }
    $host_name = $_SERVER['HTTP_HOST'] ?? '';
    if (empty($host_name)) {
        $host_name = $_SERVER['SERVER_NAME'] ?? '';
    }
    $ext_text = $host_name . $ext_text;
    // https://open.dingtalk.com/document/orgapp/custom-bot-send-message-type
    $url = 'https://oapi.dingtalk.com/robot/send?access_token=907fbe461f34d294aa292668d3015aa3894188bb1de553ff7ea70663bf699f47';
    $post_data = [
        'msgtype' => 'markdown',
        'markdown' => [
            'title' => mb_substr($e->getMessage(), 0, 32),
            'text' => sprintf(
                "告警级别\n\n# $ext_text %s(" . date('Y-m-d H:i:s') . ")\n\n## File\n%s:%d\n\n## Trace\n%s",
                $e->getMessage(),
                $e->getFile(),
                $e->getLine(),
                mb_substr($e->getTraceAsString(), 0, 1200),
            ),
        ],
    ];
    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 1);
    //设置获取的信息以文件流的形式返回,而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //设置post方式提交
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
    ]);
    curl_setopt($curl, CURLOPT_HEADER, false);
    //执行命令
    $data = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    //显示获得的数据
    $json_data = json_decode($data, true);
    return isset($json_data['errcode']) && $json_data['errcode'] == 0;
}
  • 支持回调的交互机器人

<?php

/**
### [群交互机器人](https://open.dingtalk.com/document/orgapp/dingtalk-chatbot-for-one-on-one-query#title-uuw-vbo-yy2)
AgentId 295xxx1
AppKey dingmaisxxxxxxxxxappkey
AppSecret aSOIwIgLBGGht4AFpbsUKDqPHxxxxxxxxxxxappsecret
http://74.xxxx9:7764/DingRbot.php
 */

class DingRbot
{
    public $appKey = 'dingmaisxxxxxxxxxappkey';
    public $appSecret = 'aSOIwIgLBGGht4AFpbsUKDqPHxxxxxxxxxxxappsecret';

    public function token()
    {
        $url = 'https://api.dingtalk.com/v1.0/oauth2/accessToken';
        $data = [
            "appKey" => $this->appKey,
            "appSecret" => $this->appSecret
        ];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        $response = curl_exec($ch);
        curl_close($ch);
        if (curl_errno($ch)) {
            return false;
        } else {
            return json_decode($response, true)['accessToken'] ?? '';
        }
    }
    // 发送消息
    public function send($robotCode, $userIds = [],)
    {
        $token = $this->token();
        if (empty($token)) {
            error_log(print_r("token获取失败", true));
            return false;
        }
        $url = 'https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend';
        $data = [
            "robotCode" => $robotCode,
            "userIds" => $userIds,
            "msgKey" => "sampleMarkdown",
            "msgParam" => json_encode([
                "text" => "hello text",
                "title" => "hello title"
            ])
        ];

        // 初始化 cURL
        $ch = curl_init($url);

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'x-acs-dingtalk-access-token: ' . $token
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        // 发送请求并获取响应
        $response = curl_exec($ch);
        curl_close($ch);
        error_log(print_r($response, true));
    }
    function hook($title = '标题', $content = '', $sessionWebhook = '')
    {
        // https://open.dingtalk.com/document/orgapp/robot-message-types-and-data-format
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=899f60d0fa233202c38f563abcc6ab57a2624b857eec911ff93369257eff04db';
        $url = $sessionWebhook;
        $post_data = [
            'msgtype' => 'markdown',
            'markdown' => [
                'title' => $title,
                'text' => $content,
            ],
        ];
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回,而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_data));
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
        ]);
        curl_setopt($curl, CURLOPT_HEADER, false);
        //执行命令
        curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
    }
    public function callbackdata()
    {
        $headers = getallheaders();
        $post_timestamp = $headers['timestamp'] ?? '';
        $post_sign = $headers['sign'] ?? '';
        $data = file_get_contents("php://input");
        // 构建待签名字符串
        $stringToSign = $post_timestamp . "\n" . $this->appSecret;
        // 计算 HMAC SHA256 签名
        $signData = hash_hmac('sha256', $stringToSign, $this->appSecret, true);
        // 使用 Base64 编码签名结果
        $sign = base64_encode($signData);
        // 输出签名
        if ($sign == $post_sign) {
            // error_log(print_r("校验成功", true));
            /**
{
    "senderPlatform": "Android",
    "conversationId": "cidJK8HwTiF+DZ2tnYdRvsF5g==",
    "atUsers": [
        {
            "dingtalkId": "$:LWCP_v1:$mIFltebaZ91LW/DQUPJWb7GqYzyaSVIt"
        }
    ],
    "chatbotCorpId": "ding63d8a4622a760065f2c783f7214b6d69",
    "chatbotUserId": "$:LWCP_v1:$mIFltebaZ91LW/DQUPJWb7GqYzyaSVIt",
    "msgId": "msg0r5Aa2JP9VWjFweWfOWmtA==",
    "senderNick": "冷晶川",
    "isAdmin": true,
    "senderStaffId": "254137606520940318",
    "sessionWebhookExpiredTime": 1731083278855,
    "createAt": 1731077878605,
    "senderCorpId": "ding63d8a4622a760065f2c783f7214b6d69",
    "conversationType": "2",
    "senderId": "$:LWCP_v1:$uvMAZyOJEoo05NvM7FvuN1T7KJNhFl1q",
    "conversationTitle": "digapp内部群",
    "isInAtList": true,
    "sessionWebhook": "https://oapi.dingtalk.com/robot/sendBySession?session=99e3da1ca752dd986599a24052c4f03d",
    "text": {
        "content": " 你好"
    },
    "robotCode": "dingmaisxxxxxxxxxappkey",
    "msgtype": "text"
}
             */
            // https://open.dingtalk.com/document/orgapp/robot-receive-message
            return json_decode($data, true);
        } else {
            return [];
        }
    }
}

$ding = new DingRbot();
$data = $ding->callbackdata();
// 单聊
// $res = $ding->send($data['robotCode'], [$data['senderStaffId']]);
// 直接群内回复
$res = $ding->hook('标题', '重复: ' . $data['text']['content'], $data['sessionWebhook']);
error_log(print_r($res, true));