一 、准备工作
<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
-
}