java微信小程序内容安全 - 检测文本是否含有违法违规内容

 

微信官方文档内容安全接口msgSecCheck

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/sec-check/security.msgSecCheck.html

 controller

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.wx.utils.AccessTokenUtil;
import com.ruoyi.wx.utils.MsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Test {

    @Autowired
    private AccessTokenUtil accessTokenUtil;

    /**
     * 检测文本是否含有违法违规内容
     *
     * @param content
     * @return
     */
    @PostMapping("/msgSecCheck")
    @ResponseBody
    public AjaxResult msgSecCheck(String content){
        // 获取access_token
        String accessToken = accessTokenUtil.getAccessToken();
        String msg = MsgUtil.msgSecCheck(content, accessToken);
        return AjaxResult.success(msg);
    }
}
MsgUtil
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.wx.api.controller.DetailVo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;

public class MsgUtil {


    /**
     * 调用微信开放接口msgSecCheck检测文字内容
     * 1.用户个人资料违规文字检测;
       2.媒体新闻类用户发表文章,评论内容检测;
       3.游戏类用户编辑上传的素材(如答题类小游戏用户上传的问题及答案)检测等。 频率限制:单个 appId 调用上限为 4000 次/分钟,2,000,000 次/天*
     *
     * @param msg 要检测的文字内容
     * @param accessToken 小程序全局唯一后台接口调用凭据
     */
    public static String msgSecCheck(String msg, String accessToken){
        String resultMsg = "";

        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;
        //创建客户端
        HttpClient httpclient = HttpClients.createDefault();
        //创建一个post请求
        HttpPost request = new HttpPost(url);
        //设置响应头
        request.setHeader("Content-Type", "application/json;charset=UTF-8");
        //通过fastJson设置json数据
        JSONObject postData = new JSONObject();
        //设置要检测的内容
        postData.put("version", "2"); //接口版本号,2.0版本为固定值2
        postData.put("openid", "oXHHd5PmFI5Xf3D0cQNld-tJBBIA"); //用户的openid(用户需在近两小时访问过小程序)
        postData.put("scene", "2"); //场景枚举值(1 资料;2 评论;3 论坛;4 社交日志)
        postData.put("content", msg); //需检测的文本内容,文本字数的上限为2500字,需使用UTF-8编码
        String jsonString = postData.toString();
        request.setEntity(new StringEntity(jsonString,"utf-8"));
        try {
            HttpResponse response = httpclient.execute(request);
            // 从响应模型中获取响应实体
            HttpEntity entity = response.getEntity();
            //得到响应结果
            String result = EntityUtils.toString(entity,"utf-8");
            //打印检测结果
            System.out.println("检测结果:"+result);
            //将响应结果变成json
            JSONObject resultJsonObject = JSONObject.parseObject(result);
            String errcode =resultJsonObject.getString("errcode");
            if ("0".equals(errcode)) {
               String detail = resultJsonObject.getString("result");
                DetailVo detailVo = JsonListUtil.jsonToBean(detail, DetailVo.class);
                Integer label = Integer.valueOf(detailVo.getLabel());
                switch (label) {
                    case 100:
                        resultMsg = "正常";
                        break;
                    case 10001:
                        resultMsg = "广告";
                        break;
                    case 20001:
                        resultMsg = "时政";
                        break;
                    case 20002:
                        resultMsg = "色情";
                        break;
                    case 20003:
                        resultMsg = "辱骂";
                        break;
                    case 20006:
                        resultMsg = "违法犯罪";
                        break;
                    case 20008:
                        resultMsg = "欺诈";
                        break;
                    case 20012:
                        resultMsg = "低俗";
                        break;
                    case 20013:
                        resultMsg = "版权";
                        break;
                    case 21000:
                        resultMsg = "其他";
                        break;
                }
            } else {
                return "其他";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultMsg;
    }
}

 vo

import lombok.Data;

@Data
public class DetailVo {

    private String suggest;
    private String label;
}

 测试

检测结果:{"errcode":0,"errmsg":"ok","detail":[{"strategy":"content_model","errcode":0,"suggest":"risky","label":20002,"prob":90},{"strategy":"keyword","errcode":0}],"trace_id":"62c66ac2-5f16f9f8-56459889","result":{"suggest":"risky","label":20002}}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是Java实现微信小程序内容安全检测的示例代码: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class WxMaSecCheckUtil { private static final String API_URL = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=ACCESS_TOKEN"; private static final String CHARSET = "UTF-8"; /** * 调用微信内容安全检测接口 * * @param accessToken 微信 access_token * @param content 待检测内容 * @return boolean 是否合规,true:合规,false:不合规 */ public static boolean checkMsgSec(String accessToken, String content) { try { URL url = new URL(API_URL.replace("ACCESS_TOKEN", accessToken)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json;charset=" + CHARSET); connection.setRequestProperty("Connection", "Keep-Alive"); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); String postJson = "{\"content\":\"" + content + "\"}"; out.write(postJson.getBytes(CHARSET)); out.flush(); out.close(); InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, CHARSET)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); String result = buffer.toString(); inputStream.close(); connection.disconnect(); // 根据返回结果判断是否合规 if (result.indexOf("\"errcode\":0") != -1) { return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } } /** * 计算字符串 SHA1 值 * * @param str * @return */ private static String getSha1(String str) { if (str == null || str.length() == 0) { return null; } try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; i++) { sb.append(String.format("%02x", digest[i])); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } } ``` 使用方法: 1. 替换API_URL中的ACCESS_TOKEN为实际的access_token; 2. 调用checkMsgSec方法进行内容检测,传入accessToken和待检测内容即可。 注意:此示例仅供参考,实际使用中需要根据业务需求进行修改。同时,微信官方也提供了PHP和Node.js等语言的示例代码,可以参考官方文档进行开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43652507

谢谢打赏,祝老板心想事成

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值