-- 创造无限可能

微信小程序图片安全内容检测接口

2026-07-01 15:23:04
111 人浏览 0 人点赞
有用,点赞支持一下

微信小程序越来越严格,上传图片时如果不加上图片安全检测提交审核时又可能会被驳回

例如:
你的小程序【图片】功能在进行内容安全验证时,存在信息安全风险,请尽快完善内容机制:
1、确保已接入内容安全API并要求所调用API可在小程序内任意发布的场景生效;
2、小程序内检测结果安全说明仅需提示用户所发布内容含违规信息即可; 接口调用可参考:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html

下面实例是thinkphp的实例

    //    上传单张图片
    public function uploadOne(){
        // 获取表单上传文件 例如上传了001.jpg
        $files = request()->file();
        try {
            $error = validate(['file'=>'fileSize:20000000'])
                ->check($files);

            $file = request()->file('file');
            $info = \think\facade\Filesystem::putFile( 'topic', $file);
            if($info){
                $info   = str_replace('\\','/',$info);
                $imgs =  '/' . $info;
            }

            // 验证图片内容安全验证
            (new SecurityCheckService())->checkImage($this->request->domain() . $imgs);

            if($imgs){
                return $this->success('', $imgs);
            }
            return $this->error();
        } catch (\think\exception\ValidateException $e) {
            return $this->error($e->getMessage());
        } catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }
<?php


namespace app\common\service;


use think\Exception;

class SecurityCheckService
{
// 微信小程序配置
    private $appId = '你的小程序appid';
    private $appSecret = '你的小程序秘钥';

    /**
     * 文本内容安全检测
     */
    public function checkText($content)
    {
        if (empty($content)) {
            throw new Exception('请传入内容');
        }

        // 3. 获取微信access_token
        $accessToken = $this->getAccessToken();
        if (!$accessToken) {
            throw new Exception('获取access_token失败');
        }

        // 4. 调用微信文本安全API
        $url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token={$accessToken}";
        $data = json_encode(['content' => $content]);

        $result = $this->httpPost($url, $data);
        if ($result === false) {
            throw new Exception('调用微信API失败');
        }

        $response = json_decode($result, true);

        // 5. 返回结果给前端(根据审核要求,只返回是否违规)
        if ($response['errcode'] === 0) {
            // 内容安全,无违规信息
            return true;
        } else if ($response['errcode'] === 87014) {
            // 内容含有违法违规信息
            throw new Exception('您发布的内容含有违规信息');
        } else {
            // 其他错误
            throw new Exception($response['errmsg']);
        }
    }

    /**
     * 图片内容安全检测(异步)
     */
    public function checkImage($imageUrl)
    {
        // 1. 接收并验证参数
        // $imageUrl = $request->post('content'); // 图片URL或base64数据

        if (empty($imageUrl)) {
            throw new Exception('参数不完整');
        }

        // 3. 获取access_token
        $accessToken = $this->getAccessToken();
        if (!$accessToken) {
            throw new Exception('获取access_token失败');
        }

        // 4. 调用微信图片安全API(异步)
        $url = "https://api.weixin.qq.com/wxa/media_check_async?access_token={$accessToken}";

        // 判断传入的是URL还是base64数据
        if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
            $data = json_encode(['media_url' => $imageUrl, 'media_type' => 2]);
        } else {
            // 假设传入的是base64图片数据
            $data = json_encode(['media' => $imageUrl, 'media_type' => 2]);
        }

        $result = $this->httpPost($url, $data);
        if ($result === false) {
            throw new Exception('调用微信API失败');
        }

        $response = json_decode($result, true);

        // 5. 返回结果(异步检测,通常返回任务ID)
        if ($response['errcode'] === 0) {
            // 提交成功,需要后续轮询检测结果
            return true;
        } else {
            throw new Exception($response['errmsg']);
        }
    }

    /**
     * 获取微信access_token(需缓存)
     */
    private function getAccessToken()
    {
        // 实际生产环境需要缓存token,避免频繁请求
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $result = $this->httpGet($url);
        if ($result) {
            $data = json_decode($result, true);
            return isset($data['access_token']) ? $data['access_token'] : null;
        }
        return null;
    }

    /**
     * Token验证(需根据您的实际实现)
     */
    private function validateToken($token)
    {
        // 这里需要实现您的token验证逻辑
        // 例如从数据库查询或使用JWT验证
        return true; // 示例始终返回true
    }

    /**
     * HTTP GET请求
     */
    private function httpGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * HTTP POST请求
     */
    private function httpPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}