YiDunAntiFraudUtil.java 15.7 KB
package com.cnlive.shenhe.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cnlive.shenhe.api.AvsampleCallBackControllerApi;
import com.cnlive.shenhe.entity.ShyYidun;
import com.cnlive.shenhe.serviceImpl.YiDunServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 网易易盾
 *
 * @Author: xujincheng
 * @Date: 2020/3/18 12:47
 */
public class YiDunAntiFraudUtil {

    private static Logger logger = LoggerFactory.getLogger(YiDunAntiFraudUtil.class);

    @Autowired
    YiDunServiceImpl yiDunServiceImpl;

    /**
     * 网站地址URL产品密钥ID,产品标识
     */
    private final static String SECRETID = "c7f33c191020bcc9cbacb7d70417fd2f";
    /**
     * 网站地址URL产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露
     */
    private final static String SECRETKEY = "833222b4951a67a9bc63b5ed0c24d07d";
    /**
     * 网站地址URL提交接口地址
     */
    private final static String URL_SUBMIT = "https://as.dun.163yun.com/v1/crawler/submit";
    /**
     * 需检测的网站地址URL
     */
    private final static String FILE_URL = "http://shen.cnlive.com/api/content/detail/135058.html";
    /**
     * 网站地址URL检测结果获取接口地址
     */
    private final static String URL_RESULT = "https://as.dun.163yun.com/v1/crawler/callback/results";

    /**
     * 文本识别图片识别产品密钥ID,产品标识
     */
    private final static String TEXTANDIMAGESECRETID = "11c62726ba11f03f3f7d87acbe2d4f03";
    /**
     * 文本识别图片识别产品私有密钥,服务端生成签名信息使用,请严格保管,避免泄露
     */
    private final static String TEXTANDIMAGESECRETKEY = "3c0d0d44909926f46e79d3518e7dc4e7";
    /**
     * 业务ID,易盾根据产品业务特点分配(文本)
     */
    private final static String TEXTBUSINESSID = "719926f98dc5b9bb9857e1b799ea3f5f";
    /**
     * 易盾内容安全文本在线检测接口地址
     */
    private final static String TEXT_RESULT = "https://as.dun.163yun.com/v3/text/check";
    /**
     * 业务ID,易盾根据产品业务特点分配(图片)
     */
    private final static String IMAGEBUSINESSID = "f84d6ee9f62274243825d3e969ca4c5a";
    /**
     * 易盾内容安全服务图片在线检测接口地址
     */
    private final static String IMAGE_RESULT = "https://as.dun.163yun.com/v4/image/check";

    public static void main(String[] args) {

        //智能文本识别审核测试
        //getTextFilter("好人");

        //智能图片识别审核测试
        /*JSONArray jsonArray = new JSONArray();
        JSONObject image1 = new JSONObject();
        image1.put("name", UUID.randomUUID());
        image1.put("type", 1);
        image1.put("data", "http://article-bj.bj.bcebos.com//20200326/7f3d23bbb28421e6e2a6f131273554fb_15.jpg?authorization=bce-auth-v1%2F1eda661c3697440eaaca912ccb6f959c%2F2020-03-30T05%3A42%3A21Z%2F604800%2F%2F39f195e2327ef87270bd095fa64dfdcadad6f01a0d6dc6a4313306f164591cc5");
        jsonArray.add(image1);
        JSONObject image2 = new JSONObject();
        image2.put("name", UUID.randomUUID());
        image2.put("type", 1);
        image2.put("data", "http://test.qnvod.cnlive.com/shen/802/2020/03/01/8a8a878c6dce5cfe017096cd07940c84/000002.jpg");
        jsonArray.add(image2);
        JSONObject image3 = new JSONObject();
        image3.put("name", UUID.randomUUID());
        image3.put("type", 1);
        image3.put("data", "https://wjj.ys2.cnliveimg.com/769/img/0/2020/03/21/158474856886077030277.jpg");
        jsonArray.add(image3);
        getImagesFilter(jsonArray.toJSONString());*/

        //智能网页识别审核测试
        //getURLFilter(FILE_URL);
        //getURLFilter("http://3g.huabian.com/api/hz0227/show/440549.html");
    }

    /**
     * 智能文本审核
     *
     * @param text
     * @return
     */
    public static JSONObject getTextFilter(String text) {
        JSONObject jsonObj = new JSONObject();
        try {
            Map<String, String> params = new HashMap<String, String>();
            // 1.设置公共参数
            params.put("secretId", TEXTANDIMAGESECRETID);
            params.put("businessId", TEXTBUSINESSID);
            params.put("version", "v3.1");
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            params.put("nonce", String.valueOf(new Random().nextInt()));

            // 2.设置私有参数
            params.put("dataId", UUID.randomUUID().toString());
            params.put("content", text);

            // 3.生成签名信息
            String signature = genSignature(TEXTANDIMAGESECRETKEY, params);
            params.put("signature", signature);

            // 4.发送HTTP请求
            String result = HttpClientUtils.post_str(TEXT_RESULT, params);
            logger.info("易盾智能文本识别接口返回信息:{}", result);

            if (!StringUtils.isEmpty(result)) {
                JSONObject jsonResult = JSONObject.parseObject(result);
                int code = jsonResult.getIntValue("code");
                String msg = jsonResult.getString("msg");
                JSONObject resultJsonObject = jsonResult.getJSONObject("result");
                if (code == 200 && "ok".equals(msg) && !StringUtils.isEmpty(resultJsonObject)) {
                    //检测结果,0:通过,1:嫌疑,2:不通过
                    int action = resultJsonObject.getIntValue("action");
                    String taskId = resultJsonObject.getString("taskId");
                    if (action == 0) {
                        jsonObj.put("type", "PASS");
                        jsonObj.put("desc", "易盾审核通过");
                    }
                    if (action == 1) {
                        jsonObj.put("type", "REJECT");
                        jsonObj.put("desc", "文本嫌疑");
                    }
                    if (action == 2) {
                        jsonObj.put("type", "REJECT");
                        jsonObj.put("desc", "文本违规");
                    }
                    jsonObj.put("taskId", taskId);
                    logger.info("审核云文本识别处理后结果:{}", jsonObj.toString());
                    return jsonObj;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObj.put("type", "REJECT");
        jsonObj.put("desc", "易盾文本识别其它问题需排查");
        logger.info("审核云文本识别处理后结果:{}", jsonObj.toString());
        return jsonObj;
    }

    /**
     * 智能图片审核
     *
     * @param jsonImg //http://test.qnvod.cnlive.com/shen/802/2020/03/01/8a8a878c6dce5cfe017096cd07940c84/000002.jpg
     * @return
     */
    public static JSONObject getImagesFilter(String jsonImg) {
        JSONObject jsonObj = new JSONObject();
        try {
            Map<String, String> params = new HashMap<String, String>();
            // 1.设置公共参数
            params.put("secretId", TEXTANDIMAGESECRETID);
            params.put("businessId", IMAGEBUSINESSID);
            params.put("version", "v4");
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            params.put("nonce", String.valueOf(new Random().nextInt()));
            params.put("images", jsonImg);

            // 3.生成签名信息
            String signature = genSignature(TEXTANDIMAGESECRETKEY, params);
            params.put("signature", signature);

            // 4.发送HTTP请求,这里使用的是HttpClient工具包,产品可自行选择自己熟悉的工具包发送请求
            String result = HttpClientUtils.post_str(IMAGE_RESULT, params);
            logger.info("易盾智能图片识别接口返回信息:{}", result);

            // 5.解析接口返回值
            if (!StringUtils.isEmpty(result)) {
                JSONObject jsonResult = JSONObject.parseObject(result);
                int code = jsonResult.getIntValue("code");
                String msg = jsonResult.getString("msg");
                int count = 0;
                if (code == 200 && "ok".equals(msg)) {
                    StringBuffer strBuffer = new StringBuffer();
                    strBuffer.append("易盾图片审核");
                    JSONArray antispam = jsonResult.getJSONArray("antispam");
                    if (antispam != null && antispam.size() > 0) {
                        for (int i = 0; i < antispam.size(); i++) {
                            JSONObject jsonObject = antispam.getJSONObject(i);
                            //图片检测状态码,定义为:0:检测成功,610:图片下载失败,620:图片格式错误,630:其它
                            int status = jsonObject.getIntValue("status");
                            //建议动作,2:建议删除,1:建议审核,0:建议通过
                            int action = jsonObject.getIntValue("action");
                            if (status == 0 && action == 1) {
                                strBuffer.append("(第" + (i + 1) + "张图片嫌疑)");
                                count++;
                                continue;
                            }
                            if (status == 0 && action == 2) {
                                strBuffer.append("(第" + (i + 1) + "张图片违规)");
                                count++;
                                continue;
                            }
                            if (status != 0) {
                                strBuffer.append("(第" + (i + 1) + "张图片格式问题)");
                                count++;
                                continue;
                            }
                        }
                        if (count > 0) {
                            jsonObj.put("type", "REJECT");
                            jsonObj.put("desc", strBuffer);
                        } else {
                            jsonObj.put("type", "PASS");
                            jsonObj.put("desc", "易盾图片审核通过");
                        }
                        logger.info("审核云图片识别处理后结果:{}", jsonObj.toString());
                        return jsonObj;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonObj.put("type", "REJECT");
        jsonObj.put("desc", "易盾图片识别其它问题需排查");
        logger.info("审核云图片识别处理后结果:{}", jsonObj.toString());
        return jsonObj;
    }

    /**
     * 图文识别检测接口+获取图文检测结果接口(用于测试)
     *
     * @param url
     * @return
     */
    public static JSONObject getURLFilter(String url) {
        Map<String, String> params = new HashMap<String, String>();

        // 1.设置公共参数
        params.put("secretId", SECRETID);
        params.put("version", "v1.0");
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        params.put("nonce", String.valueOf(new Random().nextInt()));

        // 2.设置私有参数
        //数据唯一标识,能够根据该值定位到该条数据(查询作用)
        params.put("dataId", UUID.randomUUID().toString());
        //网页URL, 支持contentType类型: html、txt、doc、docx、ppt、pptx、xls、xlsx、pdf
        params.put("url", url);
        //1:检测文本,2:检测图片,同时检测文本+图片则以逗号分隔,例:1,2。
        params.put("checkFlags", "1,2");
        //不是必传参数
        params.put("callback", UUID.randomUUID().toString());

        // 3.生成签名信息
        String signature = genSignature(SECRETKEY, params);
        params.put("signature", signature);

        // 4.发送HTTP请求
        //String response = HttpClient4Utils.sendPost(httpClient, API_URL, params, Consts.UTF_8);
        String s = HttpClientUtils.post_str(URL_SUBMIT, params);
        System.out.println("图文检测提交url结果" + s);


        Map<String, String> params1 = new HashMap<String, String>();
        // 1.设置公共参数
        params1.put("secretId", SECRETID);
        params1.put("version", "v1.0");
        params1.put("timestamp", String.valueOf(System.currentTimeMillis()));
        params1.put("nonce", String.valueOf(new Random().nextInt()));

        // 2.生成签名信息
        String signature1 = genSignature(SECRETKEY, params1);
        params1.put("signature", signature1);

        // 3.发送HTTP请求
        String s1 = HttpClientUtils.post_str(URL_RESULT, params1);
        System.out.println("图文检测获取url结果" + s1);

        // 4.解析接口返回值
        JSONObject resultObject = JSONObject.parseObject(s1);
        return resultObject;
    }

    /**
     * 图文识别检测接口
     *
     * @param url
     * @return
     */
    public static JSONObject submitYiDunUrl(String url) {
        try {
            Map<String, String> params = new HashMap<String, String>();

            // 1.设置公共参数
            params.put("secretId", SECRETID);
            params.put("version", "v1.0");
            params.put("timestamp", String.valueOf(System.currentTimeMillis()));
            params.put("nonce", String.valueOf(new Random().nextInt()));

            // 2.设置私有参数
            //数据唯一标识,能够根据该值定位到该条数据(查询作用)
            params.put("dataId", UUID.randomUUID().toString());
            //网页URL, 支持contentType类型: html、txt、doc、docx、ppt、pptx、xls、xlsx、pdf
            params.put("url", url);
            //1:检测文本,2:检测图片,同时检测文本+图片则以逗号分隔,例:1,2。
            params.put("checkFlags", "1,2");
            //不是必传参数
            params.put("callback", UUID.randomUUID().toString());

            // 3.生成签名信息
            String signature = YiDunAntiFraudUtil.genSignature(SECRETKEY, params);
            params.put("signature", signature);

            // 4.发送HTTP请求
            String s = HttpClientUtils.post_str(URL_SUBMIT, params);
            logger.info("向易盾提交网站检测地址返回的结果:{}", s);
            JSONObject jsonObject = JSONObject.parseObject(s);
            int code = jsonObject.getIntValue("code");
            String msg = jsonObject.getString("msg");
            if (code == 200 && "ok".equals(msg)) {
                return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 生成签名信息
     *
     * @param secretKey 产品私钥
     * @param params    接口请求参数名和参数值map,不包括signature参数名
     * @return
     */
    public static String genSignature(String secretKey, Map<String, String> params) {
        // 1. 参数名按照ASCII码表升序排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 2. 按照排序拼接参数名与参数值
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            sb.append(key).append(params.get(key));
        }
        // 3. 将secretKey拼接到最后
        sb.append(secretKey);

        // 4. MD5是128位长度的摘要算法,转换为十六进制之后长度为32字符
        try {
            String s = DigestUtils.md5Hex(sb.toString().getBytes("UTF-8"));
            return s;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

}