钉钉机器人发送自定义消息 PHP 干货

时间:2024-03-30 18:53:02
<?php declare (strict_types=1); namespace app\common\service\dingListen; class DingListen { public $listenToken = "xxxxxxx"; //测试机器人token public $listenSecret = "xxxxxxx"; // 测试机器人secret /** * 请求地址 * @var string $url * */ public $url = 'https://oapi.dingtalk.com/robot/send'; /** * 请求地址 * @var string $timestamp 13位毫秒级 * */ public $timestamp; /** * 加签 * @var string $sign * */ public $sign; /** * webhookurl * @var string $webhookurl * */ public $webhookurl; public function __construct(){ //时间戳 $this->timestamp = time() * 1000; //加签 $str = $this->timestamp."\n". $this->listenSecret; $sign = hash_hmac("sha256",$str ,$this->listenSecret,true); $sign = base64_encode($sign); $this->sign = $sign ; //返回链接 $webhookurl = $this->url.'?access_token='.$this->listenToken. '&timestamp='.$this->timestamp.'&sign='.urlencode($this->sign); $this->webhookurl = $webhookurl; } //发送text文本信息 public function text($content = '', $mobiles = [], $userIds = [], $isAtAll = true) { $sendContent = [ "msgtype" => "text", "text" => [ "content" => $content ], "at" => [ "atMobiles" => $mobiles, "atUserIds" => $userIds, //不是钉钉管理员无法获取userIds "isAtAll" => $isAtAll ] ]; $res = $this->_curl_post_json($this->webhookurl, $sendContent); return $res; } public function Markdown($content = '', $title="消息通知", $mobiles = ["13XXXXXXXX"], $userIds = [], $isAtAll = true) { $sendContent = [ "msgtype" => "markdown", "markdown"=> [ "title"=> $title, "text"=> $content ], "at" => [ "atMobiles" => $mobiles, "atUserIds" => $userIds, //不是钉钉管理员无法获取userIds "isAtAll" => $isAtAll ] ]; $res = $this->_curl_post_json($this->webhookurl, $sendContent); return $res; } //发送json数据 public function _curl_post_json($url, $data = array()) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, 320)); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $res = curl_exec($curl); curl_close($curl); return $res; } }