当前位置:编程学习 > php >>

php实现微信小程序内容安全接口校验

php实现微信小程序内容安全接口校验
 
define('MSG_SEC_CHECK','https://api.weixin.qq.com/wxa/msg_sec_check?');//小程序敏感词检查
define('IMG_SEC_CHECK','https://api.weixin.qq.com/wxa/img_sec_check?');//小程序图片检查
define('OAUTH_TOKEN_URL','https://api.weixin.qq.com/cgi-bin/token?');  //获取授权access_token
 
//检测敏感词
function msg_sec_check($appid,$secret,$content){
    $web_access_token = get_access_token($appid,$secret);
    $params = [
        'access_token' => $web_access_token,
    ];
    $request_params = to_url_params($params);
    $url = MSG_SEC_CHECK . $request_params;
    $data = json_encode(['content'=>$content],JSON_UNESCAPED_UNICODE);//网上看到的基本都是直接让中文给json转义了,实测json转义后无法检测出实际违规内容
    $result = json_decode(curl_request($url, $data, true));
    //返回数据自行根据自己需要进行判断
    return $result;
}
 
//图片检测($media参数格式为['media'=>new \CURLFile()],php5.5以上)
function img_sec_check($appid,$secret,$media){
    $web_access_token = get_access_token($appid,$secret);
    $params = [
        'access_token' => $web_access_token,
    ];
    $request_params = to_url_params($params);
    $url = IMG_SEC_CHECK . $request_params;
    $result = json_decode(curl_request($url, $media, true));
    //返回数据自行根据自己需要进行判断
    return $result;
}
 
//获取微信access_token(自行优化一下,可存缓存)
function get_access_token($appid,$secret){
    $params = [
        'grant_type' => 'client_credential',
        'appid' => $appid,
        'secret' => $secret,
    ];
    $request_params = to_url_params($params);
    $url = OAUTH_TOKEN_URL . $request_params;
    $result = json_decode(curl_request($url), true);
    //返回数据自行根据自己需要进行判断
    return $result['access_token'];
}
 
//参数处理
function to_url_params($params){
    $buff = "";
    foreach ($params as $k => $v) {
        if ($k != "sign") {
            $buff .= $k . "=" . $v . "&";
        }
    }
    $buff = trim($buff, "&");
    return $buff;
}
 
function curl_request($url = '', $postData = '', $options = array()){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if (!empty($postData)) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
    if (!empty($options)) {
        curl_setopt_array($ch, $options);
    }
    //https请求 不验证证书和host
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
使用案例

//敏感词
$appid = "";
$secret = "";
$content = "敏感词易做图";//自己想
$file = "./uploads/images/zzzyk.com.jpg";
msg_sec_check($appid,$secret,$content);
 
//图片检测
$media = ['media'=>new \CURLFile(realpath($file),'image/jpeg')];//php>=5.5
$media = ['media'=>'@'.realpath($file)];//php<5.5(未实测,可能缺少mine参数)
img_sec_check($appid,$secret,$media);
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,