配置 ZABBIX 使用企业微信发送 Alert 消息

成功的从企业微信中收到的 Alert 消息的样子:

Oracle 日志 Alert:
配置 ZABBIX 使用企业微信发送 Alert 消息

网络专线 Alert:
配置 ZABBIX 使用企业微信发送 Alert 消息

服务器 Alert:
配置 ZABBIX 使用企业微信发送 Alert 消息

Linux 命令行使用方法:

./workweixin_send.php
Usage: workweixin_send.php.php <username> <title> <content>
./workweixin_send.php <这里填写企业个人微信ID> hi  这是一条测试的企业微信消息

Windows 命令行使用方法:

php workweixin_send.php <这里填写企业个人微信ID> hi  这是一条测试的企业微信消息

测试消息发送成功的样子:
配置 ZABBIX 使用企业微信发送 Alert 消息

ZABBIX WEB前端中的配置:
配置 ZABBIX 使用企业微信发送 Alert 消息
配置 ZABBIX 使用企业微信发送 Alert 消息

ZABBIX 配置文件中的配置:

AlertScriptsPath=/opt/zabbix/scripts/

PHP脚本(需要安装PHP解释器和MEMCACHE,可以参照这个文章进行安装[《PHP版本5到7的源码编译安装》](https://blog.51cto.com/12641643/2484914)):

#!/opt/php/bin/php -q
<?php
class Cache
{   
    /**
     * Cache instance
     * @var Cache
     */
    private static $instance;

    protected $conn;

    /**
     * 获得一个 cache 缓存实例
     * @param mixed $params
     * @return Cache
     */
    public static function getConnect($params = '') : Cache
    {
        if (! self::$instance instanceof self) {
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    /**
     * 实例化一个 cache 实例
     * @param mixed $params
     * @throws \Exception
     */
    private function __construct($params)
    {
        if (! is_array($params)) {
            throw new \Exception('Invalid cache params, failed connect to cache server');
        }
        if (!isset($params['host'])) {
            throw new \Exception('Invalid cache host');
        }
        if (!isset($params['port']) or ($params['port'] < 1 and $params['port'] > 65535)) {
            throw new \Exception('Invalid cache port');
        }
        if (!isset($params['persistent'])) {
            $params['persistent'] = false;
        }
        $params['persistent'] = boolval($params['persistent']);

        $this->conn= new \Memcache();
        if ($params['persistent']) {
            $conn = $this->conn->pconnect($params['host'], $params['port']);
        } else {
            $conn = $this->conn->connect($params['host'], $params['port']);
        }
        if ($conn === false) {
            throw new \Exception('Failed connect to cache server');
        }
    }

    /**
     * 返回缓存值
     * @param string $key
     * @param mixed $default
     */
    public function get(string $key, $default = null)
    {
        if (!empty($key)) {
            $default = $this->conn->get($key);
        }
        return $default;
    }

    /**
     * 设置缓存值
     * @param string $key
     * @param mixed $value
     * @param int $ttl
     * @param bool $compress
     * @return bool
     */
    public function set(string $key, $value = null, int $ttl = null, $compress = false)
    {
        if ($ttl === null) {
            $ttl = $this->getTTL();
        }
        if ($compress) {
            return $this->conn->set($key, $value, MEMCACHE_COMPRESSED, $ttl);
        } else {
            return $this->conn->set($key, $value, 0 , $ttl);
        }
    }
}

class AccessToken
{   
    /**
     * 企业ID<p>
     * 每个企业都拥有唯一的corpid,获取此信息可在管理后台“我的企业”-“企业信息”下查看“企业ID”
     * @var string
     */
    protected $corpid;

    /**
     * secret是企业应用里面用于保障数据安全的“钥匙”,每一个应用都有一个独立的访问密钥,为了保证数据的安全,secret务必不能泄漏
     * @var string
     */
    protected $secret;

    /**
     * 获取 access token 的 url
     * @var string
     */
    protected $url;

    /**
     * 过期时间
     * @var string
     */
    protected $expire;

    /**
     * 配置 corpid 和 secret
     * @param string $corpid
     * @param string $secret
     */
    public function __construct(string $corpid, string $secret)
    {
        $this->corpid = $corpid;
        $this->secret = $secret;
    }

    /**
     * 设置获取 access token 的 url
     * @param string $url
     */
    public function setUrl(string $url) : AccessToken
    {
        $this->url = str_replace(['{corpid}', '{secret}'], [$this->corpid, $this->secret], $url);
        return $this;
    }

    /**
     * 返回 access token
     * @return string
     */
    public function getAccessToken() : string
    {
        $cache = Cache::getConnect();
        $accessToken = $cache->get('work.weixin.access.token');
        if (empty($accessToken)) {
            $accessToken = $this->getAccessTokenFromServer();
            $cache->set('work.weixin.access.token', $accessToken, $this->getExpire() - 60);
        }
        return $accessToken;
    }

    /**
     * 返回 access token 的有效时间
     * @return int
     */
    public function getExpire() : int
    {
        return $this->expire;
    }

    /**
     * 从企业微信服务器上获取 access token
     * @return string
     */
    final protected function getAccessTokenFromServer() : string
    {
        $ch = curl_init();
        $options = [
            CURLOPT_URL             => $this->url,
            CURLOPT_TIMEOUT         => 10,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false
        ];
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        /*
         * 微信接口返回数据格式:
         * {'errcode','errmsg','access_token','expires_in'}
         */
        $data = json_decode($response, true);

        if (empty($data)) {
            throw new \Exception('Failed to access work weixin api');
        }

        // 判断是否成功取得access_token
        if ($data['errcode'] !== 0) {
            throw new \Exception('Failed to get work weixin access token from server. ' . $data['errmsg']);
        }

        $this->expire = $data['expires_in'];

        return $data['access_token'];
    }
}

class SendMessage
{

    /**
     * access token instance
     * @var AccessToken
     */
    protected $accessToken;

    /**
     * 发送消息的url
     * @var string
     */
    protected $url;

    /**
     * 成员ID列表(指定为@all时则向关注该企业应用的全部成员发送)
     * @var array
     */
    protected $toUsers = [];

    /**
     * 部门ID列表(当touser为@all时忽略本参数)
     * @var array
     */
    protected $toParties = [];

    /**
     * 标签ID列表(当touser为@all时忽略本参数)
     * @var array
     */
    protected $toTags = [];

    /**
     * 企业应用的id,整型。可在应用的设置页面查看
     * @var int
     */
    protected $agentId;

    /**
     * 消息内容
     * @var string
     */
    protected $content;

    /**
     * 保密信息(表示是否是保密消息,0表示否,1表示是,默认0)
     * @var int
     */
    protected $safe = 0;

    public function __construct(AccessToken $accessToken)
    {
        $this->accessToken = $accessToken;
    }

    /**
     * 设置成员ID
     * @param array $users
     * @return SendMessage
     */
    public function setToUsers(array $users) : SendMessage
    {
        foreach ($users as $k => $user) {
            if (is_string($user)) {
                $this->toUsers[] = $user;
            }
        }
        return $this;
    }

    /**
     * 设置部门ID
     * @param array $parties
     * @return SendMessage
     */
    public function setToParties(array $parties) : SendMessage
    {
        foreach ($parties as $k => $party) {
            if (is_string($party)) {
                $this->toParties[] = $party;
            }
        }
        return $this;
    }

    /**
     * 设置标签ID
     * @param array $tags
     * @return SendMessage
     */
    public function setToTag(array $tags) : SendMessage
    {
        foreach ($tags as $k => $tag) {
            if (is_string($tag)) {
                $this->toTags[] = $tag;
            }
        }
        return $this;
    }

    /**
     * 设置应用ID
     * @param int $id
     * @return SendMessage
     */
    public function setAgentId(int $id) : SendMessage
    {
        $this->agentId = $id;
        return $this;
    }

    /**
     * 设置消息内容(最长不超过2048个字节)
     * @param string $content
     * @return SendMessage
     */
    public function setContent(string $content) : SendMessage
    {
        if (!empty($content)) {
            $this->content = $content;
        }
        return $this;
    }

    public function setUrl(string $url) : SendMessage
    {
        $this->url = str_replace('{accessToken}', $this->accessToken->getAccessToken(), $url);
        return $this;
    }

    /**
     * 调用企业微信 api 发送消息
     * @throws \Exception
     */
    private function send(string $data)
    {
        $ch = curl_init();
        $options = [
            CURLOPT_URL             => $this->url,
            CURLOPT_HEADER          => 0,
            CURLOPT_POST            => 1,
            CURLOPT_POSTFIELDS      => $data,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_TIMEOUT         => 10,
            CURLOPT_SSL_VERIFYPEER  => 0,
            CURLOPT_SSL_VERIFYHOST  => 0
        ];
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        $data = json_decode($response, true);

        if (empty($data)) {
            throw new \Exception('Failed to access work weixin api');
        }
        if ($data['errcode'] !== 0) {
            throw new \Exception('Failed to send WeiXin message. ' . $data['errmsg']);
        }
    }

    /**
     * 发送文本消息
     * @throws \Exception
     */
    public function sendTextMessage() {
        if (empty($this->toUsers) && empty($this->toParties) && empty($this->toTags)) {
            throw new \Exception('Invalid message recevier');
        }
        if (empty($this->agentId)) {
            throw new \Exception('Invalid app agentid');
        }
        if (empty($this->content)) {
            throw new \Exception('Empty message content');
        }
        $data = json_encode([
            'touser'    => implode('|', $this->toUsers),
            'toparty'   => implode('|', $this->toParties),
            'totag'     => implode('|', $this->toTags),
            'msgtype'   => 'text',
            'agentid'   => $this->agentId,
            'safe'      => $this->safe,
            'text'      => [
                'content'   => $this->content
            ]
        ], JSON_UNESCAPED_UNICODE);

        // 如果第一次发送失败,尝试两次发送
        try {
            $this->send($data);
        } catch (\Exception $e) {
            $this->send($data);
        }
    }

}

// -----------------------------------------------------------------------------------

$cacheParams = [
    'host' => '127.0.0.1',
    'port' => '11211'
];
// 每个企业都拥有唯一的corpid,获取此信息可在管理后台“我的企业”-“企业信息”下查看“企业ID”
$corpid = '*************';
//secret是企业应用里面用于保障数据安全的“钥匙”,每一个应用都有一个独立的访问密钥,为了保证数据的安全,secret务必不能泄漏
$secret = '*************';
// agentid 企业应用的id,整型。可在应用的设置页面查看
$agentid = 1;
$fetchAccessTokenUrl= "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}";
$sendMessageUrl = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={accessToken}';

// -----------------------------------------------------------------------------------

if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3])) {
    echo 'Usage: ' . basename(__FILE__) . '.php <username> <title> <content>';
    return;
}

// -----------------------------------------------------------------------------------

try {

    Cache::getConnect($cacheParams);

    $accessToken = new AccessToken($corpid, $secret);
    $accessToken->setUrl($fetchAccessTokenUrl);

    $wwx = new SendMessage($accessToken);
    $wwx->setAgentId($agentid)
        ->setUrl($sendMessageUrl)
        ->setToUsers([$argv[1]])
        ->setContent(str_replace(' ', '', strip_tags($argv[3])))
        ->sendTextMessage();
} catch (\Exception $e) {
    echo $e->getMessage();
    file_put_contents(basename(__FILE__, '.php') . '.log', $e->getMessage());
}

猜你喜欢

转载自blog.51cto.com/12641643/2485835