php发送消息到钉钉群

简介:php使用curl发送消息到钉钉群,php对接钉钉群机器人

1. 封装http请求

protected function http_post($url,$param,$method='post')
{
    $ch = curl_init();
    if(substr($url,0,5)=='https'){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);
    }
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30*1000);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_HTTPHEADER,[
        'Content-Type:application/json',
    ]);
    if($method=='post'){
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($param));
    }
    $response = curl_exec($ch);
    $error=curl_error($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if($error){
        throw new ApiCallException(ErrorCode::ERR_API_RESULT_EXCEPTION,$error);
    }
    if($statusCode!=200){
        throw new ApiCallException(ErrorCode::ERR_API_RESULT_EXCEPTION,$response);
    }
    curl_close($ch);
    return $response;
}

2. 加签

注意如果钉钉群机器人没有启用加签可以忽略这一步

// 钉钉群密钥
$secret = 'SEC4252fee82c70b59172a421fea77c';
// 毫秒级时间戳
$timestamp = round(microtime(true)*1000,0);
// 拼接签名字符串
$string_to_sign = "{$timestamp}\n{$secret}";
// HmacSHA256签名
$hmac_code = hash_hmac('sha256', $string_to_sign, $secret, true);
// base64加密及urlencode
$sign = urlencode(base64_encode($hmac_code));

3. 拼接url,设置参数,发送请求

$url = $url.'?'.http_build_query($params);
$post_data = [
            'msgtype'=>'text',
            'at'=>['atMobiles'=>[],'isAtAll'=>true],
            'text'=>['content'=>$msg]
];
$res = $this->http_post($url,$post_data);
$res = json_decode($res,true);
if ($res['errcode']!=0){
    throw new ApiCallException(ErrorCode::ERR_API_RESULT_EXCEPTION,$res['errmsg']);
}

 

编程经验共享公众号二维码
更多内容关注公众号
Copyright © 2021 编程经验共享 赣ICP备2021010401号-1