钉钉机器人接入
官方文档
https://open.dingtalk.com/document/group/custom-robot-access
代码
<?php
namespace App\Robot;
use App\Contracts\RobotInterface;
class DingtalkRobot implements RobotInterface
{
protected array $config;
public function __construct(){
$this->config = config('robot.dingtalk.config');
}
public function send($data, $robot_key = '')
{
if (!empty($robot_key)) {
$this->config = config('robot.dingtalk.' . $robot_key);
}
$secret = $this->config['secret'];
$accessToken = $this->config['access_token'];
// 当前时间(毫秒)
$timestamp = time() * 1000;
// HmacSHA256加密,设置为 true 输出原始二进制数据
$hmacsha256 = hash_hmac('sha256', $timestamp . "\n" . $secret, $secret, true);
// 请求参数
$param = [
'access_token' => $accessToken,
'timestamp' => $timestamp,
// 签名值
'sign' => urlencode(base64_encode($hmacsha256))
];
// Webhook地址
$webhook = $this->config['webhook'] . http_build_query($param);
$data_string = json_encode($data);
return DingtalkRobot::request_by_curl($webhook, $data_string);
}
public static function request_by_curl($remote_server, $post_string)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_server);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
// curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
// curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
$message = "我就是我,不一样的我!";
$data = array(
'at' => array('atMobiles' => [13800138000], 'isAtAll' => false),
'msgtype' => 'text',
'text' => array('content' => $message)
);
$robot_key = 'TEST';
$this->robot->send($data, $robot_key);
本作品采用《CC 协议》,转载必须注明作者和本文链接
自荐一下: github.com/guanguans/notify。目前已支持 26 种推送通知。