该接口文档地址:https://market.cloud.tencent.com/products/6841,公司在使用,目前没发现什么问题
//控制层
@PostMapping("/getAuth")
@ApiOperation(value = "实名认证接口", notes = "")
public GlobalReponse<Object> getAuth(@RequestBody AuthDTO authDTO) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
if (StringUtils.isRealBlank(authDTO.getName()) || StringUtils.isRealBlank(authDTO.getNumber())) {
GlobalReponse.fail("参数不能为空");
}
Long userId = JwtUtil.getCurrentJwtUser().getId();
//Long userId = 1L;
return iCertificationService.getAuth(userId, authDTO);
}
//service
GlobalReponse<Object> getAuth(Long userId, AuthDTO authDTO) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException;
//serviceImpl
/**
* 实名认证接口
*
* @param userId
* @param name
* @param number
* @return
*/
@Override
public GlobalReponse<Object> getAuth(Long userId, AuthDTO authDTO) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
/*//云市场分配的密钥Id
String secretId = secretId;
//云市场分配的密钥Key
String secretKey = secretKey;*/
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("cardNo", authDTO.getNumber());
queryParams.put("realName", authDTO.getName());
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "http://service-hcgajsa5-1253495967.ap-beijing.apigateway.myqcloud.com/release/idcard/VerifyIdcardv2";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
JsonParser jp = new JsonParser();
//将json字符串转化成json对象
JsonObject jo = jp.parse(result).getAsJsonObject();
if (jo.get("error_code").getAsString().equals("0")) {
if (StringUtils.isRealBlank(authDTO.getBackImg()) || StringUtils.isRealBlank(authDTO.getPositiveImg())) {
return GlobalReponse.fail("身份证地址不能为空");
}
System.out.println(jo);
//实名认证成功,插入实名认证表,并更新user表
String sexInfo = jo.get("result").getAsJsonObject().get("IdCardInfor").getAsJsonObject().get("sex").getAsString();
System.out.println(sexInfo);
Certification certification = new Certification();
certification.setUserId(userId);
certification.setName(authDTO.getName());
certification.setIdentityNum(authDTO.getNumber());
certification.setCreateTime(new Date());
certification.setUpdateTime(new Date());
if (!StringUtils.isRealBlank(sexInfo)) {
if ("男".equals(sexInfo)) {
certification.setSex(1);
} else {
certification.setSex(2);
}
}
certification.setIsDelete(0);
certification.setBackImg(authDTO.getBackImg());
certification.setPositiveImg(authDTO.getPositiveImg());
certificationDao.insert(certification);
//去更新user表
User user = userDao.createLambdaQuery().andEq(User::getId, userId).single();
if (CheckUtil.checkObjAllFieldsIsNull(user)) {
return GlobalReponse.fail("用户不存在");
}
user.setName(authDTO.getName());
if (!StringUtils.isRealBlank(sexInfo)) {
if ("男".equals(sexInfo)) {
user.setSex("1");
} else {
user.setSex("2");
}
}
user.setSex(authDTO.getSex());
user.setAuth(1);
userDao.updateTemplateById(user);
}
System.out.println(result);
GlobalReponse g = new GlobalReponse();
g.setCode(1000);
g.setMessage("认证成功");
g.setData(result);
return g;
} catch (Exception e) {
log.error("服务器异常");
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return GlobalReponse.fail("实名认证异常");
}
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}