支付宝接口解析

 

首先是AlipayCore.java这个类,该类是请求、通知返回两个文件所调用的公用函数核心处理文件,不需要修改。方法主要是对签名和请求参数进行拼接:

  1. /**  
  2.      * 生成签名结果  
  3.      * @param sArray 要签名的数组  
  4.      * @return 签名结果字符串  
  5.      */  
  6.     public static String buildMysign(Map<String, String> sArray) {  
  7.         String prestr = createLinkString(sArray); //把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串  
  8.         prestrprestr = prestr + AlipayConfig.key; //把拼接后的字符串再与安全校验码直接连接起来  
  9.         String mysign = AlipayMd5Encrypt.md5(prestr);  
  10.         return mysign;  
  11.     }  
  12.   
  13.     /**   
  14.      * 除去数组中的空值和签名参数  
  15.      * @param sArray 签名参数组  
  16.      * @return 去掉空值与签名参数后的新签名参数组  
  17.      */  
  18.     public static Map<String, String> paraFilter(Map<String, String> sArray) {  
  19.   
  20.         Map<String, String> result = new HashMap<String, String>();  
  21.   
  22.         if (sArray == null || sArray.size() <= 0) {  
  23.             return result;  
  24.         }  
  25.   
  26.         for (String key : sArray.keySet()) {  
  27.             String value = sArray.get(key);  
  28.             if (value == null || value.equals("") || key.equalsIgnoreCase("sign")  
  29.                 || key.equalsIgnoreCase("sign_type")) {  
  30.                 continue;  
  31.             }  
  32.             result.put(key, value);  
  33.         }  
  34.   
  35.         return result;  
  36.     }  
  37.   
  38.     /**   
  39.      * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串  
  40.      * @param params 需要排序并参与字符拼接的参数组  
  41.      * @return 拼接后字符串  
  42.      */  
  43.     public static String createLinkString(Map<String, String> params) {  
  44.   
  45.         List<String> keys = new ArrayList<String>(params.keySet());  
  46.         Collections.sort(keys);  
  47.   
  48.         String prestr = "";  
  49.   
  50.         for (int i = 0; i < keys.size(); i++) {  
  51.             String key = keys.get(i);  
  52.             String value = params.get(key);  
  53.   
  54.             if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符  
  55.                 prestrprestr = prestr + key + "=" + value;  
  56.             } else {  
  57.                 prestrprestr = prestr + key + "=" + value + "&";  
  58.             }  
  59.         }  
  60.   
  61.         return prestr;  
  62.     }  
AlipayConfig.java这个类是一个基础配置类,主要用来设置账户有关信息和返回路径:
  1. //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  
  2.     // 合作身份者ID,以2088开头由16位纯数字组成的字符串  
  3.     public static String partner = "";  
  4.       
  5.     // 交易安全检验码,由数字和字母组成的32位字符串  
  6.     public static String key = "";  
  7.       
  8.     // 当前页面跳转后的页面 要用 http://格式的完整路径,不允许加?id=123这类自定义参数  
  9.     // 域名不能写成http://localhost/alipay.auth.authorize_jsp_utf8/return_url.jsp ,否则会导致return_url执行无效  
  10.     public static String return_url = "http://127.0.0.1:8080/alipay.auth.authorize_jsp_utf8/return_url.jsp";  
  11.   
  12.     //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  
  13.       
  14.   
  15.     // 调试用,创建TXT日志路径  
  16.     public static String log_path = "D:\\alipay_log_" + System.currentTimeMillis()+".txt";  
  17.   
  18.     // 字符编码格式 目前支持 gbk 或 utf-8  
  19.     public static String input_charset = "UTF-8";  
  20.       
  21.     // 签名方式 不需修改  
  22.     public static String sign_type = "MD5";  
  23.       
  24.     //访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http  
  25.     public static String transport = "http";  
AlipayMd5Encrypt.java这个类是对签名进行加密的工具类,不需要修改即可用:
  1. /**  
  2.      * 对字符串进行MD5签名  
  3.      *   
  4.      * @param text  
  5.      *            明文  
  6.      *   
  7.      * @return 密文  
  8.      */  
  9.     public static String md5(String text) {  
  10.   
  11.         return DigestUtils.md5Hex(getContentBytes(text, AlipayConfig.input_charset));  
  12.   
  13.     }  
  14.   
  15.     /**  
  16.      * @param content  
  17.      * @param charset  
  18.      * @return  
  19.      * @throws SignatureException  
  20.      * @throws UnsupportedEncodingException   
  21.      */  
  22.     private static byte[] getContentBytes(String content, String charset) {  
  23.         if (charset == null || "".equals(charset)) {  
  24.             return content.getBytes();  
  25.         }  
  26.   
  27.         try {  
  28.             return content.getBytes(charset);  
  29.         } catch (UnsupportedEncodingException e) {  
  30.             throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);  
  31.         }  
  32.     }  
接下来是AlipayNotify.java这个类,这个类主要是处理支付宝各接口通知返回:
  1. /**  
  2.      * HTTPS形式消息验证地址  
  3.      */  
  4.     private static final String HTTPS_VERIFY_URL = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify&";  
  5.   
  6.     /**  
  7.      * HTTP形式消息验证地址  
  8.      */  
  9.     private static final String HTTP_VERIFY_URL  = "http://notify.alipay.com/trade/notify_query.do?";  
  10.   
  11.     /**  
  12.      * 验证消息是否是支付宝发出的合法消息  
  13.      * @param params 通知返回来的参数数组  
  14.      * @return 验证结果  
  15.      */  
  16.     public static boolean verify(Map<String, String> params) {  
  17.         String mysign = getMysign(params);  
  18.         String responseTxt = "true";  
  19.         if(params.get("notify_id") != null) {responseTxt = verifyResponse(params.get("notify_id"));}  
  20.         String sign = "";  
  21.         if(params.get("sign") != null) {sign = params.get("sign");}  
  22.   
  23.         //写日志记录(若要调试,请取消下面两行注释)  
  24.         //String sWord = "responseTxt=" + responseTxt + "\n notify_url_log:sign=" + sign + "&mysign="  
  25.         //              + mysign + "\n notify回来的参数:" + AlipayCore.createLinkString(params);  
  26.         //AlipayCore.logResult(sWord);  
  27.   
  28.   
  29.         //验证  
  30.         //responsetTxt的结果不是true,与服务器设置问题、合作身份者ID、notify_id一分钟失效有关  
  31.         //mysign与sign不等,与安全校验码、请求时的参数格式(如:带自定义参数等)、编码格式有关  
  32.         if (mysign.equals(sign) && responseTxt.equals("true")) {  
  33.             return true;  
  34.         } else {  
  35.             return false;  
  36.         }  
  37.     }  
  38.   
  39.     /**  
  40.      * 根据反馈回来的信息,生成签名结果  
  41.      * @param Params 通知返回来的参数数组  
  42.      * @return 生成的签名结果  
  43.      */  
  44.     private static String getMysign(Map<String, String> Params) {  
  45.         Map<String, String> sParaNew = AlipayCore.paraFilter(Params);//过滤空值、sign与sign_type参数  
  46.         String mysign = AlipayCore.buildMysign(sParaNew);//获得签名结果  
  47.         return mysign;  
  48.     }  
  49.   
  50.     /**  
  51.     * 获取远程服务器ATN结果,验证返回URL  
  52.     * @param notify_id 通知校验ID  
  53.     * @return 服务器ATN结果  
  54.     * 验证结果集:  
  55.     * invalid命令参数不对 出现这个错误,请检测返回处理中partner和key是否为空   
  56.     * true 返回正确信息  
  57.     * false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟  
  58.     */  
  59.     private static String verifyResponse(String notify_id) {  
  60.         //获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求  
  61.         String transport = AlipayConfig.transport;  
  62.         String partner = AlipayConfig.partner;  
  63.         String veryfy_url = "";  
  64.         if (transport.equalsIgnoreCase("https")) {  
  65.             veryfy_url = HTTPS_VERIFY_URL;  
  66.         } else {  
  67.             veryfy_url = HTTP_VERIFY_URL;  
  68.         }  
  69.         veryfy_urlveryfy_url = veryfy_url + "partner=" + partner + "¬ify_id=" + notify_id;  
  70.   
  71.         return checkUrl(veryfy_url);  
  72.     }  
  73.   
  74.     /**  
  75.     * 获取远程服务器ATN结果  
  76.     * @param urlvalue 指定URL路径地址  
  77.     * @return 服务器ATN结果  
  78.     * 验证结果集:  
  79.     * invalid命令参数不对 出现这个错误,请检测返回处理中partner和key是否为空   
  80.     * true 返回正确信息  
  81.     * false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟  
  82.     */  
  83.     private static String checkUrl(String urlvalue) {  
  84.         String inputLine = "";  
  85.   
  86.         try {  
  87.             URL url = new URL(urlvalue);  
  88.             HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();  
  89.             BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection  
  90.                 .getInputStream()));  
  91.             ininputLine = in.readLine().toString();  
  92.         } catch (Exception e) {  
  93.             e.printStackTrace();  
  94.             inputLine = "";  
  95.         }  
  96.   
  97.         return inputLine;  
  98.     }  
下面我们就需要进行alipay的访问请求了,在请求过程中我们要有请求参数数组,提交的表单,有了这些条件之后我们就可以进行模拟HTTP请求获得返回的数据了。生成请求参数数组的代码如下:
  1. /**  
  2.      * 生成要请求给支付宝的参数数组  
  3.      * @param sParaTemp 请求前的参数数组  
  4.      * @return 要请求的参数数组  
  5.      */  
  6.     private static Map<String, String> buildRequestPara(Map<String, String> sParaTemp) {  
  7.         //除去数组中的空值和签名参数  
  8.         Map<String, String> sPara = AlipayCore.paraFilter(sParaTemp);  
  9.         //生成签名结果  
  10.         String mysign = AlipayCore.buildMysign(sPara);  
  11.   
  12.         //签名结果与签名方式加入请求提交参数组中  
  13.         sPara.put("sign", mysign);  
  14.         sPara.put("sign_type", AlipayConfig.sign_type);  
  15.   
  16.         return sPara;  
  17.     }  
构造提交表单代码:
  1. /**  
  2.      * 构造提交表单HTML数据  
  3.      * @param sParaTemp 请求参数数组  
  4.      * @param gateway 网关地址  
  5.      * @param strMethod 提交方式。两个值可选:post、get  
  6.      * @param strButtonName 确认按钮显示文字  
  7.      * @return 提交表单HTML文本  
  8.      */  
  9.     public static String buildForm(Map<String, String> sParaTemp, String gateway, String strMethod,  
  10.                                    String strButtonName) {  
  11.         //待请求参数数组  
  12.         Map<String, String> sPara = buildRequestPara(sParaTemp);  
  13.         List<String> keys = new ArrayList<String>(sPara.keySet());  
  14.   
  15.         StringBuffer sbHtml = new StringBuffer();  
  16.   
  17.         sbHtml.append("<form id=\"alipaysubmit\" name=\"alipaysubmit\" action=\"" + gateway  
  18.                       + "_input_charset=" + AlipayConfig.input_charset + "\" method=\"" + strMethod  
  19.                       + "\">");  
  20.   
  21.         for (int i = 0; i < keys.size(); i++) {  
  22.             String name = (String) keys.get(i);  
  23.             String value = (String) sPara.get(name);  
  24.   
  25.             sbHtml.append("<input type=\"hidden\" name=\"" + name + "\" value=\"" + value + "\"/>");  
  26.         }  
  27.   
  28.         //submit按钮控件请不要含有name属性  
  29.         sbHtml.append("<input type=\"submit\" value=\"" + strButtonName + "\" style=\"display:none;\"></form>");  
  30.         sbHtml.append("<script>document.forms['alipaysubmit'].submit();</script>");  
  31.   
  32.         return sbHtml.toString();  
  33.     }  
构造模拟远程HTTP的POST请求,获取支付宝的返回XML处理结果:
  1. public static String sendPostInfo(Map<String, String> sParaTemp, String gateway)  
  2.                                                                                     throws Exception {  
  3.         //待请求参数数组  
  4.         Map<String, String> sPara = buildRequestPara(sParaTemp);  
  5.   
  6.         HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();  
  7.   
  8.         HttpRequest request = new HttpRequest(HttpResultType.BYTES);  
  9.         //设置编码集  
  10.         request.setCharset(AlipayConfig.input_charset);  
  11.   
  12.         request.setParameters(generatNameValuePair(sPara));  
  13.         request.setUrl(gateway+"_input_charset="+AlipayConfig.input_charset);  
  14.   
  15.         HttpResponse response = httpProtocolHandler.execute(request);  
  16.         if (response == null) {  
  17.             return null;  
  18.         }  
  19.           
  20.         String strResult = response.getStringResult();  
  21.   
  22.         return strResult;  
  23.     }  
generatNameValuePair方法:
  1. /**  
  2.      * MAP类型数组转换成NameValuePair类型  
  3.      * @param properties  MAP类型数组  
  4.      * @return NameValuePair类型数组  
  5.      */  
  6.     private static NameValuePair[] generatNameValuePair(Map<String, String> properties) {  
  7.         NameValuePair[] nameValuePair = new NameValuePair[properties.size()];  
  8.         int i = 0;  
  9.         for (Map.Entry<String, String> entry : properties.entrySet()) {  
  10.             nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue());  
  11.         }  
  12.   
  13.         return nameValuePair;  
  14.     }  
接下来要看看HttpProtocolHandler.java这个类了,这个类是模拟HTTP请求的核心类,最主要的是execute这个执行http请求的方法:
  1. public HttpResponse execute(HttpRequest request) {  
  2.         HttpClient httpclient = new HttpClient(connectionManager);  
  3.   
  4.         // 设置连接超时  
  5.         int connectionTimeout = defaultConnectionTimeout;  
  6.         if (request.getConnectionTimeout() > 0) {  
  7.             connectionTimeout = request.getConnectionTimeout();  
  8.         }  
  9.         httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);  
  10.   
  11.         // 设置回应超时  
  12.         int soTimeout = defaultSoTimeout;  
  13.         if (request.getTimeout() > 0) {  
  14.             soTimeout = request.getTimeout();  
  15.         }  
  16.         httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);  
  17.   
  18.         // 设置等待ConnectionManager释放connection的时间  
  19.         httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);  
  20.   
  21.         String charset = request.getCharset();  
  22.         charsetcharset = charset == null ? DEFAULT_CHARSET : charset;  
  23.         HttpMethod method = null;  
  24.   
  25.         if (request.getMethod().equals(HttpRequest.METHOD_GET)) {  
  26.             method = new GetMethod(request.getUrl());  
  27.             method.getParams().setCredentialCharset(charset);  
  28.   
  29.             // parseNotifyConfig会保证使用GET方法时,request一定使用QueryString  
  30.             method.setQueryString(request.getQueryString());  
  31.         } else {  
  32.             method = new PostMethod(request.getUrl());  
  33.             ((PostMethod) method).addParameters(request.getParameters());  
  34.             method.addRequestHeader("Content-Type",  
  35.                 "application/x-www-form-urlencoded; text/html; charset=" + charset);  
  36.   
  37.         }  
  38.   
  39.         // 设置Http Header中的User-Agent属性  
  40.         method.addRequestHeader("User-Agent", "Mozilla/4.0");  
  41.         HttpResponse response = new HttpResponse();  
  42.   
  43.         try {  
  44.             httpclient.executeMethod(method);  
  45.             if (request.getResultType().equals(HttpResultType.STRING)) {  
  46.                 response.setStringResult(method.getResponseBodyAsString());  
  47.             } else if (request.getResultType().equals(HttpResultType.BYTES)) {  
  48.                 response.setByteResult(method.getResponseBody());  
  49.             }  
  50.             response.setResponseHeaders(method.getResponseHeaders());  
  51.         } catch (UnknownHostException ex) {  
  52.   
  53.             return null;  
  54.         } catch (IOException ex) {  
  55.   
  56.             return null;  
  57.         } catch (Exception ex) {  
  58.   
  59.             return null;  
  60.         } finally {  
  61.             method.releaseConnection();  
  62.         }  
  63.         return response;  
  64.     }  
当然我们需要在new HttpProtocolHandler这个类的时候创建一个线程安全的HTTP连接池,为什么要线程安全,下文会有提示。我们把这个步骤放到私有的构造方法当中:
  1. private HttpProtocolHandler() {  
  2.         connectionManager = new MultiThreadedHttpConnectionManager();  
  3.         connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);  
  4.         connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);  
  5.   
  6.         IdleConnectionTimeoutThread ict = new IdleConnectionTimeoutThread();  
  7.         ict.addConnectionManager(connectionManager);  
  8.         ict.setConnectionTimeout(defaultIdleConnTimeout);  
  9.   
  10.         ict.start();  
  11.     }  
然后使用如下方法来使其他类能使用getInstance()方法就获得HttpProtocolHandler这个类的实例对象,并且是线程安全的:
  1. private static HttpProtocolHandler httpProtocolHandler                 = new HttpProtocolHandler();  
  2.   
  3.     /**  
  4.      * 工厂方法  
  5.      *   
  6.      * @return  
  7.      */  
  8.     public static HttpProtocolHandler getInstance() {  
  9.         return httpProtocolHandler;  
  10.     }  
此类当中还有一些属性,用来设置http连接的超时时间,连接数等参数:
  1. private static String              DEFAULT_CHARSET                     = "GBK";  
  2.   
  3.     /** 连接超时时间,由bean factory设置,缺省为8秒钟 */  
  4.     private int                        defaultConnectionTimeout            = 8000;  
  5.   
  6.     /** 回应超时时间, 由bean factory设置,缺省为30秒钟 */  
  7.     private int                        defaultSoTimeout                    = 30000;  
  8.   
  9.     /** 闲置连接超时时间, 由bean factory设置,缺省为60秒钟 */  
  10.     private int                        defaultIdleConnTimeout              = 60000;  
  11.   
  12.     private int                        defaultMaxConnPerHost               = 30;  
  13.   
  14.     private int                        defaultMaxTotalConn                 = 80;  
  15.   
  16.     /** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用):1秒*/  
  17.     private static final long          defaultHttpConnectionManagerTimeout = 3 * 1000;  
  18.   
  19.     /**  
  20.      * HTTP连接管理器,该连接管理器必须是线程安全的.(如何设置线程安全上文已经写了)  
  21.      */  
  22.     private HttpConnectionManager      connectionManager;  
此类当中还有HttpClient和HttpResponse这两个类,这两个类主要是对HTTP请求的封装和返回http的相应消息。这两个类就不在这里讲了,就是两个pojo类,HttpClient里面封装了请求需要的属性比如字符集,请求method,超时时间等,HttpResponse里面是响应头和返回结构的封装。
最后一个是支付宝各接口构造类AlipayService.java,
  1. /**  
  2.      * 支付宝提供给商户的服务接入网关URL(新)  
  3.      */  
  4.     private static final String ALIPAY_GATEWAY_NEW = "https://mapi.alipay.com/gateway.do?";  
  5.   
  6.     /**  
  7.      * 构造快捷登录接口  
  8.      * @param sParaTemp 请求参数集合  
  9.      * @return 表单提交HTML信息  
  10.      */  
  11.     public static String alipay_auth_authorize(Map<String, String> sParaTemp) {  
  12.   
  13.         //增加基本配置  
  14.         sParaTemp.put("service", "alipay.auth.authorize");  
  15.         sParaTemp.put("target_service", "user.auth.quick.login");  
  16.         sParaTemp.put("partner", AlipayConfig.partner);  
  17.         sParaTemp.put("return_url", AlipayConfig.return_url);  
  18.         sParaTemp.put("_input_charset", AlipayConfig.input_charset);  
  19.   
  20.         String strButtonName = "确认";  
  21.   
  22.         return AlipaySubmit.buildForm(sParaTemp, ALIPAY_GATEWAY_NEW, "get", strButtonName);  
  23.     }  
  24.   
  25.     /**  
  26.      * 用于防钓鱼,调用接口query_timestamp来获取时间戳的处理函数  
  27.      * 注意:远程解析XML出错,与服务器是否支持SSL等配置有关  
  28.      * @return 时间戳字符串  
  29.      * @throws IOException  
  30.      * @throws DocumentException  
  31.      * @throws MalformedURLException  
  32.      */  
  33.     public static String query_timestamp() throws MalformedURLException,  
  34.                                                         DocumentException, IOException {  
  35.   
  36.         //构造访问query_timestamp接口的URL串  
  37.         String strUrl = ALIPAY_GATEWAY_NEW + "service=query_timestamp&partner=" + AlipayConfig.partner;  
  38.         StringBuffer result = new StringBuffer();  
  39.   
  40.         SAXReader reader = new SAXReader();  
  41.         Document doc = reader.read(new URL(strUrl).openStream());  
  42.   
  43.         List<Node> nodeList = doc.selectNodes("//alipay/*");  
  44.   
  45.         for (Node node : nodeList) {  
  46.             // 截取部分不需要解析的信息  
  47.             if (node.getName().equals("is_success") && node.getText().equals("T")) {  
  48.                 // 判断是否有成功标示  
  49.                 List<Node> nodeList1 = doc.selectNodes("//response/timestamp/*");  
  50.                 for (Node node1 : nodeList1) {  
  51.                     result.append(node1.getText());  
  52.                 }  
  53.             }  
  54.         }  
  55.   
  56.         return result.toString();  
  57.     }  
到这里支付宝的登录接口基本上已经结束了,讲的不是很详细,具体流程和代码在这里下载: http://download.csdn.net/detail/uohzoaix/4009777
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值