Quellcode durchsuchen

添加微信敏感字眼检查接口

wuweihao vor 5 Jahren
Ursprung
Commit
076baa9d28

+ 6 - 0
gis_common/pom.xml

@@ -133,6 +133,12 @@
         </dependency>
 
 
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+        </dependency>
+
+
         <!-- 钉钉sdk -->
         <!--<dependency>-->
             <!--<groupId>com.dingtalk.open</groupId>-->

+ 4 - 0
gis_common/src/main/java/com/gis/common/constant/TypeCode.java

@@ -11,4 +11,8 @@ public class TypeCode {
     /**redis wxToken 前缀*/
     public static final String REDIS_LOGIN_WXTOKEN = "museum_yw_wxToken_";
 
+    public static final String REDIS_WX_ACCESS_TOKEN_KEY = "museum_yw_wxAccessToken";
+
+
+
 }

+ 183 - 0
gis_common/src/main/java/com/gis/common/util/HttpClientUtil.java

@@ -0,0 +1,183 @@
+package com.gis.common.util;
+
+import lombok.extern.log4j.Log4j2;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+import org.springframework.util.CollectionUtils;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+
+/**
+ * @author abnerhou
+ * @date 2020/5/11 17:48
+ * @desciption
+ */
+@Log4j2
+public class HttpClientUtil {
+
+    public static String doGet(String url, Map<String, String> param) {
+
+        // 创建Httpclient对象
+        CloseableHttpClient httpclient = HttpClients.createDefault();
+
+        String resultString = "";
+        CloseableHttpResponse response = null;
+        try {
+            // 创建uri
+            URIBuilder builder = new URIBuilder(url);
+            if (param != null) {
+                for (String key : param.keySet()) {
+                    builder.addParameter(key, param.get(key));
+                }
+            }
+            URI uri = builder.build();
+
+            // 创建http GET请求
+            HttpGet httpGet = new HttpGet(uri);
+
+            // 执行请求
+            response = httpclient.execute(httpGet);
+            // 判断返回状态是否为200
+            if (response.getStatusLine().getStatusCode() == 200) {
+                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
+            }
+        } catch (Exception e) {
+            log.error("http调用执行get出错:{}" , e);
+        } finally {
+            try {
+                if (response != null) {
+                    response.close();
+                }
+                httpclient.close();
+            } catch (IOException e) {
+               log.error("http调用执行get关闭资源出错:{}" , e);
+            }
+        }
+        return resultString;
+    }
+
+    public static String doGet(String url) {
+        return doGet(url, null);
+    }
+
+    public static String doPost(String url, Map<String, Object> param) {
+        // 创建Httpclient对象
+        CloseableHttpClient httpClient = HttpClients.createDefault();
+        CloseableHttpResponse response = null;
+        String resultString = "";
+        try {
+            // 创建Http Post请求
+            HttpPost httpPost = new HttpPost(url);
+//            httpPost.setHeader("contentType" , "application/x-www-form-urlencoded;charset=UTF-8");
+            // 创建参数列表
+            if (param != null) {
+                List<NameValuePair> paramList = new ArrayList<>();
+                for (String key : param.keySet()) {
+                    paramList.add(new BasicNameValuePair(key, param.get(key).toString()));
+                }
+                // 模拟表单
+                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
+                httpPost.setEntity(entity);
+            }
+            // 执行http请求
+            response = httpClient.execute(httpPost);
+            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
+        } catch (Exception e) {
+            log.error("http执行post调用出错:{}" , e);
+        } finally {
+            try {
+                if(null != response){
+                    response.close();
+                }
+            } catch (IOException e) {
+                log.error("http执行post调用关闭资源出错:{}" , e);
+            }
+        }
+
+        return resultString;
+    }
+
+    public static String doPost(String url) {
+        return doPost(url, null);
+    }
+
+    public static String doPostJson(String url, String json) {
+        // 创建Httpclient对象
+        CloseableHttpClient httpClient = HttpClients.createDefault();
+        CloseableHttpResponse response = null;
+        String resultString = "";
+        try {
+            // 创建Http Post请求
+            HttpPost httpPost = new HttpPost(url);
+            // 创建请求内容
+            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
+            httpPost.setEntity(entity);
+            // 执行http请求
+            response = httpClient.execute(httpPost);
+            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
+        } catch (Exception e) {
+            log.error("http执行post调用出错:{}" , e);
+        } finally {
+            try {
+                if(null != response){
+                    response.close();
+                }
+            } catch (IOException e) {
+                log.error("http执行post调用关闭资源出错:{}" , e);
+            }
+        }
+
+        return resultString;
+    }
+
+    public static String doPostJsonWithHeader(String url, String json ,Map<String, Object> headers) {
+        // 创建Httpclient对象
+        CloseableHttpClient httpClient = HttpClients.createDefault();
+        CloseableHttpResponse response = null;
+        String resultString = "";
+        try {
+            // 创建Http Post请求
+            HttpPost httpPost = new HttpPost(url);
+            // 创建请求内容
+            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
+            httpPost.setEntity(entity);
+
+            if(!CollectionUtils.isEmpty(headers)){
+                for (Map.Entry<String,Object> entry : headers.entrySet()){
+                    httpPost.addHeader(entry.getKey() , (String) entry.getValue());
+                }
+            }
+            // 执行http请求
+            response = httpClient.execute(httpPost);
+            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
+        } catch (Exception e) {
+            log.error("http执行post调用出错:{}" , e);
+        } finally {
+            try {
+                if(null != response){
+                    response.close();
+                }
+            } catch (IOException e) {
+                log.error("http执行post调用关闭资源出错:{}" , e);
+            }
+        }
+
+        return resultString;
+    }
+
+}

+ 30 - 0
gis_common/src/main/java/com/gis/common/util/WxUtil.java

@@ -0,0 +1,30 @@
+package com.gis.common.util;
+
+import cn.hutool.http.HttpUtil;
+import com.alibaba.fastjson.JSONObject;
+import lombok.extern.log4j.Log4j2;
+
+
+/**
+ * Created by owen on 2020/7/31 0031 18:20
+ */
+@Log4j2
+public class WxUtil {
+
+
+    public static String getAccessToken(String appId, String appSecret ){
+
+            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
+            String s = HttpUtil.get(url);
+            log.info("s: {}", s);
+            JSONObject result = JSONObject.parseObject(s);
+            String accessToken = result.getString("access_token");
+            log.info("access_token: {}", accessToken);
+            if (accessToken == null) {
+                log.error(result);
+                return null;
+            }
+
+        return accessToken;
+    }
+}

+ 4 - 0
gis_web/pom.xml

@@ -17,6 +17,10 @@
             <groupId>com.gis</groupId>
             <artifactId>gis_service</artifactId>
         </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+        </dependency>
         <!--<dependency>-->
             <!--<groupId>junit</groupId>-->
             <!--<artifactId>junit</artifactId>-->

+ 8 - 4
gis_web/src/main/java/com/gis/web/controller/BaseController.java

@@ -22,6 +22,13 @@ import javax.servlet.http.HttpServletRequest;
 @Slf4j
 public class BaseController {
 
+
+    @Value("${app_id}")
+    public String APP_ID;
+
+    @Value("${app_secret}")
+    public String APP_SECRET;
+
     @Autowired
     protected HttpServletRequest request;
 
@@ -58,10 +65,7 @@ public class BaseController {
         return JwtUtil.getUserId(getToken());
     }
 
-    /** 获取用户角色*/
-//    String getTokenUserRole(){
-//        return JwtUtil.getUserRole(getToken());
-//    }
+
 
 
     /**

+ 84 - 17
gis_web/src/main/java/com/gis/web/controller/WxCommentController.java

@@ -1,6 +1,8 @@
 package com.gis.web.controller;
 
-import com.gis.common.util.Result;
+import com.alibaba.fastjson.JSONObject;
+import com.gis.common.constant.TypeCode;
+import com.gis.common.util.*;
 import com.gis.domain.entity.GoodsEntity;
 import com.gis.domain.entity.WxCommentEntity;
 import com.gis.domain.request.PageRequest;
@@ -13,15 +15,16 @@ import com.github.pagehelper.PageInfo;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.extern.log4j.Log4j2;
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
 import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.web.bind.annotation.*;
 
 import javax.validation.Valid;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
 
 
 /**
@@ -42,6 +45,9 @@ public class WxCommentController extends BaseController {
     @Autowired
     private CommonMapper commonMapper;
 
+    @Autowired
+    private RedisTemplate<String, String> redisTemplate;
+
 
 
     @ApiOperation(value = "列表")
@@ -65,26 +71,43 @@ public class WxCommentController extends BaseController {
 
     @ApiOperation(value = "新增")
     @PostMapping(value = "save")
-    public Result save(@Valid @RequestBody WxCommentRequest param)  {
+    public Result save(@Valid @RequestBody WxCommentRequest param) throws Exception {
 
         WxCommentEntity entity = new WxCommentEntity();
-        BeanUtils.copyProperties(param, entity);
-        entity.setWxId(getWxOpenId());
-        wxCommentService.save(entity);
+        String comment = entity.getComment();
+        String s = wxMsgCheck(comment);
 
+        JSONObject reJson = JSONObject.parseObject(s);
+        Integer errcode = reJson.getInteger("errcode");
 
 
-        GoodsEntity goods = goodsService.findById(param.getGoodsId());
-        if (goods == null) {
-            log.error("对象不存在: {}", param.getGoodsId());
-            return Result.failure("对象不存在");
-        }
+        log.info("result: {}", s);
+        if (errcode == 0) {
 
-        goods.setCountComment(goods.getCountComment() + 1);
+            BeanUtils.copyProperties(param, entity);
+            entity.setWxId(getWxOpenId());
+            wxCommentService.save(entity);
+
+
+
+            GoodsEntity goods = goodsService.findById(param.getGoodsId());
+            if (goods == null) {
+                log.error("对象不存在: {}", param.getGoodsId());
+                return Result.failure("对象不存在");
+            }
+
+            goods.setCountComment(goods.getCountComment() + 1);
+
+            goodsService.update(goods);
+
+            return Result.success();
+        } else {
+            String errmsg = reJson.getString("errmsg");
+            log.error("留言内容违法: {}",errmsg);
+            return Result.failure(errmsg);
+        }
 
-        goodsService.update(goods);
 
-        return Result.success();
     }
 
 
@@ -108,8 +131,52 @@ public class WxCommentController extends BaseController {
     }
 
 
+    /**
+     * 微信api
+     * 检查一段文本是否含有违法违规内容
+     * @param msg
+     * @return
+     * @throws Exception
+     */
+    @Test
+    public String wxMsgCheck(String msg) throws Exception {
+//        String AccessToken = "35_fgwbTUFcmsorNtFCEF0bi1qimwmLizUmo_P8wLki-Tc9Lhvdy9cLyUuVD7tI5mvCGrA4CkMHXL89mxZ5l1BZIO4H5Pjop-ugvPa0OZ1TKFbVqUjLK4xWycqIT6AqGaS1guv54Sq1gr36U_4NCHHgABAKPP";
+        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + getAccessToken();
+//        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + AccessToken;
+
+        JSONObject jsonObject = new JSONObject();
+        jsonObject.put("content", msg);
+
+        return HttpClientUtil.doPostJson(url, jsonObject.toJSONString());
+    }
+
+
+    /**
+     * 获取微信access_token
+     * 有效期7200s, 两小时
+     *
+     * GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
+     */
+    private String getAccessToken(){
 
+        // 校验请求token是否跟redis token一致
+        String accessToken = redisTemplate.opsForValue().get(TypeCode.REDIS_WX_ACCESS_TOKEN_KEY);
+        if (StringUtils.isBlank(accessToken)) {
+             accessToken = WxUtil.getAccessToken(APP_ID, APP_SECRET);
 
 
+            // 更新accessToken
+            // 更新accessToken, 有效期7200s, 旧token无效, 做单用户登录
+            redisTemplate.opsForValue().set(TypeCode.REDIS_WX_ACCESS_TOKEN_KEY, accessToken, Long.parseLong("2"), TimeUnit.HOURS);
+        }
+        return accessToken;
+    }
+
+    @ApiOperation("AccessToken")
+    @GetMapping("get")
+    public Result get(){
+        return Result.success(getAccessToken());
+    }
+
 
 }

+ 5 - 5
gis_web/src/main/java/com/gis/web/controller/WxLoginController.java

@@ -26,11 +26,11 @@ import java.util.concurrent.TimeUnit;
 @RequestMapping("api/wx")
 public class WxLoginController extends BaseController {
 
-    @Value("${app_id}")
-    private String APP_ID;
-
-    @Value("${app_secret}")
-    private String APP_SECRET;
+//    @Value("${app_id}")
+//    private String APP_ID;
+//
+//    @Value("${app_secret}")
+//    private String APP_SECRET;
 
     private static Integer TOKEN_EXPIRE = 1000 * 60 * 60 * 24;