根据银行卡号查银行信息
微信官方接口文档:根据卡号查银行信息
access_token获取方式:微信官方接口文档
实体类
需要引入lombok依赖
否则手写getter ,setter 方法
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class BankInfoResVo {
private String bank_code;
private Long bank_id;
private String bank_name;
private Boolean need_branch;
private String account_bank;
}
@Getter
@Setter
@NoArgsConstructor
public class BankResVo {
private List<BankInfoResVo> data;
private Integer totalCount;
private Integer errcode;
private String errmsg;
}
接口实现
传入小程序全局唯一后台接口调用凭据access_token、银行卡号carNo
将微信接口返回的结果转换成实体类返回到前端
/**
* 获取银行信息
* @param accessToken 小程序全局唯一后台接口调用凭据
* @param cardNo 银行卡号
* @return
*/
public BankResVo bankInfoRequest(String accessToken, String cardNo) {
BankResVo bankResVo = new BankResVo();
// 构造请求URL
String requestUrl = "https://api.weixin.qq.com/shop/funds/getbankbynum?access_token=" + accessToken;
JSONObject jsonParams = new JSONObject();
jsonParams.put("account_number", cardNo);
// 创建 CloseableHttpClient 实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 POST 请求
HttpPost post = new HttpPost(requestUrl);
try {
// 设置请求头
post.setHeader("Content-Type", "application/json");
// 设置请求体
StringEntity entity = new StringEntity(jsonParams.toString(), ContentType.APPLICATION_JSON);
post.setEntity(entity);
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// 解析响应
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity);
//log.info("success,return body = " + responseString );
// 解析 JSON 响应
JSONObject jsonResponse = new JSONObject(responseString);
JSONArray data = jsonResponse.getJSONArray("data");
// 将 JSON 数组转换为实体类列表
ObjectMapper mapper = new ObjectMapper();
List<BankInfoResVo> bankInfoList = mapper.readValue(data.toString(), new TypeReference<List<BankInfoResVo>>() {});
bankResVo.setData(bankInfoList);
bankResVo.setTotalCount(jsonResponse.getInt("total_count"));
bankResVo.setErrcode(jsonResponse.getInt("errcode"));
bankResVo.setErrmsg(jsonResponse.getString("errmsg"));
} else {
throw new IOException("request failed");
}
} catch (IOException e) {
e.printStackTrace();
}
return bankResVo;
}