简单的工具类封装

只依赖 curl 扩展,复制即可使用。封装了 文本、markdown、图片类型,其他类型也可根据需求快速添加,当然也可以根据需求适当调整参数(比如 @某某 的功能)。

/**
 * 企业微信群机器人
 * @see https://developer.work.weixin.qq.com/document/path/91770
 */
class WorkGroupRobot
{
    private $webhookUrl;

    public static function create($webhookUrl): WorkGroupRobot
    {
        return new WorkGroupRobot($webhookUrl);
    }

    public function __construct($webhookUrl)
    {
        if (empty($webhookUrl)) {
            throw new \Exception('webhookUrl is empty!');
        }
        $this->webhookUrl = $webhookUrl;
    }

    private function _post($params)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->webhookUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json;charset=UTF-8']);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);
    }

    public function sendText($content)
    {
        return $this->_post([
            'msgtype' => 'text',
            'text'    => [
                'content' => $content,
            ],
        ]);
    }

    public function sendMarkdown($content)
    {
        return $this->_post([
            'msgtype'  => 'markdown',
            'markdown' => [
                'content' => $content,
            ],
        ]);
    }

    public function sendImage($base64Image)
    {
        return $this->_post([
            'msgtype' => 'image',
            'image'   => [
                'base64' => $base64Image,
                'md5'    => md5($base64Image),
            ],
        ]);
    }
}

发送 markdown 消息

$url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx-xxx-xxx-xxx';
WorkGroupRobot::create($url)
    ->sendMarkdown("# 测试标题\n## 测试二级标题\n> 测试引用");

效果不错:

2023-11-21T16:25:36.png

标签: 企业微信, 群机器人

添加新评论