一 、準備工作
<1>域名認證準備工作
在需要調用攝像頭的接口頁面引入微信的js,具體地址爲:(支持https):http://res.wx.qq.com/open/js/jweixin-1.2.0.js
首先JS安全接口域名認證:
具體可參考開發文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
填寫規則(必須是備案通過的域名):
若域名類似爲:xxx.xxx.xxx.com 則接口域名爲:xxx.xxx.com
若域名類似爲:xxx.xxx.com 則接口域名爲:xxx.com
若域名類似爲:xxx.xxx.com:8080 則接口域名爲:xxx.com:8080
<2>OCR識別準備工作
註冊百度雲服務賬號,網址:https://cloud.baidu.com/index.html?track=cp:npinzhuan|pf:pc|pp:left|ci:|pu:495
點擊智能控制檯>>產品服務>>人工智能>>文字識別>>創建應用
填寫相關信息選擇對應的需求
點擊創建應用>>查看詳情:appid、apikey、secretkey是我們所需要的
二、具體代碼實現
在需要調用微信js的jsp頁面引入js,做如下操作:
- $(function (){
- wx.config({
- debug: true, // 開啓調試模式,調用的所有api的返回值會在客戶端alert出來,測試完成後需要關閉。
- appId: $('#appId').val(), // 必填,公衆號的唯一標識
- timestamp: $('#timestamp').val(), // 必填,生成簽名的時間戳
- nonceStr: $('#nonceStr').val(), // 必填,生成簽名的隨機串
- signature: $('#signature').val(),// 必填,簽名(加密後,下文有實現)
- jsApiList: ['chooseImage', 'uploadImage'] // 必填,需要使用的JS接口列表,開發文檔上有所有接口名稱,根據需要選用就好。
- });
- });
-
-
- function openCamera(){
- wx.chooseImage({
- count: 1, // 默認9
- sizeType: ['original', 'compressed'], // 指定是原圖還是壓縮圖,默認都有
- sourceType: ['album', 'camera'], // 指定來源是相冊還是相機,默認都有
- success: function (res) {
- var localIds = res.localIds; // 返回選定照片的本地ID列表,localId可以作爲img標籤的src屬性顯示圖片
- wx.uploadImage({
- localId: localIds.toString(), // 需要上傳的圖片的ID,由chooseImage接口獲得
- isShowProgressTips: 1, // 進度提示
- success: function (res) {
- var mediaId = res.serverId; // 返回圖片的服務器端ID,即mediaId
- //將獲取到的 mediaId 傳入後臺 方法savePicture
- $.post(path+"/getImage/savePicture",{"mediaId":mediaId,"tmp":"填寫證件的正反面參數"},function(res){
- //填寫你自己的業務邏輯
- });
- },
- fail: function (res) {
- alertModal('圖片上傳失敗,請重試');
- }
- });
- }
- });
- }
wx.config這個函數是進行js域名驗證所必須的操作,具體實現如下:
- //-------------------------初始化js-sdk--------begin----------------------------
- SortedMap<Object, Object> params = new TreeMap<Object, Object>();
- String access_token = WechatAppUtil.getAccessToken(appid,appSecret);// 建議放redis放緩存中(access_token )
- String jsapi_ticket = WechatAppUtil.getJsapiTicket(access_token);
- String noncestr = WechatSignUtil.getNonceStr();
- String timestamp = WechatSignUtil.getTimestamp();
- params.put("noncestr", noncestr);
- params.put("jsapi_ticket", jsapi_ticket);
- params.put("timestamp", timestamp);
- StringBuffer url = cRequest.getRequestURL();
- Enumeration<String> headerNames = cRequest.getHeaderNames();
- if (headerNames != null) {
- while (headerNames.hasMoreElements()) {
- String header = headerNames.nextElement();
- log.info("Header: {}, Value={}", header, cRequest.getHeader(header));
- }
- }
- String httpFlag = cRequest.getHeader("X-Forwarded-Proto");
- if (httpFlag != null && httpFlag.equals("https")) {
- url.replace(0, 5, "https");
- }
- String queryString = cRequest.getQueryString();
- log.info("queryString={}", queryString);
- if (StringUtil.isNotEmpty(queryString)) {
- url.append("?").append(cRequest.getQueryString());
- }
- params.put("url", url.toString());
- log.info("url---------------->:"+url.toString());
- String sign = WechatSignUtil.createSignBySha1(params);
- log.info("sign---------------->:"+sign);
- //-------------------------初始化js-sdk--------end----------------------------
- ModelAndView tView = new ModelAndView(LoginPageConstant.STAFF_REGIST2);
- tView.addObject("appId", appid);
- tView.addObject("timestamp", timestamp);
- tView.addObject("nonceStr", noncestr);
- tView.addObject("signature", sign); return tView;
- /**
- * @Title: getAccessToken
- * @Description: 獲取公衆號access_token
- * @param @param appId
- * @param @param appSecret
- * @param @return
- * @return String 返回類型
- * @throws
- */
- public static String getAccessToken(String appId,String appSecret){
- final String param = "grant_type=client_credential" + "&appid=" + appId + "&secret=" + appSecret;
- final String data = HttpClientUtil.get(GET_ACCESS_TOKEN_PATH, param);
- JSONObject resultJson = JSON.parseObject(data);
- String access_token = resultJson.getString("access_token");
- return access_token;
- }
-
- /**
- *
- * @Title: getJsapiTicket
- * @Description: 獲取JsapiTicket
- * @param @param access_token
- * @param @return
- * @return String 返回類型
- * @throws
- */
- public static String getJsapiTicket(String access_token){
- final String param = "access_token="+access_token+ "&type=jsapi";
- final String data = HttpClientUtil.get(GET_JSAPI_TICKET, param);
- JSONObject resultJson = JSON.parseObject(data);
- String jsapi_ticket = resultJson.getString("ticket");
- return jsapi_ticket;
- }/**
- *
- * @Title: getNonceStr
- * @Description: 生成隨機字符串
- * @param @return
- * @return String 返回類型
- * @throws
- */
- public static String getNonceStr() {
- String currT = getCurrTime();
- String strT = currT.substring(8, currT.length());
- String strRandom = buildRandom(4) + "";
- return strT + strRandom;
- }
-
-
- /**
- *
- * @Title: buildRandom
- * @Description: 生成隨機數
- * @param @param length
- * @param @return
- * @return int 返回類型
- * @throws
- */
- public static int buildRandom(int length) {
- int mm= 1;
- double random = Math.random();
- if (random < 0.1) {
- random = random + 0.1;
- }
- for (int i = 0; i < length; i++) {
- mm= mm* 10;
- }
- return (int) ((random * mm));
- }
-
-
- /**
- *
- * @Title: getCurrTime
- * @Description: 獲取當前時間
- * @param @return
- * @return String 返回類型
- * @throws
- */
- public static String getCurrTime() {
- Date date = new Date();
- SimpleDateFormat of= new SimpleDateFormat("yyyyMMddHHmmss");
- String s = of.format(date);
- return s;
- }
-
- /**
- *
- * @Title: createSignBySha1
- * @Description: 生成簽名
- * @param @param params
- * @param @return
- * @return String 返回類型
- * @throws
- */
- @SuppressWarnings("rawtypes")
- public static String createSignBySha1(SortedMap<Object, Object> params) {
- StringBuffer sb = new StringBuffer();
- Set es = params.entrySet();
- Iterator it = es.iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- String k = (String) entry.getKey();
- String v = (String) entry.getValue();
- if (v != null && !v.equals("")) {
- sb.append(k + "=" + v + "&");
- }
- }
- String result = sb.toString().substring(0, sb.toString().length()-1);
- return getSHA1(result);
- }
- /**
- *
- * @Title: getTimestamp
- * @Description: 獲取時間戳(秒)
- * @param @return 參數
- * @return String 返回類型
- * @throws
- */
- public static String getTimestamp() {
- return String.valueOf(System.currentTimeMillis() / 1000);
- }
-
-
- /**
- *
- * @Title: getSHA1
- * @Description: SHA1簽名生成
- * @param @param str
- * @param @return 參數
- * @return String 返回類型
- * @throws
- */
- public static String getSHA1(String str){
- StringBuffer hexstr = new StringBuffer();
- try {
- MessageDigest md = MessageDigest.getInstance("SHA-1");
- md.update(str.getBytes());
- byte[] digest = md.digest();
- String shaHex = "";
- for (int i = 0; i < digest.length; i++) {
- shaHex = Integer.toHexString(digest[i] & 0xFF);
- if (shaHex.length() < 2) {
- hexstr.append(0);
- }
- hexstr.append(shaHex);
- }
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- }
- return hexstr.toString();
- }
驗證完成後臺實現如下:
- /**
- *
- * @Title: savePicture
- * @Description: 接收圖片
- * @param @param request
- * @param @return
- * @return String 返回類型
- * @throws
- */
- @ResponseBody
- @RequestMapping("/savePicture")
- public String savePicture(HttpServletRequest request) {
- String mediaId = request.getParameter("mediaId");
- String tmp = request.getParameter("tmp");
- String filename = saveImageToDisk(mediaId,tmp,request);
- log.info("filename----------->:"+filename);
- return "success";
- }
-
- /**
- *
- * @Title: saveImageToDisk
- * @Description: 存盤
- * @param @param mediaId
- * @param @return
- * @return String 返回類型
- * @throws
- */
- private String saveImageToDisk(String mediaId,String tmp,HttpServletRequest request){
- String filename = "";
- InputStream inputStream = getMedia(mediaId);
- byte[] data = new byte[1024];
- int len = 0;
- FileOutputStream fileOutputStream = null;
- try {
- //服務器存圖路徑
- String path = request.getServletContext().getRealPath("你需要存放的服務器路徑");
- filename = System.currentTimeMillis() + WechatSignUtil.getNonceStr() + ".jpg";
- fileOutputStream = new FileOutputStream(path + filename);
- while ((len = inputStream.read(data)) != -1) {
- fileOutputStream.write(data, 0, len);
- }
- WeChatUser idCardMsg = getIdCardMsg(tmp,path + filename);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (fileOutputStream != null) {
- try {
- fileOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return filename;
- }
-
- /**
- *
- * @Title: getMedia
- * @Description: 獲取圖片
- * @param @param mediaId
- * @param @return 參數
- * @return InputStream 返回類型
- * @throws
- */
- private InputStream getMedia(String mediaId) {
- String url = "https://api.weixin.qq.com/cgi-bin/media/get";
- String access_token = WechatAppUtil.getAccessToken("**********","*************");
- String params = "access_token=" + access_token + "&media_id=" + mediaId;
- InputStream is = null;
- try {
- String urlNameString = url + "?" + params;
- URL urlGet = new URL(urlNameString);
- HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
- http.setRequestMethod("GET"); // 必須是get方式請求
- http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
- http.setDoOutput(true);
- http.setDoInput(true);
- http.connect();
- // 獲取文件轉化爲byte流
- is = http.getInputStream();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return is;
- }
-
- /**
- *
- * @Title: getIdCardMsg
- * @Description:
- * @param @param tmp
- * @param @param imgUrl 圖片路徑
- * @param @return
- * @return WeChatUser 返回類型
- * @throws
- */
- private WeChatUser getIdCardMsg(String tmp,String imgUrl){
- // 初始化一個AipOcr
- AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
- // 可選:設置網絡連接參數
- client.setConnectionTimeoutInMillis(2000);
- client.setSocketTimeoutInMillis(60000);
- // 傳入可選參數調用接口
- HashMap<String, String> options = new HashMap<String, String>();
- options.put("detect_direction", "true");
- options.put("detect_risk", "false");
- String idCardSide = tmp;
- // 參數爲圖片路徑
- String image = imgUrl;
- JSONObject res = client.idcard(image, idCardSide, options);
- 具體返回信息處理請參考開發文檔:https://cloud.baidu.com/doc/OCR/OCR-Java-SDK.html#.E6.8E.A5.E5.8F.A3.E8.83.BD.E5.8A.9B
- }