1、注册百度云账号 https://cloud.baidu.com/index.html?track=cp:npinzhuan|pf:pc|pp:left|ci:|pu:495
2、注册完成点击
创建应用(应用名称和应用描述自定义)
3、创建应用之后将信息填入后台工具类
4、IdentificationUtil工具类编写如下:
public class IdentificationUtil {
// 身份证识别URL
private static String idcardIdentificate = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
// 获取 access_token URL
private static String GETTOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
// 用户的API_KEY
private static String API_Key = "自己账户的API_Key";
// 用户的Secret_Key
private static String Secret_Key = "自己账户的Secret_Key ";
/**
* 获取API访问token 该token有一定的有效期,需要自行管理,当失效时需重新获取.
*
* @param ak
* - 百度云官网获取的 API Key
* @param sk
* - 百度云官网获取的 Securet Key
* @return assess_token 示例:
* "24.cf4ba2b027cc124bbd210a69ffd137b8.2592000.1527040641.282335-11136581"
*/
public static String getAuth(String ak, String sk) {
// 获取token地址
String getAccessTokenUrl = GETTOKEN_URL
// 1. grant_type为固定参数
+ "?grant_type=client_credentials"
// 2. 官网获取的 API Key
+ "&client_id=" + API_Key
// 3. 官网获取的 Secret Key
+ "&client_secret=" + Secret_Key;
try {
URL realUrl = new URL(getAccessTokenUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
// 获取所有响应头字段
Map> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.err.println(key + " --->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回结果示例
*/
System.err.println("result:" + result);
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
System.err.printf("获取token失败!");
e.printStackTrace(System.err);
}
return null;
}
/**
* 识别获取身份证正面相关信息
*
* @param front
* @return
*/
public static Map identification(String front) {// 执行认证查询
Map map = new HashMap();
try {
// 识别身份证正面id_card_side=front;识别身份证背面id_card_side=back;
// 正面
byte[] imgData = FileUtil.readFileByBytes(front);
String imgStr = Base64Util.encode(imgData);
// 识别身份证正面id_card_side=front;识别身份证背面id_card_side=back;
String params = " id_card_side=front&" + URLEncoder.encode("image", "UTF-8") + "="
+ URLEncoder.encode(imgStr, "UTF-8");
/**
* 线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
*/
String accessToken = getAuth(API_Key, Secret_Key);
String result = HttpUtil.post(idcardIdentificate, accessToken, params);
JSONObject jsonObject = new JSONObject(result);// 转换成JSON格式 身份证正面所有信息
map.put("result", jsonObject);// 身份证所有信息
map.put("address", (JSONObject) jsonObject.getJSONObject("words_result").get("住址"));// 地址
map.put("birth", (JSONObject) jsonObject.getJSONObject("words_result").get("出生"));// 出生
map.put("name", (JSONObject) jsonObject.getJSONObject("words_result").get("姓名"));// 姓名
map.put("IDCard", (JSONObject) jsonObject.getJSONObject("words_result").get("公民身份号码"));// 身份证ID
map.put("sex", (JSONObject) jsonObject.getJSONObject("words_result").get("性别"));// 性别
map.put("nation", (JSONObject) jsonObject.getJSONObject("words_result").get("民族"));// 民族
Set> entrySet = map.entrySet();
for (Entry entry : entrySet) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取身份证背面相关信息
*
* @param back
* @return
*/
public static Map idCardVerify(String back) {
Map map = new HashMap();
try {
// 识别身份证正面id_card_side=front;识别身份证背面id_card_side=back;
byte[] imgData = FileUtil.readFileByBytes(back);
String imgStr = Base64Util.encode(imgData);
// 识别身份证正面id_card_side=front;识别身份证背面id_card_side=back;
String params = " id_card_side=back&" + URLEncoder.encode("image", "UTF-8") + "="
+ URLEncoder.encode(imgStr, "UTF-8");
/**
* 线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
*/
String accessToken = getAuth(API_Key, Secret_Key);
String result = HttpUtil.post(idcardIdentificate, accessToken, params);
JSONObject jsonObject = new JSONObject(result); // 转换成JSON格式 身份证反面所有信息
map.put("result", jsonObject);// 所有信息
map.put("issueDate", (JSONObject) jsonObject.getJSONObject("words_result").get("签发日期"));// 签发日期
map.put("expiryDate", (JSONObject) jsonObject.getJSONObject("words_result").get("失效日期")); // 失效日期
map.put("issueyAuthority", (JSONObject) jsonObject.getJSONObject("words_result").get("签发机关"));// 签发机关
return map;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
5、service层代码调用
/**
* 身份认证
*/
public MsgUtil identification(String name, String front, String back) {
PageData pd = new PageData();
try {
// CommonsMultipartFile[] file = new CommonsMultipartFile[] { front, back };// 上传到本地
// List uploadFile = UploadFile(file, request);/ / 返回图片URL
// 验证身份证有效期 反面
Map idCardVerifyBack = IdentificationUtil.idCardVerify(back);
/ / 获得身份证失效日期
String expiryDate = ((JSONObject) idCardVerifyBack.get("expiryDate")).get("words").toString();
StringBuffer str = new StringBuffer(expiryDate);// 处理日期格式 20180424-->2018-04-24
str.insert(4, "-");
str.insert(7, "-");
String currentTime = getCurrentTime();// 获得当前日期 进行比对
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 格式化
Date cu = dateFormat.parse(currentTime);// 转换成毫秒数 进行比对
Date ex = dateFormat.parse(str.toString());
if (ex.before(cu)) { // 当前时间小于当前时间
return MsgUtil.result(false, "身份证已过期");
}
// 执行认证
Map idCardVerifyFront = IdentificationUtil.identification(front);
/ / 验证姓名是否跟身份证姓名是否匹对
String names = ((JSONObject) idCardVerifyFront.get("name")).get("words").toString();
if (!names.equals(name)) {
return MsgUtil.result(false, "输入姓名与身份证姓名不匹配");
}
// IDCard身份证号码
String IDCard = ((JSONObject) idCardVerifyFront.get("IDCard")).get("words").toString();
// 修改数据库字段填入身份证号码 认证成功
// Vip_info vip = (Vip_info) request.getSession().getAttribute("user");// 获取当前登录用户
Map map = new HashMap();
map.put("uid", pd.getString("uid"));/ /用户编号
map.put("id_card", IDCard);
// mapper.updateIDCardById(map);// 执行修改
dao.update("BtcAppImMapper.updateIDCardById", map);//执行修改
// // 删除上传图片
// for (String path : uploadFile) {
// File f = new File(path);
// f.delete(); // 执行删除
// }
// 认证成功
return MsgUtil.result(true, "认证成功");
} catch (Exception e) {
e.printStackTrace();
return MsgUtil.result(false, "认证失败,请稍后再试");
}
}
6、controller层代码调用
btcAppIdCardService.identification(name, front, back);
注意:文中的工具类支持身份证照片也支持身份证照片路径,注释的部分为上传身份证照片认证
若为上传身份证照片,则字段类型为CommonsMultipartFile
若上传为照片路径,则字段类型为String