微信小程序發佈須要校驗敏感信息(內容、圖片)-Java後端實現

微信官方文檔(內容安全接口開發文檔): https://mp.weixin.qq.com/cgi-bin/announce?action=getannouncement&key=11522142966rk3L2&version=1&lang=zh_CN&platform=2前端

前端只須要將圖片和內容傳過來便可java

pom依賴

HttpClient的依賴和json轉換的依賴web

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.54</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

封裝Vo類

用於獲取到access_token後進行轉換,access_token是什麼就不用我多少了吧spring

public class AccessTokenVO {
    private String access_token;
    private Integer expires_in;
    //記得給get set方法
}

封裝工具類

import com.alibaba.fastjson.JSONObject;
import com.itheima.fete.pojo.AccessTokenVO;
import org.apache.http.HttpEntity;
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.entity.ByteArrayEntity;
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.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author manlu
 */
public class SenInfoCheckUtil {
    /**
     * 圖片違規檢測,對外提供,直接使用
     *
     * @param accessToken
     * @param file
     * @return
     */
    public static Boolean imgFilter(String accessToken, MultipartFile file) {
        String contentType = file.getContentType();
        return checkPic(file, accessToken, contentType);
    }

    /**
     * 文本違規檢測,對外提供,直接使用
     *
     * @param accessToken
     * @param content
     * @return
     */
    public static Boolean cotentFilter(String accessToken, String content) {
        return checkContent(accessToken, content);
    }

    /**
     * 校驗圖片是否有敏感信息
     *
     * @param multipartFile
     * @return
     */
    private static Boolean checkPic(MultipartFile multipartFile, String accessToken, String contentType) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken);
            request.addHeader("Content-Type", "application/octet-stream");
            InputStream inputStream = multipartFile.getInputStream();
            byte[] byt = new byte[inputStream.available()];
            inputStream.read(byt);
            request.setEntity(new ByteArrayEntity(byt, ContentType.create(contentType)));
            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 轉成string
            JSONObject jso = JSONObject.parseObject(result);
            return getResult(jso);
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

    /**
     * 校驗內容是否有敏感信息
     * @param accessToken
     * @param content
     * @return
     */
    private static Boolean checkContent(String accessToken, String content) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            HttpPost request = new HttpPost("https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken);
            request.addHeader("Content-Type", "application/json");
            Map<String, String> map = new HashMap<>();
            map.put("content", content);
            String body = JSONObject.toJSONString(map);
            request.setEntity(new StringEntity(body, ContentType.create("text/json", "UTF-8")));
            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 轉成string
            JSONObject jso = JSONObject.parseObject(result);
            return getResult(jso);
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

    /**
     * 返回狀態信息,能夠修改成本身的邏輯
     * @param jso
     * @return
     */
    private static Boolean getResult(JSONObject jso) {
        Object errcode = jso.get("errcode");
        int errCode = (int) errcode;
        if (errCode == 0) {
            return true;
        } else if (errCode == 87014) {
            return false;
        } else {
            return false;
        }
    }

    /**
     * 獲取小程序的 access_token
     * @return
     */
    public static String getAccessToken() {
        AccessTokenVO accessTokenVO = null;
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            //改爲本身的appid和secret
            HttpGet request = new HttpGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxbh0594d32gf315&secret=c9864f6e8aafg8313b6d5d608bd6a6b");
            request.addHeader("Content-Type", "application/json");
            response = httpclient.execute(request);
            HttpEntity httpEntity = response.getEntity();
            String result = EntityUtils.toString(httpEntity, "UTF-8");// 轉成string
            accessTokenVO = JSONObject.parseObject(result, AccessTokenVO.class);
            //返回token
            return accessTokenVO.getAccess_token();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

編寫Controller層

import com.itheima.fete.utils.SenInfoCheckUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 漫路h
 * 校驗內容是否敏感
 */
@RestController
@RequestMapping("/check")
public class CheckController {
    /**
     * 校驗內容
     * @param content
     * @return
     * @throws IOException
     */
    @GetMapping("/content/{content}")
    public Boolean checkContent(@PathVariable String content) {
        System.out.println(content);
        String accessToken = SenInfoCheckUtil.getAccessToken();
        return SenInfoCheckUtil.cotentFilter(accessToken, content);
    }

    /**
     * 校驗圖片
     * @param multipartFile
     * @return
     */
    @PostMapping("/image")
    public Boolean checkImage(@RequestPart(value = "file") MultipartFile multipartFile){
        String accessToken = SenInfoCheckUtil.getAccessToken();
        return SenInfoCheckUtil.imgFilter(accessToken, multipartFile);
    }
}

若是不明白就問,若是須要uniapp代碼的kou我apache

相關文章
相關標籤/搜索