JAVA項目實戰-微信小程序服務端開發(二)


本節繼續分享微信小程序端,實現小程序服務端圖片識別功能,包括:識別身份證,營業執照,行駛證,駕駛證,文本信息等(具體文檔參考:https://developers.weixin.qq.com/miniprogram/dev/framework/)

======================================================

                                      圖片識別工具類

======================================================

 

package com.sf.vsolution.hb.sfce.util.wechat.discern;

import com.alibaba.fastjson.JSON;
import com.sf.vsolution.hb.sfce.config.execption.MyRuntimeException;
import com.sf.vsolution.hb.sfce.util.FuntionUtils;
import com.sf.vsolution.hb.sfce.util.wechat.appletService.AppletServiceConstants;
import com.sf.vsolution.hb.sfce.util.wechat.discern.param.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @description: 圖像識別工具類
 * @author: zhucj
 * @date: 2019-10-17 9:18
 */
@Slf4j
@Component
public class DiscernImgUtil {

    @Value("${applet.appId}")
    private String appId;
    @Value("${applet.secret}")
    private String secret;
    @Value("${applet.secret.discern.imgPath}")
    private String discernPath;


    @Autowired
    private StringRedisTemplate redis;

    /**
     * 小程序端圖片識別
     * @param discernRequest
     *  1:識別
     * @return
     */
    @ApiOperation(value = "小程序服務端-圖片識別")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "discernType",name = "識別類型(1:銀行卡  2:營業執照 3:駕駛證 4:身份證 5:通用印刷體 6:行駛證)"
            ,required = true,dataType = "Integer"),
            @ApiImplicitParam(value = "msg",name = "圖片的MultipartFile對象(暫時只支持傳照片,未寫照片連接情況)",required = true,dataType = "MultipartFile"),
            @ApiImplicitParam(value = "imgType",name = "圖片識別模式 1:photo(拍照模式) 2:scan(掃描模式)",required = true,dataType = "Integer")
    })
    public R appletDiscern(DiscernRequest discernRequest){

        switch (discernRequest.getImgType()){
            case 1:
                discernRequest.setType("photo");
                break;
            case 2:
                discernRequest.setType("scan");
                break;
                default:
                    throw new DisCernImgException(SystemConstants.PARAM_INCORRECT_CODE,AppletDiscernConstant.IMG_TYPE_ERROR);
        }
        //封裝圖片數據
        Map mapImg = new HashMap();
        //封裝參數
        Map mapParam = new HashMap<>();
        mapParam.put("type",discernRequest.getType());
        mapParam.put("access_token",getToken());
        MultipartFile msg = discernRequest.getMsg();

        mapImg.put("img",uploadFile(discernPath+ genRandomName()+".jpg",msg));
        String url = null;
        Class object = null;
        switch (discernRequest.getDiscernType()){
            case 1:
                url = DisCernImgApi.ORC_BANKCARD.getServerName();
                object =  BankCard.class;
                break;
            case 2:
                url = DisCernImgApi.ORC_BIZLICENSE.getServerName();
                object = Bizlicense.class;
                break;
            case 3:
                url = DisCernImgApi.ORC_DRIVINGLICENSE.getServerName();
                object = DriverLicense.class;
                break;
            case 4:
                url = DisCernImgApi.ORC_IDCARD.getServerName();
                object = IDCard.class;
                break;
            case 5:
                url = DisCernImgApi.ORC_COMM.getServerName();
                object = PrintedText.class;
                break;
            case 6:
                url = DisCernImgApi.ORC_DRIVING.getServerName();
                break;
            default:
                throw new DisCernImgException(SystemConstants.PARAM_INCORRECT_CODE,AppletDiscernConstant.DIECERN_TYPE_ERROR);
        }
        String result = HttpClientUtil.postFormData(url, mapParam, mapImg, "image/png");
        log.info("響應信息內容:{}",result);
        DiscernCommonResponse discernCommonResponse = JSON.parseObject(result, DiscernCommonResponse.class);
        if (Objects.equals(AppletDiscernConstant.SUCCESS, discernCommonResponse.getErrcode())){
            return R.ok(JSON.parseObject(result,object));
        }else {
            log.error("獲取照片信息失敗:{}", discernCommonResponse.getErrcode());
            return R.ok(discernCommonResponse.getErrmsg());
        }

    }





    /**
     * 小程序授權
     * @return accessToken
     * @throws  DisCernImgException
     */
    public String getToken(){
        //先從緩存中判斷是否存在
        String redisString = redis.opsForValue().get(AppletDiscernConstant.ACCESS_TOKEN);
        if (Objects.nonNull(redisString)){
            return redisString;
        }
        String reqUrl = AppletServiceConstants.ACCESS_TOKEN_API;
        Map map = new HashMap();
        map.put("grant_type","client_credential");
        map.put("appid",appId);
        map.put("secret",secret);
        String result = HttpClientUtil.doGet(reqUrl, map);
        AuthAccessTokenResponse auth = JSON.parseObject(result, AuthAccessTokenResponse.class);
        //判斷errcode ==0 即請求成功
        if (Objects.equals(auth.getErrcode(),AppletServiceConstants.SUCCESS_CODE)){
            log.info("獲取的accessToken值:{}",auth.getAccess_token());
            //將accessToken存入到redis 設置過期時間
            redis.opsForValue().set(AppletServiceConstants.ACCESS_TOKEN,auth.getAccess_token(),AppletServiceConstants.EXPIRES_IN, TimeUnit.SECONDS);
            return auth.getAccess_token();
        }else {
            log.error("小程序授權失敗返回錯誤碼:{},錯誤信息:{}",auth.getErrcode(),auth.getErrmsg());
            throw new DisCernImgException(SystemConstants.SERVER_ERROR_CODE,AppletDiscernConstant.ACCESS_TOKRN_ERROR);
        }


    }

    /**
     * 上傳文件到本地服務器磁盤
     * @param fileName 上傳文件路徑名稱
     *                 例如: /static/upload/121321321.jpg
     *                      E:/upload/img/12013212.jpg
     * @param file
     * @return
     */
    public static String uploadFile(String fileName, MultipartFile file){

        //服務器端保存的文件對象
        File serverFile= new File(fileName);
        try {
            //判斷文件是否已經存在
            if (serverFile.exists()) {
                throw new DisCernImgException(SystemConstants.PARAM_INCORRECT_CODE,"文件已存在");
            }
            //判斷文件父目錄是否存在
            if (!serverFile.getParentFile().exists()) {
                serverFile.getParentFile().mkdir();
            }
            //將上傳的文件寫入到服務器端文件內
            file.transferTo(serverFile);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return fileName;
    }

public static String genRandomName() {
//取當前時間的長整形值包含毫秒
long millis = System.currentTimeMillis();
//加上三位隨機數
Random random = new Random();
int end3 = random.nextInt(999);
//如果不足三位前面補0
String str = millis + String.format("%03d", end3);

return str;
}
}

=================================================

                   封裝類,常量類,異常類

=================================================

package com.sf.vsolution.hb.sfce.util.wechat.discern;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
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.util.EntityUtils;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

/**
 * @description: get/post請求工具類
 * @author: zhucj
 * @date: 2019-04-26 10:10
 */
@Slf4j
public class HttpClientUtil {

    /**
     * 發送get請求
     * @param url
     * @param param
     * @return
     */
    public static String doGet(String url, Map<String, String> param) {
        log.info("GET請求地址:{},請求參數內容:{}",url, JSON.toJSON(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) {
            e.printStackTrace();
            log.error("網絡出現異常:{}",e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
                log.error("IO出現異常:{}",e.getMessage());
            }
        }
        log.info("GET響應參數:{}",resultString);
        return resultString;
    }

    /**
     * 發送post請求
     * @param url
     * @param param
     * @return
     */
    public static String doPostParam(String url, Map<String, String> param) {
        log.info("GET請求地址:{},請求參數內容:{}",url, JSON.toJSON(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請求
            HttpPost httpPost = new HttpPost(uri);

            // 執行請求
            response = httpclient.execute(httpPost);
            // 判斷返回狀態是否為200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("網絡出現異常:{}",e.getMessage());
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
                log.error("IO出現異常:{}",e.getMessage());
            }
        }
        log.info("GET響應參數:{}",resultString);
        return resultString;
    }

    /**
     * 發post請求 傳入xml/json字符串
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json) {
        log.info("POST請求地址:{},請求參數內容:{}",url,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) {
            e.printStackTrace();
            log.error("網絡出現異常:{}",e.getMessage());
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
                log.error("IO出現異常:{}",e.getMessage());
            }
        }
        log.info("POST響應參數:{}",resultString);
        return resultString;
    }

    /**
     * 發送文件和參數
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @param contentType 沒有傳入文件類型默認采用application/octet-stream
     * contentType非空采用filename匹配默認的圖片類型
     * @return 返回response數據
     */
    @SuppressWarnings("rawtypes")

    public static String postFormData(String urlStr, Map<String, String> textMap,
                                    Map<String, String> fileMap,String contentType) {
        String res = "";
        HttpURLConnection conn = null;
        // boundary就是request頭和上傳文件內容的分隔符
        String BOUNDARY = "---------------------------123821742118716";
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY)
                            .append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }
            // file
            if (fileMap != null) {
                Iterator iter = fileMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String filename = file.getName();

                    //沒有傳入文件類型,同時根據文件獲取不到類型,默認采用application/octet-stream
                    contentType = new MimetypesFileTypeMap().getContentType(file);
                    //contentType非空采用filename匹配默認的圖片類型
                    if(!"".equals(contentType)){
                        if (filename.endsWith(".png")) {
                            contentType = "image/png";
                        }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                            contentType = "image/jpeg";
                        }else if (filename.endsWith(".gif")) {
                            contentType = "image/gif";
                        }else if (filename.endsWith(".ico")) {
                            contentType = "image/image/x-icon";
                        }
                    }
                    if (contentType == null || "".equals(contentType)) {
                        contentType = "application/octet-stream";
                    }
                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY)
                            .append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"; filename=\"" + filename
                            + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                    out.write(strBuf.toString().getBytes());
                    DataInputStream in = new DataInputStream(
                            new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
            }
            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();
            // 讀取返回數據
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("發送POST請求出錯。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }
}
package com.sf.vsolution.hb.sfce.util.wechat.discern;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.ToString;

import java.io.Serializable;

/**
 * 返回類型
 * @author choleece
 * @date 2018/9/27
 */
@ApiModel
@ToString
public class R<T> implements Serializable {

    private static final long serialVersionUID = -6287952131441663819L;

    /**
     * 編碼
     */
    @ApiModelProperty(value = "響應碼", example = "200")
    private int code = 200;

    /**
     * 成功標志
     */
    @ApiModelProperty(value = "成功標志", example = "true")
    private Boolean success;

    /**
     * 返回消息
     */
    @ApiModelProperty(value = "返回消息說明", example = "操作成功")
    private String msg="操作成功";

    /**
     * 返回數據
     */
    @ApiModelProperty(value = "返回數據")
    private T data;

    /**
     * 創建實例
     * @return
     */
    public static R instance() {
        return new R();
    }

    public int getCode() {
        return code;
    }

    public R setCode(int code) {
        this.code = code;
        return this;
    }

    public Boolean getSuccess() {
        return success;
    }

    public R setSuccess(Boolean success) {
        this.success = success;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public R setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public T getData() {
        return data;
    }
    public R setData(T data) {
        this.data = data;
        return this;
    }

    public static R ok() {
        return R.instance().setSuccess(true);
    }

    public static R ok(Object data) {
        return ok().setData(data);
    }

    public static R ok(Object data, String msg) {
        return ok(data).setMsg(msg);
    }

    public static R error() {
        return R.instance().setSuccess(false);
    }

    public static R error(String msg) {
        return error().setMsg(msg);
    }

    /**
     * 無參
     */
    public R() {
    }

    public R(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public R(int code, T data){
        this.code = code;
        this.data = data;
    }

    /**
     * 有全參
     * @param code
     * @param msg
     * @param data
     * @param success
     */
    public R(int code, String msg, T data, Boolean success) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.success = success;
    }

    /**
     * 有參
     * @param code
     * @param msg
     * @param data
     */
    public R(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

}
package com.sf.vsolution.hb.sfce.util.wechat.discern;

/**
 * @description: 圖片識別異常
 * @author: zhucj
 * @date: 2019-10-17 10:16
 */
public class DisCernImgException extends RuntimeException  {


    private Integer errcode;

    private String errmsg;


    public DisCernImgException(Integer errcode, String errmsg) {
        this.errcode = errcode;
        this.errmsg = errmsg;
    }

    public Integer getErrcode() {
        return errcode;
    }

    public void setErrcode(Integer errcode) {
        this.errcode = errcode;
    }

    public String getErrmsg() {
        return errmsg;
    }

    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

/**
 * @description: 小程序API常量
 * @author: zhucj
 * @date: 2019-09-17 18:25
 */
public class AppletDiscernConstant {


    /**
     * 小程序登錄API
     */
    public static final String AUTH_CODE_API = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * accessToken授權API
     */
    public static final String ACCESS_TOKEN_API = "https://api.weixin.qq.com/cgi-bin/token";
    /**
     * 客服消息API
     */
    public static final String  MESSAGE_SEND_API = "https://api.weixin.qq.com/cgi-bin/message/custom/send";


    /**
     * accessToken緩存key
     */
    public static final String ACCESS_TOKEN = "ACCESS_TOKEN";

    public static final Integer EXPIRES_IN  = 7000;


    //TODO: 異常信息狀態


    public static final String ACCESS_TOKRN_ERROR = "小程序授權獲取accessToken失敗";
    public static final String DIECERN_TYPE_ERROR = "diecernType傳參格式不支持";
    public static final String IMG_TYPE_ERROR = "imgType傳參格式不支持";

    public static final String SUCCESS = "0";
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import com.sf.vsolution.hb.sfce.util.wechat.appletService.param.CommonResponse;
import lombok.*;

/**
 * @description: 小程序獲取AccessToken返回參數
 * @author: zhucj
 * @date: 2019-11-14 16:43
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class AuthAccessTokenResponse extends CommonResponse {


    /**
     * 獲取到的憑證
     */
    private String access_token;

    /**
     * 憑證有效時間,單位:秒。目前是7200秒之內的值。
     */
    private Integer expires_in;
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import lombok.Data;

/**
 * @description: 識別銀行卡號返回參數
 * @author: zhucj
 * @date: 2019-10-17 12:55
 */
@Data
public class BankCard extends DiscernCommonResponse {

    /**
     * 銀行卡號
     */
    private String number;
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import lombok.Data;

/**
 * @description: 識別營業執照返回參數
 * @author: zhucj
 * @date: 2019-10-17 12:57
 */
@Data
public class Bizlicense extends DiscernCommonResponse {

    /**
     * 注冊號
     */
    private String reg_num;

    /**
     * 編號
     */
    private String serial;

    /**
     * 法定代表人姓名
     */
    private String legal_representative;

    /**
     * 企業名稱
     */
    private String enterprise_name;

    /**
     * 組成形式
     */
    private String type_of_organization;

    /**
     * 經營場所/企業住所
     */
    private String address;

    /**
     * 公司類型
     */
    private String type_of_enterprise;

    /**
     * 經營范圍
     */
    private String business_scope;

    /**
     * 注冊資本
     */
    private String registered_capital;

    /**
     * 實收資本
     */
    private String paid_in_capital;

    /**
     * 營業期限
     */
    private String valid_period;


    /**
     * 注冊日期/成立日期
     */
    private String registered_date;



}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import lombok.*;

/**
 * @description: 通用返回參數
 * @author:zhucj
 * @date: 2019-10-17 9:25
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ToString
public class DiscernCommonResponse {

    /**
     * 響應編碼
     */
    private String errcode;

    /**
     * 響應消息
     */
    private String errmsg;
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

/**
 * @description: 圖片識別常量
 * @author: zhucj
 * @date: 2019-10-17 9:48
 */
public class DisCernConstant {


    /**
     * 共用接口
     */
    public static final String  WX_DISCERN_SERVER_API = "https://api.weixin.qq.com";

    /**
     * 小程序的銀行卡 OCR 識別
     */
    public static final String  WX_BANKCARD_DISCERN_SERVER_NAME = "/cv/ocr/bankcard";

    /**
     * 小程序的營業執照 OCR 識別
     */
    public static final String  WX_BUCINESS_DISCERN_SERVER_NAME = "/cv/ocr/bizlicense";

    /**
     * 小程序的駕駛證 OCR 識別
     */
    public static final String  WX_DRIVER_DISCERN_SERVER_NAME = "/cv/ocr/drivinglicense";

    /**
     * 小程序的身份證 OCR 識別
     */
    public static final String  WX_IDCARD_DISCERN_SERVER_NAME = "/cv/ocr/idcard";

    /**
     * 小程序的通用印刷體 OCR 識別
     */
    public static final String  WX_PRINTED_DISCERN_SERVER_NAME = "/cv/ocr/comm";

    /**
     * 小程序的行駛證 OCR 識別
     */
    public static final String  WX_DRIVING_DISCERN_SERVER_NAME = "/cv/ocr/driving";

}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import com.sf.vsolution.hb.sfce.util.wechat.discern.param.DisCernConstant;

/**
 * @description: 圖片識別API
 * @author: zhucj
 * @date: 2019-10-17 9:44
 */
public enum  DisCernImgApi {
    /**
     * 小程序端識別
     */
    ORC_BANKCARD(1, DisCernConstant.WX_DISCERN_SERVER_API+DisCernConstant.WX_BANKCARD_DISCERN_SERVER_NAME),
    ORC_BIZLICENSE(2,DisCernConstant.WX_DISCERN_SERVER_API+DisCernConstant.WX_BUCINESS_DISCERN_SERVER_NAME),
    ORC_DRIVINGLICENSE(3,DisCernConstant.WX_DISCERN_SERVER_API+DisCernConstant.WX_DRIVER_DISCERN_SERVER_NAME),
    ORC_IDCARD(4,DisCernConstant.WX_DISCERN_SERVER_API+DisCernConstant.WX_IDCARD_DISCERN_SERVER_NAME),
    ORC_COMM(5,DisCernConstant.WX_DISCERN_SERVER_API+DisCernConstant.WX_PRINTED_DISCERN_SERVER_NAME),
    ORC_DRIVING(6,DisCernConstant.WX_DISCERN_SERVER_API+DisCernConstant.WX_DRIVING_DISCERN_SERVER_NAME)
    ;

    private int discernType;

    private String  serverName;

    DisCernImgApi(int discernType, String serverName) {
        this.discernType = discernType;
        this.serverName = serverName;
    }

    public int getDiscernType() {
        return discernType;
    }

    public void setDiscernType(int discernType) {
        this.discernType = discernType;
    }

    public String getServerName() {
        return serverName;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import lombok.Builder;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

/**
 * @description: 識別請求信息
 * @author: zhucj
 * @date: 2019-10-17 9:31
 */
@Data
@Builder
public class DiscernRequest {

    /**
     * 識別類型
     * 1:銀行卡  2:營業執照 3:駕駛證 4:身份證 5:通用印刷體 6:行駛證
     */
    private Integer discernType;

    /**
     * 圖片識別模式 1:photo(拍照模式) 2:scan(掃描模式)
     */
    private Integer imgType;

    /**
     * form-data 中媒體文件標識,有filename、filelength、content-type等信息,傳這個則不用傳 img_url
     */
    private MultipartFile msg;


    private String type;
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import lombok.Data;

/**
 * @description: 識別駕駛證返回參數
 * @author: zhucj
 * @date: 2019-11-15 13:51
 */
@Data
public class DriverLicense extends DiscernCommonResponse {

    /**
     * 證號
     */
    private String id_num;

    /**
     * 姓名
     */
    private String name;
    /**
     *性別
     */
    private String sex;

    /**
     * address
     */
    private String address;

    /**
     * 出生日期
     */
    private String birth_date;

    /**
     * 初次領證日期
     */
    private String issue_date;

    /**
     * 准駕車型
     */
    private String car_class;

    /**
     * 有效期限起始日
     */
    private String valid_from;

    /**
     * 有效期限終止日
     */
    private String valid_to;

    /**
     * 印章文構
     */
    private String official_seal;
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import lombok.Data;

/**
 * @description: 身份證識別返回參數
 * @author: zhucj
 * @date: 2019-11-15 14:02
 */
@Data
public class IDCard extends DiscernCommonResponse {

    /**
     * 姓名
     */
    private String name;

    /**
     * 身份證號
     */
    private String id;

    /**
     * 地址
     */
    private String addr;

    /**
     * 性別
     */
    private String gender;

    /**
     * 民族
     */
    private String nationality;

    /**
     * 正面或背面,Front / Back
     */
    private String type;

    /**
     * 有效期(type = back 才有)
     */
    private String validDate;
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

import lombok.Data;

/**
 * @description:
 * @author:zhucj
 * @date: 2019-10-17 15:22
 */
@Data
public class PrintedText extends DiscernCommonResponse {

    private String items;

    private String img_size;
}
package com.sf.vsolution.hb.sfce.util.wechat.discern.param;

/**
 * @ClassName SystemConstants
 * @Description 常量字段
 * @Author zhucj
 * @Date 2019/5/7 11:13
 * @Version 1.0
 **/
public class SystemConstants {


    /** 傳參不規范,code:400*/
    public static final Integer PARAM_INCORRECT_CODE = 400;

    /** 成功,code:200*/
    public static final Integer SUCCESS_CODE = 200;

    /** 服務內部調用失敗,code:500*/
    public static final Integer SERVER_ERROR_CODE = 500;

    /** 登錄失效,code:401*/
    public static final Integer AUTH_FAIL_CODE = 401;

    /** 無對應接口權限,code:402*/
    public static final Integer HAVE_NOT_PERMISSION_CODE = 402;

    /** 操作無記錄,code:403*/
    public static final Integer NO_RECORD_OPERATION = 403;


}
#小程序參數
applet:
  appId: *****
  secret: *****
  discern:
   #識別圖片保存地址
    imgPath: E:/upload/img/

 

       <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>

       <!--htttpclient依賴-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>

    <!-- swagger API -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.0</version>
        </dependency>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM