PHP对接钉钉自定义机器人
<?php
namespace App\Services;
use GuzzleHttp\Client;
class MessageService
{
public static function dingSend($message = '测试')
{
// 加签
$token = ""; // 机器人的token
$secret = ""; // 钉钉给出的密钥
// 获取微秒数时间戳
list($s1, $s2) = explode(' ', microtime());
// 转换成毫秒数时间戳
$msectime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
// 拼装成待加密字符串
// 格式:毫秒数+"\n"+密钥
$stringToSign = $msectime . "\n" . $secret;
// 进行加密操作 并输出二进制数据
$sign = hash_hmac('sha256', $stringToSign, $secret, true);
// 加密后进行base64编码 以及url编码
$sign = urlencode(base64_encode($sign));
// 拼接url
$url = 'https://oapi.dingtalk.com/robot/send?access_token=' . $token;
$url .= '×tamp=' . $msectime; // 拼接时间戳
$url .= '&sign=' . $sign; // 拼接加密签名
return self::dingtalk_by_curl($url, $message);
}
/**
* 发送消息
*/
public static function dingtalk_by_curl($url, $message)
{
$client = new Client();
$data = [
'json' => [
'msgtype' => 'text',
'text' => [
'content' => $message
],
],
'headers' => [
'Content-Type' => 'application/json',
'charset' => 'utf-8',
],
];
$res = $client->request('POST', $url, $data)->getBody()->getContents();
$res = json_decode($res, true);
return $res;
}
}