对接百度API的银行卡四要素校验

发布时间:2024年01月17日

正文

因为百度提供的API文档比较难懂,搞了一天从才弄好, 所以记录一下正确的demo。要使用百度API,要先开通服务获取到 appkey和secretKey

代码

@PostMapping("/validate-bank-auth")
	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "校验银行卡四要素", notes = "校验银行卡四要素")
	public R validateBankAuth(String mobile,String name,String idCardNo,String bankCardNo) {
		BankCardAuthModel bankCardModel = baiduAiTemplate.validateBankAuth( mobile, name, idCardNo, bankCardNo);
		log.info("validateBankAuth==={}", JsonUtil.toJson(bankCardModel));
		return R.data(bankCardModel);
	}
@SneakyThrows
	public BankCardAuthModel validateBankAuth(String mobile,String name,String idNum,String cardNo) {
		BankCardAuthModel bankCardAuthModel = new BankCardAuthModel();
		String result = "";
		try {
			result = bankAuth( mobile, name, idNum, cardNo);
			com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);

			String code = jsonObject.getString("code");
			bankCardAuthModel.setCode(code);
			com.alibaba.fastjson.JSONObject data = jsonObject.getJSONObject("data");
			if(ObjectUtil.isNotEmpty(data)){
				String message = data.getJSONObject("responseParams").getString("message");
				bankCardAuthModel.setMessage(message);
				if(!"01".equals(code)){
					throw new ServerException(message);
				}
			}
		} catch (Exception e) {
			log.error("获取身份证信息失败:" + result, e);
		}
		return bankCardAuthModel;
	}
private String bankAuth(String mobile,String name,String idNum,String cardNo) {
		String result = "";
		String localUrl = "http://ai-ccomm.baidu.com/pnvs/api/invoke/ydxsbankcardauth4";
		String secretKey = "替换成自己的secretKey ";
		String appKey = "替换成自己的appKey";

		// appKey
		Long timestamp = System.currentTimeMillis() / 1000;
		Map<String, Object> paramMap = new HashMap<>(4);

		paramMap.put("mobile", mobile);
		paramMap.put("name", name);
		paramMap.put("idNum", idNum);
		paramMap.put("cardNo", cardNo);

		String json = JsonUtil.toJson(paramMap);

		String parameters = "{\"parameters\":" + json + "}";

		String encrypt = AesEncryptUtil.encrypt(json, secretKey);

		StringBuilder assemble = AssembleUtil.assembleParameters(new HashMap<>(10));

		assemble.append("cardNo=").append(cardNo)
			.append("&idNum=").append(idNum)
			.append("&mobile=").append(mobile)
			.append("&name=").append(name)
			.append("&").append(timestamp)
			.append("&").append(secretKey);
		String signature = MD5Util.md5Encode(assemble.toString());


		Map<String, String> header = new HashMap(3);
		header.put("appkey", appKey);
		header.put("timestamp", timestamp + "");
		header.put("signature", signature);
		result = OkHttpUtil.postJson(localUrl, header, parameters);
		System.out.println(result);
		return result;
	}

工具类和model

@Data
public class BankCardAuthModel {

	/**
	 * 01
	 */
	private String code;
	/**
	 * 896487b984e14a9382b384a5d37f7fa5
	 */
	private String id;
	/**
	 * 业务成功
	 */
	private String statusType;
	/**
	 * 验证成功,一致
	 */
	private String message;

}
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AesEncryptUtil {

	public static String encrypt(String content, String encryptKey) {
		String key = encryptKey;
		if (encryptKey.length() > 64) {
			key = encryptKey.substring(0, 32);
		}
		try {
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
			byte[] b = cipher.doFinal(content.getBytes("utf-8"));
			return Base64.encodeBase64String(b);
		} catch (Exception e) {
//			log.info("AesEncryptUtil encrypt catch e: {}", e);
			e.printStackTrace();
			return null;
		}

	}

}
import java.util.Comparator;
import java.util.Map;

/**
 * 银行卡四要素详版接口 : assemble方法
 */
public class AssembleUtil {

	public static <T> StringBuilder assembleParameters(Map<String, T> paramMap) {
		StringBuilder result = new StringBuilder();
		if (paramMap == null || paramMap.isEmpty()) {
			return result;
		}

		paramMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).forEach(entry ->
			result.append(entry.getKey()).append("=").append(entry.getValue()).append("&"));
		return result;
	}

}

import org.apache.commons.lang3.StringUtils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

	public static String md5Encode(String plainText) {
		byte[] secretBytes;
		try {
			secretBytes = MessageDigest.getInstance("md5").digest(plainText
				.getBytes());
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("无此md5算法");
		}
		String md5code = (new BigInteger(1, secretBytes)).toString(16);
		return StringUtils.leftPad(md5code, 32, "0");
	}

}

pom

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>

吐槽

百度的这个文档,一言难尽啊

文章来源:https://blog.csdn.net/weixin_39388918/article/details/135642115
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。