对接百度api之银行卡识别

对接百度api之银行卡识别

    • 1. 成为开发者
    • 2. 创建应用
    • 3. 获取密钥
    • 4. 配置图像识别sdk
    • 5. 调用银行卡识别接口

详情步骤参考链接

1. 成为开发者

三步完成账号的基本注册与认证:

STEP1:点击百度AI开放平台导航右侧的控制台,选择需要使用的AI服务项。若为未登录状态,将跳转至登录界面,请您使用百度账号登录。如还未持有百度账户,可以点击此处注册百度账户。
STEP2:首次使用,登录后将会进入开发者认证页面,请填写相关信息完成开发者认证。注:(如您之前已经是百度云用户或百度开发者中心用户,此步可略过。)
STEP3:进入具体AI服务项的控制面板(如文字识别、人脸识别),进行相关业务操作。

2. 创建应用

账号登录成功,您需要创建应用才可正式调用AI能力。应用是您调用API服务的基本操作单元,您可以基于应用创建成功后获取的API Key及Secret Key,进行接口调用操作,及相关配置。

3. 获取密钥

在您创建完毕应用后,平台将会分配给您此应用的相关凭证,主要为AppID、API Key、Secret Key。以上三个信息是您应用实际开发的主要凭证,每个应用之间各不相同,请您妥善保管。下图为示例内容:
对接百度api之银行卡识别_第1张图片

4. 配置图像识别sdk

对接百度api之银行卡识别_第2张图片

下载的连接

5. 调用银行卡识别接口

返回的结果类:

package com.baidu.model;
 
import java.io.Serializable;

import com.smartpay.actlist.model.BaseResult;

public class BaiduBankCardRes extends BaseResult implements Serializable{
	private static final long serialVersionUID = -7603769448608885895L;

	private String log_id;
	private BankCardRes result;
	private String error_code;
	private String error_msg;
	
	public String getError_code() {
		return error_code;
	}

	public void setError_code(String error_code) {
		this.error_code = error_code;
	}

	public String getError_msg() {
		return error_msg;
	}

	public void setError_msg(String error_msg) {
		this.error_msg = error_msg;
	}

	public BaiduBankCardRes() {
		super();
	}

	public BaiduBankCardRes(String resCode, String resMsg) {
		super(resCode, resMsg);
	}

	public String getLog_id() {
		return log_id;
	}

	public void setLog_id(String log_id) {
		this.log_id = log_id;
	}

	public BankCardRes getResult() {
		return result;
	}

	public void setResult(BankCardRes result) {
		this.result = result;
	}
	
	
}


package com.baidu.model;

import java.io.Serializable;

public class BankCardRes implements Serializable {

	private static final long serialVersionUID = -5831232998485197967L;
	
	private String bank_card_number;
	private String valid_date;
	private String bank_name;
	private int bank_card_type;
	
	public String getBank_card_number() {
		return bank_card_number;
	}
	public void setBank_card_number(String bank_card_number) {
		this.bank_card_number = bank_card_number;
	}
	public String getValid_date() {
		return valid_date;
	}
	public void setValid_date(String valid_date) {
		this.valid_date = valid_date;
	}
	public String getBank_name() {
		return bank_name;
	}
	public void setBank_name(String bank_name) {
		this.bank_name = bank_name;
	}
	public int getBank_card_type() {
		return bank_card_type;
	}
	public void setBank_card_type(int bank_card_type) {
		this.bank_card_type = bank_card_type;
	}

}

Access Token获取
温馨提示:Access Token的有效期为30天(以秒为单位)

package com.baidu.ai.aip.auth;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 获取token类
 */
public class AuthService {

    /**
     * 获取权限token
     * @return 返回示例:
     * {
     * "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
     * "expires_in": 2592000
     * }
     */
    public static String getAuth() {
        // 官网获取的 API Key 更新为你注册的
        String clientId = "百度云应用的AK";
        // 官网获取的 Secret Key 更新为你注册的
        String clientSecret = "百度云应用的SK";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期,需要自行管理,当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例:
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getString("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败!");
            e.printStackTrace(System.err);
        }
        return null;
    }

}

/*
 * Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
 */
package com.baidu.ai.aip.ocr;

import com.baidu.ai.aip.utils.Base64Util;
import com.baidu.ai.aip.utils.FileUtil;
import com.baidu.ai.aip.utils.HttpUtil;

import java.net.URLEncoder;

/**
 * 银行卡识别
 */
public class Bankcard {

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static void main(String[] args) {
        // 银行卡识别url
        String bankcardIdentificate = "https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard";
        // 本地图片路径
        String filePath = "#####本地文件路径#####";
        try {
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String params = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(imgStr, "UTF-8");
            /**
             * 线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
             * 这里放入redis
             */
          //  String accessToken = "#####调用鉴权接口获取的token#####";
           String access_token = redisTemplate.opsForValue().get("BAIDU_ACCESS_TOKEN");
    		log.info("redis_baidu_access_token=="+ access_token);
    		if(ValidateUtil.isBlank(access_token)){
    			try {
    				access_token = AuthService.getAuth();
    			} catch (Exception e) {
    				log.info("baidu_access_token获取异常");
    				e.printStackTrace();
    				return new BaiduBankCardRes("9999","baidu_access_token获取异常!");
    			}
    			log.info("baidu_access_token=="+ access_token);
    			if(ValidateUtil.isBlank(access_token)){
    				return new BaiduBankCardRes("9999","baidu_access_token获取失败!");
    			}else{
    				redisTemplate.opsForValue().set("BAIDU_ACCESS_TOKEN", access_token,30,TimeUnit.DAYS);
    			}
    		}
            String result = HttpUtil.post(bankcardIdentificate, access_token , params);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Controller 方法

	@RequestMapping("/getBankCardRes")
	@ResponseBody
	public  BaiduBankCardRes getBankCardRes(String imgStr){
        try {
            String params = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(imgStr, "UTF-8");
            /**
             * 线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
             */
        	String access_token = redisTemplate.opsForValue().get("BAIDU_ACCESS_TOKEN");
    		log.info("redis_baidu_access_token=="+ access_token);
    		if(ValidateUtil.isBlank(access_token)){
    			try {
    				access_token = AuthService.getAuth();
    			} catch (Exception e) {
    				log.info("baidu_access_token获取异常");
    				e.printStackTrace();
    				return new BaiduBankCardRes("9999","baidu_access_token获取异常!");
    			}
    			log.info("baidu_access_token=="+ access_token);
    			if(ValidateUtil.isBlank(access_token)){
    				return new BaiduBankCardRes("9999","baidu_access_token获取失败!");
    			}else{
    				redisTemplate.opsForValue().set("BAIDU_ACCESS_TOKEN", access_token,30,TimeUnit.DAYS);
    			}
    		}
            String result = HttpUtil.post(ConfigConst.BAI_DU__BANK_CARD_IDENTIFICATE_URL, access_token, params);
            log.info("result=="+result);
            if(ValidateUtil.isBlank(result)){
            	return new BaiduBankCardRes("9999","银行卡识别失败!");
            }
            
			BaiduBankCardRes baiduBankCardRes = new Gson().fromJson(result, BaiduBankCardRes.class);
			
			log.info("baiduBankCardRes=="+ new Gson().toJson(baiduBankCardRes) );
		
			if(!ValidateUtil.isBlank(baiduBankCardRes.getError_code())){
				baiduBankCardRes.setResCode(baiduBankCardRes.getError_code());
				baiduBankCardRes.setResMsg(baiduBankCardRes.getError_msg());
	            return baiduBankCardRes;
			}
			baiduBankCardRes.setResCode("0000");
            return baiduBankCardRes;
			
        } catch (Exception e) {
        	  log.info("异常");
            e.printStackTrace();
        }
		return new BaiduBankCardRes("9999","银行卡识别失败!");
		
	}

返回的结果实例

{"log_id": 6666890388889816218, "result": {"bank_card_number": "6225 7688 8888 8888", "valid_date": "07/21", "bank_card_type": 2, "bank_name": "招商银行"}}

你可能感兴趣的:(java基础)