加载中...

ocr.idcard 微信小程序的身份证 OCR 识别

文章积累知识,如有存在问题,请大家不啬赐教

官方apl地址:

ocr.idcard | 微信开放文档

请求地址

POST https://api.weixin.qq.com/cv/ocr/idcard?type=MODE&img_url=ENCODE_URL&access_token=ACCESS_TOCKEN

请求参数

属性类型默认值必填说明
access_tokenstring接口调用凭证
img_urlstring要检测的图片 url,传这个则不用传 img 参数。
imgFormDataform-data 中媒体文件标识,有filename、filelength、content-type等信息,传这个则不用传 img_url。

分析:请求参数有两种方式:

 1、要检测的图片 url,传这个则不用传 img 参数。

 2、form-data 中媒体文件标识,有filename、filelength、content-type等信息,传这个则不用传 img_url。

方案一:img_url

  1. // 根据imgurl识别身份证
  2. public static JSONObject uploadCard(String type, String imgUrl) throws Exception {
  3. String requestUrl = "https://api.weixin.qq.com/cv/ocr/idcard";
  4. String params = "type=" + type + "&img_url=" + imgUrl + "&access_token=" + getToken();
  5. String url = requestUrl + "?" + params;
  6. String data = MyHttpUtils.doPost(url, null);
  7. JSONObject json = JSONObject.parseObject(data);
  8. String errcode = json.getString("errcode");
  9. if (!"0".equals(errcode)) {
  10. throw new AppletsException("-1", "身份识别失败,请检查图片");
  11. }
  12. return json;
  13. }
  14. // 获取token
  15. public static String getToken() throws Exception {
  16. String strTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + appid + "&secret=" + appsecret;
  17. String resulstrToken = MyHttpUtils.doGet(strTokenUrl);
  18. JSONObject object = JSONObject.parseObject(resulstrToken);
  19. String accessToken = object.getString("access_token");
  20. return accessToken;
  21. }
  22. /**
  23. * 向指定 URL 发送POST方法的请求
  24. *
  25. * @param url 发送请求的 URL
  26. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  27. * @return 所代表远程资源的响应结果
  28. */
  29. public static String doPost(String url, String param) {
  30. PrintWriter out = null;
  31. BufferedReader in = null;
  32. String result = "";
  33. try {
  34. URL realUrl = new URL(url);
  35. // 打开和URL之间的连接
  36. URLConnection conn = realUrl.openConnection();
  37. // 设置通用的请求属性
  38. conn.setRequestProperty("accept", "*/*");
  39. conn.setRequestProperty("connection", "Keep-Alive");
  40. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  41. conn.setRequestProperty("Content-Type", "multipart/form-data;");
  42. // 发送POST请求必须设置如下两行
  43. conn.setDoOutput(true);
  44. conn.setDoInput(true);
  45. // 获取URLConnection对象对应的输出流
  46. out = new PrintWriter(conn.getOutputStream());
  47. // 发送请求参数
  48. out.print(param);
  49. // flush输出流的缓冲
  50. out.flush();
  51. // 定义BufferedReader输入流来读取URL的响应
  52. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
  53. String line;
  54. while ((line = in.readLine()) != null) {
  55. result += line;
  56. }
  57. } catch (Exception e) {
  58. System.out.println("发送 POST 请求出现异常!" + e);
  59. e.printStackTrace();
  60. }
  61. //使用finally块来关闭输出流、输入流
  62. finally {
  63. try {
  64. if (out != null) {
  65. out.close();
  66. }
  67. if (in != null) {
  68. in.close();
  69. }
  70. } catch (IOException ex) {
  71. ex.printStackTrace();
  72. }
  73. }
  74. return result;
  75. }

方案二:img

  1. // 身份证识别
  2. String url = SmallWxUtil.uploadCard("photo");
  3. String postForm = MyHttpUtils.postForm(url, file);
  4. JSONObject object = JSONObject.parseObject(postForm);
  5. String errcode = object.getString("errcode");
  6. if (!"0".equals(errcode)) {
  7. throw new AppletsException("身份识别失败,请上传有效证件");
  8. }
  9. // 请求地址
  10. public static String uploadCard(String type) throws Exception {
  11. String requestUrl = "https://api.weixin.qq.com/cv/ocr/idcard";
  12. String params = "type=" + type + "&access_token=" + getToken();
  13. String url = requestUrl + "?" + params;
  14. return url;
  15. }
  16. /**
  17. * 表单提交参数和文件
  18. *
  19. * @param file
  20. * @return
  21. */
  22. public static String postForm(String urlPath, File file) {
  23. HttpPost httpPost = new HttpPost(urlPath);
  24. CloseableHttpClient httpClient = HttpClients.createDefault();
  25. MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
  26. // 文件参数
  27. // 用特定的字段名,接收方用对应的字段名接收
  28. entityBuilder.addPart("fileName", new FileBody(file));
  29. BufferedReader bufferedReader = null;
  30. InputStream in = null;
  31. try {
  32. HttpEntity httpEntity = entityBuilder.build();
  33. httpPost.setEntity(httpEntity);
  34. RequestConfig config = RequestConfig.custom()
  35. .setConnectTimeout(20000)
  36. .setSocketTimeout(20000) // read time out
  37. .build();
  38. httpPost.setConfig(config); // 请求配置
  39. CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
  40. in = httpResponse.getEntity().getContent();
  41. bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
  42. StringBuffer sb = new StringBuffer();
  43. String readLine = null;
  44. while ((readLine = bufferedReader.readLine()) != null) {
  45. sb.append(readLine);
  46. }
  47. return sb.toString();
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. System.out.println("请求异常");
  51. return null;
  52. } finally {
  53. try {
  54. if (bufferedReader != null) {
  55. bufferedReader.close();
  56. }
  57. if (in != null) {
  58. in.close();
  59. }
  60. } catch (Exception e2) {
  61. e2.printStackTrace();
  62. }
  63. }
  64. }

返回数据示例

正面返回

  1. {
  2. "errcode": "0",
  3. "errmsg": "ok",
  4. "type": "Front",
  5. "name": "张三",
  6. "id": "123456789012345678",
  7. "addr": "广东省广州市",
  8. "gender": "男",
  9. "nationality": "汉"
  10. }

背面返回

  1. {
  2. "errcode": 0,
  3. "errmsg": "ok",
  4. "type": "Back",
  5. "valid_date": "20070105-20270105"
  6. }