腾讯云--人脸核身项目实战

腾讯云接口文档:

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调试接口
在这里插入图片描述
请求成功!!!!
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
## 使用前准备​ 1. 前往注册: [腾讯云账号注册](https://cloud.tencent.com/register) (详细指引见 [注册腾讯云](https://cloud.tencent.com/document/product/378/9603)) 2. 取得存储桶名称 **BucketName**: 请前往 [创建存储桶](https://cloud.tencent.com/document/product/460/10637) 3. 取得 **APPID**、**SecretId**、**SecretKey**:请前往 [云API密钥](https://console.cloud.tencent.com/cam/capi) ,点击“新建密钥” ## 快速体验 1. 修改文件 src/main/java/com/qcloud/image/demo/Demo.java 的 main() 方法,填入上述申请到的 **APPID**、**SecretId**、**SecretKey**、**BucketName** 2. 导入到 IDE:工程用 Maven 构建,以 Intellij IDEA 为例,导入方式为:Import Project -> 选择工程目录 -> Import project from external model -> Maven 3. 运行:Demo.java 右键,Run Demo.main() ## 使用简介 ### 初始化 ```java ImageClient imageClient = new ImageClient(APPID, SecretId, SecretKey); ``` ### 设置代理 根据实际网络环境,可能要设置代理,例如: ```java Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("127.0.0.1", 8080)); imageClient.setProxy(proxy); ``` ### 使用 SDK 提供功能如下: **图像识别**:鉴黄,标签 **文字识别(OCR)**:身份证,名片,通用,驾驶证行驶证,营业执照,银行卡,车牌号 **人脸识别**:人脸检测,五官定位,个体信息管理,人脸验证,人脸对比及人脸检索 **人脸核身**:照片核身(通过照片和身份证信息),获取唇语验证码(用于活体核身),活体核身(通过视频和照片),活体核身(通过视频和身份证信息) ```java // 调用车牌识别API示例 String imageUrl = "http://youtu.qq.com/app/img/experience/char_general/icon_ocr_license_3.jpg"; String result = imageClient.ocrPlate(new OcrPlateRequest("bucketName", imageUrl)); System.out.println(result); ``` 更多例子详情可参见 [Demo.java](https://github.com/tencentyun/image-java-sdk-v2.0/blob/master/src/main/java/com/qcloud/image/demo/Demo.java) 的代码。 ## 集成到你的项目中 ### 获得 SDK jar 文件 1. 直接使用 release/*-with-dependencies.jar 2. 自行编译:在工程根目录下执行命令 `mvn assembly:assembly`,编译结果见 target/*-with-dependencies.jar ### 导入 jar 文件 根据项目具体情况导入 *-with-dependencies.jar

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值