企业微信群聊机器人发送信息

废话不多说 直接上代码 复制可用

/**
 * 企业微信发送信息
 * @param $msg 备注信息
 * @param string $api 接口
 * @param array $par  请求参数
 * @param string $res 接口返回
 */
function sendWebHookMsg($msg,$api = '',$par = [],$res = '')
{
    $template = $msg.PHP_EOL;
    $template .= '--------------------------'.PHP_EOL;
    $template .= '时间:'.date('Y-m-d H:i:s',time()).PHP_EOL;
    if ($api)  $template .= '接口:'.$api.PHP_EOL;
    if ($par)  $template .= '接口参数:'.json_encode($par,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE).PHP_EOL;
    if ($res)  $template .= '接口返回:'.json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE).PHP_EOL;

	//企业微信机器人Webhook地址
    $url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=89........................';

    $send_params = [
        'msgtype' => 'text',
        'text' => [
            'content' => $template,
        ]
    ];

    curlRequest($url,'POST',json_encode($send_params));
}

/**
 * curl请求
 * @param  string $url 请求Url
 * @param  string $method 请求方式
 * @param  array/string $headers Headers信息
 * @param  array/string $params 请求参数
 * @return 返回的
 */
function curlRequest($url, $method = 'GET', $params = []){
    if (is_array($params)) {
        $requestString = http_build_query($params);
    } else {
        $requestString = $params ? : '';
    }

    $headers = array('Content-type: text/json');

    // setting the curl parameters.
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    // turning off the server and peer verification(TrustManager Concept).
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    // setting the POST FIELD to curl
    switch ($method){
        case "GET" : curl_setopt($ch, CURLOPT_HTTPGET, 1);break;
        case "POST": curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);break;
        case "PUT" : curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);break;
        case "DELETE":  curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);break;
    }
    // getting response from server
    $response = curl_exec($ch);
    //close the connection
    curl_close($ch);

    //return the response
    if (stristr($response, 'HTTP 404') || $response == '') {
        return array('Error' => '请求错误');
    }
    return $response;
}

1.企业微信创建群聊

创建一个三人群聊,然后踢了其他两人,

2.添加机器人

添加机器人 获取webhook;

3.以上代码填写webhook

4.调用:

4.结果:

麦志建博客
请先登录后发表评论
  • latest comments
  • 总共1条评论
麦志建博客

Wake in Dublin : 给我搞了机器人,聊聊天麦志建博客

2021-06-25 17:02:13 回复