1. Business background
I have recently come into contact with some e-commerce businesses and found that when dealing with e-commerce business interfaces, such as Taobao and payment interfaces, both the interface parties need to sign the interface data in order to ensure that the data parameters have not been tampered with during the transmission process, and then verify the interface parameters on the interface server side to ensure that the two signatures are the same. After the verification is passed, the business logic processing is carried out. Let’s mainly introduce the processing ideas here. As for the signature algorithm, I won’t introduce it too much, there are a lot of them on the Internet.
2. Processing ideas
The two parties agreed that the parameters are arranged in a specific order, such as in the order of the first letter, such as url: http://xxx/xxx.do?a=wersd&b=sd2354&c=4&signature=XXXXXXXXXXXXXXXX(signature is the incoming signature). After you get the incoming parameter, add the parameter string a=wersd&b=sd2354&c=4 according to the signature rules you agreed on, and use md5 to sign it once, and then compare it with the signature value of the incoming parameter to confirm whether the caller is legal. This is the idea of interface signature verification.
3. Example exercises
After communication between the interface, the following consensus was reached on the interface:
1. Notes mainly refer to the interface's protocol, incoming parameter type, signature algorithm, file format, etc.
2. The following is a real case of an e-commerce business interface. The two parties have agreed on the interface URL, business parameters, fixed parameters, signatures and return data formats.
When calling an interface, the code of the interface caller is as follows (for reference only): package com.pcmall;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.ArrayList;import java.util.Collections;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.TreeMap;public class APITest { static String TEST_URL = "Pending"; static String TEST_KEY = "Pending"; static String TEST_SEC = "Pending"; public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException { String result = getResult(TEST_URL, getReqParam()); System.out.print(result); } private static String getReqParam() throws UnsupportedEncodingException, NoSuchAlgorithmException { TreeMap<String, String> req = new TreeMap<String, String>(); req.put("a", TEST_KEY); req.put("f", "json"); req.put("l", "zh_CN"); req.put("m", "zhongan.repair.query"); req.put("v", "1.0"); req.put("i", "" + System.currentTimeMillis() / 1000); req.put("params", "{/"assignNo/":/"TEST018/"}"); req.put("s", sign(req, null, TEST_SEC)); StringBuilder param = new StringBuilder(); for (Iterator<Map.Entry<String, String>> it = req.entrySet().iterator(); it.hasNext();) { Map.Entry<String, String> e = it.next(); param.append("&").append(e.getKey()).append("=").append(URLEncoder.encode(e.getValue(), "UTF-8")); } return param.toString().substring(1); } private static String sign(Map<String, String> paramValues, List<String> ignoreParamNames, String secret) throws NoSuchAlgorithmException, UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); List<String> paramNames = new ArrayList<String>(paramValues.size()); paramNames.addAll(paramValues.keySet()); if (ignoreParamNames != null && ignoreParamNames.size() > 0) { for (String ignoreParamName : ignoreParamNames) { paramNames.remove(ignoreParamName); } } Collections.sort(paramNames); sb.append(secret); for (String paramName : paramName) { sb.append(paramName).append(paramValues.get(paramName)); } sb.append(secret); MessageDigest md = MessageDigest.getInstance("SHA-1"); return byte2hex(md.digest(sb.toString().getBytes("UTF-8"))); } private static String byte2hex(byte[] bytes) { StringBuilder sign = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() == 1) { sign.append("0"); } sign.append(hex.toUpperCase()); } return sign.toString(); } private static String getResult(String urlStr, String content) { URL url = null; HttpURLConnection connection = null; try { url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.setUseCaches(false); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(content.getBytes("UTF-8")); out.flush(); out.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); return buffer.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } } The server-side code is as follows (for reference only):
@RequestMapping("/repairTakeOrder")@ResponseBodypublic ResponseVO repairTakeOrder(@RequestBody String jsonStr) {logger.info("repairTakeOrder parameter: " + jsonStr);ResponseVO responseVO = null;try {RepairOrder repairOrder = JackJsonUtil.toBean(jsonStr,RepairOrder.class);TreeMap<String, String> paramsMap = new TreeMap<String, String>();paramsMap.put("gsxx01", repairOrder.getGsxx01());paramsMap.put("orderType", repairOrder.getOrderType().toString());paramsMap.put("serviceNo", repairOrder.getServiceNo());paramsMap.put("vipCard", repairOrder.getVipCard());paramsMap.put("customerName", repairOrder.getCustomerName());paramsMap.put("customerPhone", repairOrder.getCustomerPhone());paramsMap.put("customerTel", repairOrder.getCustomerTel());paramsMap.put("province", repairOrder.getProvince());paramsMap.put("city", repairOrder.getCity());paramsMap.put("county", repairOrder.getCounty());paramsMap.put("address", repairOrder.getAddress());paramsMap.put("salerCode", repairOrder.getSalerCode());paramsMap.put("salerName", repairOrder.getSalerName());paramsMap.put("storeCode", repairOrder.getStoreCode());paramsMap.put("storeName", repairOrder.getStoreName());paramsMap.put("site", repairOrder.getSite());paramsMap.put("siteDesp", repairOrder.getSiteDesp());paramsMap.put("engineerCode", repairOrder.getEngineerCode());paramsMap.put("engineerName", repairOrder.getEngineerName());if (repairOrder.getServiceDate() != null) {paramsMap.put("serviceDate",DateUtils.formatDate(repairOrder.getServiceDate()));}if (repairOrder.getSalePrice() != null) {paramsMap.put("salePrice", repairOrder.getSalePrice().toString());}paramsMap.put("profitCenter", repairOrder.getProfitCenter());paramsMap.put("costCenter", repairOrder.getCostCenter());paramsMap.put("gsxx02", repairOrder.getGsxx02());paramsMap.put("returnReason", repairOrder.getReturnReason());if (repairOrder.getOriOrder() != null) {paramsMap.put("oriOrder", repairOrder.getOriOrder().toString());}if (repairOrder.getOriServiceNo() != null) {paramsMap.put("oriServiceNo", repairOrder.getOriServiceNo());}//Split signature original string (a=1&b=2)String paramSrc = RequestUtils.getParamSrc(paramsMap);logger.info("SignOrder:" + paramSrc);//Check the signature verification operation if (SignUtils.verifymd5(paramSrc, repairOrder.getSign())) {//Processing business logic responseVO=erpServiceImpl.repairTakeOrder(repairOrder);} else {responseVO = new ResponseVO();responseVO.setSuccess(false);responseVO.setErrorMsg("Login verification failed");}} catch (Exception e) {logger.error("", e);responseVO = new ResponseVO();responseVO.setSuccess(false);responseVO.setErrorMsg(StringUtils.isNotBlank(e.getMessage()) ? e.getMessage() : "Background Exception");}return responseVO;}The above article on the Java Http interface plus and verification operation is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.