腾讯云接口文档:
1.获取 AccessToken https://cloud.tencent.com/document/product/1007/37304
2.获取 SIGN ticket
https://cloud.tencent.com/document/product/1007/37305
3.合作方后台上送身份信息
https://cloud.tencent.com/document/product/1007/35893
附代码实战
1.maven依赖【httpclient】
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
配置文件配置httpclient
#http设置
http:
#最大连接数
maxTotal: 100
defaultMaxPerRoute: 20
#连接超时时间
connectTimeout: 1000
#从连接池中获取到连接的最长时间
connectionRequestTimeout: 500
#数据传输的最长时间
socketTimeout: 10000
#提交请求前测试连接是否可用
staleConnectionCheckEnabled: true
2.FaceConfig 配置
public class FaceConfig {
//wbappid
public static final String APP_ID = "自己腾讯云申请";
//wbappid对应的密钥
public static final String Secret = "自己腾讯云申请";
//授权类型
public static final String grant_type = "client_credential";
//版本号
public static final String version = "1.0.0";
//ticket 类型
public static final String type = "SIGN";
//访问 Access Tokend地址
public static final String Access_Token_URL = "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token";
//获取 SIGN ticket
public static final String SIGN_ticket_URL = "https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket";
//生成签名
public static final String signature_URL="https://miniprogram-kyc.tencentcloudapi.com/api/server/h5/geth5faceid";
}
3.工具类
3.1HttpClientUtil
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.*;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/*
* 利用HttpClient进行post请求的工具类
*/
public class HttpClientUtil {
public String doPost(String url,String xmlParam,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClientUtil();
httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setEntity(new StringEntity(xmlParam, HTTP.UTF_8));
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
public static String sendGetRequest(String reqURL, String decodeCharset){
long responseLength = 0; //响应长度
String responseContent = null; //响应内容
HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例
HttpGet httpGet = new HttpGet(reqURL); //创建org.apache.http.client.methods.HttpGet
try{
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity(); //获取响应实体
// if(null != entity){
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, decodeCharset==null ? "UTF-8" : decodeCharset);
// }
System.out.println("请求地址: " + httpGet.getURI());
System.out.println("响应状态: " + response.getStatusLine());
System.out.println("响应长度: " + responseLength);
System.out.println("响应内容: " + responseContent);
}catch(Exception e){
}
return responseContent;
}
public static final String sendHttpsRequestByPost(String url, Map<String, String> params) {
String responseContent = null;
HttpClient httpClient = new DefaultHttpClient();
//创建TrustManager
X509TrustManager xtm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
//这个好像是HOST验证
X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
public void verify(String arg0, SSLSocket arg1) throws IOException {}
public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
public void verify(String arg0, X509Certificate arg1) throws SSLException {}
};
try {
//TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
SSLContext ctx = SSLContext.getInstance("TLS");
//使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
ctx.init(null, new TrustManager[] { xtm }, null);
//创建SSLSocketFactory
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
socketFactory.setHostnameVerifier(hostnameVerifier);
//通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); // 获取响应实体
if (entity != null) {
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
httpClient.getConnectionManager().shutdown();
}
return responseContent;
}
}
JsonUtil
import com.google.gson.Gson;
import java.lang.reflect.Type;
/**
* Java对象和JSON字符串相互转化工具类
* @author penghuaiyi
* @date 2013-08-10
*/
public final class JsonUtil {
public JsonUtil(){}
/**
* 对象转换成json字符串
* @param obj
* @return
*/
public static String toJson(Object obj) {
Gson gson = new Gson();
return gson.toJson(obj);
}
/**
* json字符串转成对象
* @param str
* @param type
* @return
*/
public static <T> T fromJson(String str, Type type) {
Gson gson = new Gson();
return gson.fromJson(str, type);
}
/**
* json字符串转成对象
* @param str
* @param type
* @return
*/
public static <T> T fromJson(String str, Class<T> type) {
Gson gson = new Gson();
return gson.fromJson(str, type);
}
}
QianMingUitls
import java.util.List;
public class QianMingUitls {
public static String getqianming(List<String> list,String apiticket) throws Exception{
String string = Sha1Uitls.sign(list, apiticket);
return string;
}
}
Sha1Uitls
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import java.util.Collections;
import java.util.List;
/**
*
* [sha1加密排序工具类]
*/
public class Sha1Uitls {
public static String sign(List<String> values, String ticket) {
if (values == null) {
throw new NullPointerException("values is null");
}
values.removeAll(Collections.singleton(null));// remove null
values.add(ticket);
Collections.sort(values);
StringBuilder sb = new StringBuilder();
for (String s : values) {
sb.append(s);
}
System.out.println("排序后的值是"+sb);
return Hashing.sha1().hashString(sb, Charsets.UTF_8).toString().toUpperCase();
}
}
SSLClientUtil
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
//用于进行Https请求的HttpClient
public class SSLClientUtil extends DefaultHttpClient{
public SSLClientUtil() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
业务代码
FaceNucleusController
import com.szzz.authentication.service.AutChannelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import result.CommonResult;
@RestController
@Slf4j
@RequestMapping(value = "/faceNucleus")
@Api(tags = {"人脸核身"}, value = "人脸核身")
public class FaceNucleusController {
@Autowired
private AutChannelService autChannelService;
@ApiOperation(value = "获取AccessToken", httpMethod = "GET", notes = "获取AccessToken")
@GetMapping(value = "/getAccessToken")
public CommonResult getAccessToken() {
return autChannelService.getAccessToken();
}
@ApiOperation(value = "获取SIGNTicket", httpMethod = "GET", notes = "获取SIGNTicket")
@GetMapping(value = "/getSIGNTicket")
public CommonResult getSIGNTicket() {
return autChannelService.getSIGNTicket();
}
@ApiOperation(value = "生成签名", httpMethod = "POST", notes = "生成签名")
@PostMapping(value = "/signature")
public CommonResult signature(@RequestParam String name, @RequestParam String idNo,@RequestParam String sourcePhotoStr,@RequestParam String sourcePhotoType) {
return autChannelService.signature(name, idNo,sourcePhotoStr,sourcePhotoType);
}
}
业务层
@Service
@Slf4j
public class AutChannelServiceImpl extends ServiceImpl<AutChannelMapper, RealAuthChannel> implements AutChannelService {
@Autowired
private AutChannelMapper autChannelMapper;
@Autowired
private AutChannelCacheService autChannelCacheService;
@Autowired
private HttpClient httpClient;
@Autowired
private HttpAPIService httpAPIService;
@Override
@Transactional(rollbackFor = Exception.class)
public void catAutChannel(String autChannelName) {
RealAuthChannel realAuthChannel = new RealAuthChannel();
realAuthChannel.setId(1);
realAuthChannel.setUpdateTime(new Date());
realAuthChannel.setAutChannel(autChannelName);
autChannelCacheService.setAutChannel(realAuthChannel);
autChannelMapper.updateById(realAuthChannel);
}
@SneakyThrows
@Override
public CommonResult getAccessToken() {
HttpGet httpGet = new HttpGet(FaceConfig.Access_Token_URL + Cat.question
+ "app_id" + Cat.equ + FaceConfig.APP_ID + Cat.and
+ "secret" + Cat.equ + FaceConfig.Secret + Cat.and
+ "grant_type" + Cat.equ + FaceConfig.grant_type + Cat.and
+ "version" + Cat.equ + FaceConfig.version);
JSONObject resp;
try (CloseableHttpResponse response = (CloseableHttpResponse) this.httpClient.execute(httpGet)) {
String string = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
resp = JSON.parseObject(string);
}
return CommonResult.success(resp.get("access_token"));
}
@SneakyThrows
@Override
public CommonResult getSIGNTicket() {
HttpGet httpGet = new HttpGet(FaceConfig.SIGN_ticket_URL + Cat.question
+ "app_id" + Cat.equ + FaceConfig.APP_ID + Cat.and
+ "access_token" + Cat.equ + getAccessToken().getData() + Cat.and
+ "type" + Cat.equ + FaceConfig.type + Cat.and
+ "version" + Cat.equ + FaceConfig.version);
JSONObject resp;
try (CloseableHttpResponse response = (CloseableHttpResponse) this.httpClient.execute(httpGet)) {
String string = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
resp = JSON.parseObject(string);
}
return CommonResult.success(resp);
}
@SneakyThrows
@Override
public CommonResult signature(String name, String idNo,String sourcePhotoStr,String sourcePhotoType) {
CommonResult<JSONObject> commonResult = (CommonResult<JSONObject>) getSIGNTicket();
String value = commonResult.getData().getJSONArray("tickets").getJSONObject(0).getString("value");
String orderNo = "orderNo"+System.currentTimeMillis()+"";
String userId = Calendar.getInstance().getTimeInMillis()+"";
ArrayList<String> l = new ArrayList<String>();
l.add(FaceConfig.version);
l.add(idNo);
l.add(FaceConfig.APP_ID);
l.add(orderNo);
l.add(name);
l.add(userId);
//获取签名
System.err.println("第二部执行获取H5FaceID请求的"+"sha1加密工具参数"+l);
System.out.println();
String getqianming = QianMingUitls.getqianming(l, value);
System.out.println();
System.out.println("获取执行H5FaceID请求的"+"SingTicket "+value);
System.out.println();
System.out.println("获取执行H5FaceID请求的"+getqianming.length()+"位签名为"+getqianming);
JSONObject params = new JSONObject();
params.put("webankAppId", FaceConfig.APP_ID);
params.put("orderNo", orderNo);
params.put("name", name);
params.put("idNo", idNo);
params.put("userId", userId);
params.put("sourcePhotoStr", sourcePhotoStr);
params.put("sourcePhotoType", sourcePhotoType);
params.put("version", FaceConfig.version);
params.put("sign", getqianming);
HttpClientUtil httpClientUtil = new HttpClientUtil();
String xmlData = httpClientUtil.doPost(FaceConfig.signature_URL, params.toString(), "utf-8");
System.out.println("获取H5faceID请求返回值为 " + xmlData);
Map<String, Object> map = JsonUtil.fromJson(xmlData.toString(), Map.class);
Object object = map;
String json = JsonUtil.toJson(object);
Map fromJson = JsonUtil.fromJson(json, Map.class);
return CommonResult.success(fromJson);
}
}
postman调试接口
请求成功!!!!