laravel 使用微信的图片内容检测及文字内容检测

文字内容检测

bash 复制代码
	const SEC_LABEL = [
        100 => '正常',
        10001 => '广告',
        20001 => '时政',
        20002 => '色情',
        20003 => '辱骂',
        20006 => '违法犯罪',
        20008 => '欺诈',
        20012 => '低俗',
        20013 => '版权',
        21000 => '敏感',
    ];
    
	/**
     * 检测文字安全
     * @param $openid   openid
     * @param $content  检测文本
     * @param $errmsg   错误信息
     */
    public static function secMsgCheck($openid, $content, &$errmsg)
    {
        $uri = 'https://api.weixin.qq.com/wxa/msg_sec_check';
        $uri = $uri . '?access_token=' . $getAccessToken;

        $info = [
            'content' => $content,
            'version' => 2,
            'scene' => 2,
            'openid' => $openid,
        ];
        // curl请求,方式post,参数json
        $res = CurlUtil::getJson($uri, $info);

        $response = json_decode($res, true);

        switch ($response['errcode']) {
            case 0:
                if ($response['result'] && ($response['result']['suggest'] ?? 'pass') != 'pass') {
                    $msg_type = self::SEC_LABEL[$response['result']['label'] ?? ''] ?? '违规';
                    $errmsg = sprintf('发布失败,内容可能包含%s内容', $msg_type);
                    return false;
                }
                return true;
            case 87014:
                $errmsg = '内容可能存在风险';
                return false;
            default:
                $errmsg = $response['errmsg'];
                return false;
        }
    }

调用

php 复制代码
	$flag = Util::secMsgCheck($openid, $content, $errmsg);
	// $flag == true 及正确,否则返回 $errmsg 信息
    if (!$flag) return $this->error($errmsg);

图片内容检测

微信的图片检测,需要文件大小在1M以内,这就导致用户上传大图的时候无法检测成功,思路使用PHP将文件大小压缩至1M内

图片检测方法

php 复制代码
	// 图片检测是否合法
    public function checkImg(Request $request)
    {
        $file = $request->file('file');
        $extt = ['png', 'jpg', 'jpeg'];
        try {
            if (!$file->isValid()) throw new \Exception("请上传文件");
            //扩展名
            $ext = $file->getClientOriginalExtension();
            if (!in_array($ext, $extt)) throw new \Exception("图片格式不支持上传(支持png,jpg,jpeg)");
            // 文件大小
            $size = $file->getSize();
            //临时绝对路径
            $realPath = $file->getRealPath();
            // 大于1M就将图片压缩
            if ($size > 1024 * 1024 * 1) {
                // 图片压缩
                $img_path = public_path() . '/images/';
                $rand_img_url = date('Ymd') . uniqid() . '.' . $ext;
                ImagesUtil::thumb($realPath, $img_path, $rand_img_url, $ext);
                // 微信检测图片
                $rand_img_url = $img_path . $rand_img_url;
                $flag = Util::secImgCheck($rand_img_url, $errmsg);
                
                // 如果想保留图片将就不加这段代码
                // ******** start ********
                unlink($rand_img_url);
                // ********  end  ********
                
                if (!$flag) throw new \Exception($errmsg);
            } else {
                $flag = Util::secImgCheck($file, $errmsg);
                if (!$flag) throw new \Exception($errmsg);
            }
            return response()->json(['message' => ['检测成功!']]);
        } catch (\Exception $e) {
            return response()->json(['message' => [$e->getMessage()]], 422);
        }
    }

Util文件

php 复制代码
	/**
     * 检测图片安全
     * @param $file     图片
     * @param $errmsg   错误信息
     * @return bool
     */
    public static function secImgCheckNew($file, &$errmsg)
    {
        $uri = 'https://api.weixin.qq.com/wxa/img_sec_check';
        $uri = $uri . '?access_token=' .  $getAccessToken;

        $real_path = realpath($file);
        $obj = new \CurlFile($real_path);
        $obj->setMimeType("image/jpeg");

        $info = [
            'media' => $obj,
        ];
        // curl请求,方式post,参数 FormData
        $res = CurlUtil::SeedHttp($uri, $info, true);

        $response = json_decode($res, true);

        switch ($response['errcode']) {
            case 0:
                return true;
            case 87014:
                $errmsg = '图片可能存在风险';
                return false;
            case 40006:
                $errmsg = '被检测图片内容不能超过1M';
                return false;
            case 45002:
                $errmsg = '被检测图片内容超过限制';
                return false;
            default:
                $errmsg = $response['errmsg'];
                return false;
        }
    }

ImagesUtil文件

php 复制代码
	/**
     * 对图片进行缩放
     * @param $filename     图片的路径
     * @param $img_path     生成图片路劲
     * @param $img_url      生成图片名称
     * @param $ext          图片后缀
     * @param int $width    设置图片缩放的宽度
     * @param int $height   设置图片缩放的高度
     */
    public static function thumb($filename, $img_path, $img_url, $ext, $width = 600, $height = 600)
    {
        // 获得原图的宽度和高度
        list($width_orig, $height_orig) = getimagesize($filename);
        // 根据参数$width和$height的值,换算出等比例的宽高
        if ($width && ($width_orig < $height_orig)) {
            $width = ($height / $height_orig) * $width_orig;
        } else {
            $height = ($width / $width_orig) * $height_orig;
        }
        // 将原图缩放到这个新创建的图片资源中
        $image_p = imagecreatetruecolor($width, $height);
        // 获取原图的图像资源
        if ($ext == 'jpg' || $ext == 'jpeg') {
            $image = imagecreatefromjpeg($filename);
        } elseif ($ext == 'png') {
            $image = imagecreatefrompng($filename);
        } else {
            $image = imagecreatefromgif($filename);
        }

        // 使用imagecopyresamapled()函数进行缩放设置
        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
        // 将缩放后的图片保存
        $_img_url = $img_path . $img_url;
        if ($ext == 'jpg' || $ext == 'jpeg') {
            imagejpeg($image_p, $_img_url, 9);
        } elseif ($ext == 'png') {
            imagepng($image_p, $_img_url, 9);
        } else {
            imagegif($image_p, $_img_url);
        }

        imagedestroy($image_p);// 销毁图片资源$image_p
        imagedestroy($image);// 销毁图片资源$image
    }

CurlUtil文件内容

php 复制代码
	public static function getJson($url = '', $param = [], $contentType = 'json')
    {
        $ch = curl_init();
        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $url);
        // 请求参数类型
        $param = $contentType == 'json' ? urldecode(json_encode($param)) : http_build_query($param);
        // 关闭https验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // post提交
        if ($param) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        }
        // 返回的数据是否自动显示
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 执行并接收响应结果
        $output = curl_exec($ch);
        // 关闭curl
        curl_close($ch);
        return $output !== false ? $output : false;
    }

    /**
     * 发送CURL请求
     * @param $url 请求URL
     * @param $data 请求数据 无数据 == null
     * @param $ispost 是否发送POST 发送 true or false
     * @return bool|string 返回结果集
     */
    public static function SeedHttp($url, $data, $ispost)
    {
        //初使化init方法
        $ch = curl_init();
        //指定URLCURLOPT_POSTFIELDS
        curl_setopt($ch, CURLOPT_URL, $url);
        //设定请求后返回结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //声明使用POST方式来进行发送
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, 1);
        }

        //发送什么数据呢
        if ($data != null || $data != '') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        //忽略证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //忽略header头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        //发送请求
        $output = curl_exec($ch);
        //关闭curl
        curl_close($ch);
        //返回数据
        return $output;
    }
相关推荐
陈思杰系统思考Jason8 小时前
系统思考:短期反馈与长期后果的冲突
百度·微信·微信公众平台·新浪微博·微信开放平台
小代码201611 小时前
ubuntu vscode docker php 环境搭建
vscode·ubuntu·docker·php·laravel
lskblog1 天前
PHP中正确处理HTTP响应:从原始响应到JSON数组的完整指南
http·json·php·laravel
JaguarJack1 天前
前后端分离框架 CatchAdmin V5 beta.2 发布 插件化与开发效率的进一步提升
后端·php·laravel
陈思杰系统思考Jason3 天前
系统思考与业务协同
百度·微信·微信公众平台·新浪微博·微信开放平台
catchadmin3 天前
使用 Laravel Workflow 作为 MCP 工具提供给 AI 客户端
人工智能·php·laravel
天呐草莓3 天前
企业微信自动打标签教程
大数据·python·微信·微信小程序·小程序·企业微信
孙严Pay4 天前
代付功能的跨界新玩法:不止于金融领域
笔记·科技·计算机网络·其他·微信
弓乙图4 天前
弓乙图 先后天八卦的演化源头
经验分享·微信
陈思杰系统思考Jason4 天前
系统思考:决策偏差
百度·微信·微信公众平台·新浪微博·微信开放平台