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;
    }
相关推荐
特视界说1 天前
多规格产品动画怎么规划?把“一个型号一条片”改成可管理的内容架构
人工智能·安全·微信·新浪微博
悟空码字2 天前
视频号直播变了
微信·视频号
随性而行3603 天前
企业微信 Webhook 接收不到消息?网络连通性、URL 签名验签与 API 返回错误码排查指南
java·网络·人工智能·后端·微信·企业微信
未秃头的程序猿4 天前
同一个商户号,V2 免密代扣和 V3 分账的证书怎么共存?
java·后端·微信
木易 士心4 天前
Spring Boot 微信公众号后端服务开发实战指南
spring boot·后端·微信
linda`li6 天前
如何使用TRAE+Figma自动生成前端代码
微信·figma·自动写代码
随性而行3607 天前
企业微信 API 如何实现业务消息自动通知?接口应用场景解析
java·人工智能·后端·微信·机器人·企业微信
极客互动API7 天前
企业微信二次开发 API:如何与 SCRM 打通外部联系人的消息发送
微信·企业微信·企微scrm·企业微信api·企微外部联系人
青柠之夏cc11 天前
Laravel服务容器底层原理揭秘
javascript·rpc·laravel