android 实现支付宝wap接口编程

2013-11-03  univasity   阅 1625  转 7
关于支付宝的一些信息可以直接访问支付宝网站。   
  
国内电子商务系统实现的基本流程如下:   

客户在系统内下订单 -> 系统根据订单生成支付宝接口url -> 客户通过url使用支付宝(网上银行)付款 -> 支付宝将客户的付款完成信息发送给电子商务系统 -> 系统收到支付宝信息后确定客户订单已经付款 -> 进行发货等后续流程。   
  
其实这个流程与以前讲paypal接口的基本类似,都是为了实现订单的自动付款确认。   
  
paypal与支付宝在使用时候有一点区别:paypal接口是直接通过一个form提交给paypal网站;而支付宝是通过一个url跳转到支付宝网站的。   
  
在开始下面的内容之前,你要先有一个支付宝账户,如果要集成支付宝接口,你还必须申请开通服务(关于如何开通,可以直接到支付宝网站上申请).在服务开通后,支付宝会给你2个字符串编号:1个partnerId(合作伙伴ID),还有1个securityCode(安全码).当你拿到这2个码的时候就可以开始下面的内容了.   
  
(1)如何调用支付宝接口?(将客户的订单信息按照既定的规则生成一个url跳转到支付宝网站)   
  
通过下面方法[makeOrderAlipayUrl(HttpServletRequest httpRequest,Order order)]的调用得到支付宝的url,然后进行跳转(response.sendRedirect(url);).

  1. Java代码   
  2. /**   
  3.      * 根据订单生成支付宝接口URL.   
  4.      * @param httpRequest   
  5.      * @param order 订单实例   
  6.      * @return   
  7.      * @throws Exception   
  8.      */   
  9.     public static String makeOrderAlipayUrl(HttpServletRequest httpRequest,Order order) throws Exception {     
  10.         HashMap hm = new HashMap();     
  11.         hm.put("_input_charset",httpRequest.getCharacterEncoding());//采用相同的编码方式     
  12.         hm.put("body","您在www.xxx.com上的订单");//填写在跳到支付宝页面上显示的付款内容信息     
  13.         hm.put("discount","-5");//填写折扣信息 -5表示抵扣5元     
  14.         hm.put("logistics_fee","10");//物流费用     
  15.         hm.put("logistics_payment","BUYER_PAY");//物流费用支付人 BUYER_PAY=买家支付物流费用     
  16.         hm.put("logistics_type","EXPRESS");//物流方式     
  17.         hm.put("notify_url","http://www.xxx.com/notifyurl.jsp");//客户付款后,支付宝调用的页面     
  18.         hm.put("out_trade_no",order.getId());//外部交易号,最好具有唯一性,在获取支付宝发来的付款信息时使用.     
  19.         hm.put("partner",partnerId);//partnerId(合作伙伴ID)     
  20.         hm.put("agent",partnerId);//partnerId(合作伙伴ID)     
  21.         hm.put("payment_type","1");//支付类型 1=商品购买,2=服务购买,...     
  22.         hm.put("price","105.30");//订单金额信息     
  23.         hm.put("quantity","1");//订单商品数量,一般都是写1,它是按照整个订单包来计算     
  24.         hm.put("return_url","http://www.xxx.com/ReturnUrl.jsp");//客户付款成功后,显示给客户的页面     
  25.         hm.put("seller_email","alipay@xxx.com");//你的支付宝账户email     
  26.         hm.put("service","create_direct_pay_by_user");//create_direct_pay_by_user=直接付款,trade_create_by_buyer 担保付款      
  27.         hm.put("subject","www.xxx.com的订单");//填写在跳到支付宝页面上显示的付款标题信息     
  28.         String payGateway = "https://www.alipay.com/cooperate/gateway.do?";//跳转到支付宝的url头     
  29.         return makeUrl(hm,securityCode,httpRequest.getCharacterEncoding(),payGateway);//securityCode(安全码)      
  30.     }     
  31.          
  32.          
  33.     /**   
  34.      * 根据传入的参数生成alipay的支付URL   
  35.      * @param hm 参数值   
  36.      * @param securityCode 安全码   
  37.      * @param charset 编码   
  38.      * @param payGateway 支付宝gateway   
  39.      * @return   
  40.      */   
  41.     public static String makeUrl(HashMap hm,String securityCode,String charset,String payGateway) throws Exception{     
  42.         List keys = new ArrayList(hm.keySet());     
  43.         Collections.sort(keys);//支付宝要求参数必须按字母排序     
  44.         StringBuffer content = new StringBuffer();     
  45.         for (int i = 0; i < keys.size(); i++) {     
  46.             content.append((String) keys.get(i));     
  47.             content.append("=");     
  48.             content.append((String) hm.get((String) keys.get(i)));     
  49.             if (i != keys.size() - 1) {     
  50.                 content.append("&");     
  51.             }     
  52.         }     
  53.         content.append(securityCode);     
  54.         String sign = md5(content.toString(),charset);     
  55.         content.delete(0,content.length());     
  56.         content.append(payGateway);     
  57.         for (int i = 0; i < keys.size(); i++) {     
  58.             content.append(keys.get(i));     
  59.             content.append("=");     
  60.             content.append(URLEncoder.encode((String) hm.get(keys.get(i)), charset));     
  61.             content.append("&");     
  62.         }     
  63.         content.append("sign=");     
  64.         content.append(sign);     
  65.         content.append("&sign_type=MD5");     
  66.         keys.clear();     
  67.         keys = null;     
  68.         return content.toString();     
  69.     }     
  70.          
  71.     /**   
  72.      * 生成md5编码字符串.   
  73.      * @param str 源字符串   
  74.      * @param charset 编码方式   
  75.      * @return   
  76.      *   
  77.      */   
  78.     public static String md5(String str,String charset) {     
  79.         if (str == null)     
  80.             return null;     
  81.         char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',     
  82.                 'a', 'b', 'c', 'd', 'e', 'f' };     
  83.             
  84.         MessageDigest md5MessageDigest = null;     
  85.         byte[] md5Bytes = null;     
  86.         char md5Chars[] = null;     
  87.         byte[] strBytes = null;     
  88.         try {     
  89.             strBytes = str.getBytes(charset);     
  90.             md5MessageDigest = MessageDigest.getInstance("MD5");     
  91.             md5MessageDigest.update(strBytes);     
  92.             md5Bytes = md5MessageDigest.digest();     
  93.             int j = md5Bytes.length;     
  94.             md5Chars = new char[j * 2];     
  95.             int k = 0;     
  96.             for (int i = 0; i < j; i++) {     
  97.                 byte md5Byte = md5Bytes[i];     
  98.                 md5Chars[k++] = hexDigits[md5Byte >>> 4 & 0xf];     
  99.                 md5Chars[k++] = hexDigits[md5Byte & 0xf];     
  100.             }     
  101.             return new String(md5Chars);     
  102.         } catch (NoSuchAlgorithmException e) {     
  103.             //Log.output(e.toString(), Log.STD_ERR);     
  104.             return null;     
  105.         } catch (UnsupportedEncodingException e) {     
  106.             //Log.output(e.toString(), Log.STD_ERR);     
  107.             return null;     
  108.         } finally {     
  109.             md5MessageDigest = null;     
  110.             strBytes = null;     
  111.             md5Bytes = null;     
  112.         }     
  113.     }   
  114.   
  115. /**
  116.      * 根据订单生成支付宝接口URL.
  117.      * @param httpRequest
  118.      * @param order 订单实例
  119.      * @return
  120.      * @throws Exception
  121.      */  
  122.     public static String makeOrderAlipayUrl(HttpServletRequest httpRequest,Order order) throws Exception {  
  123.         HashMap hm = new HashMap();  
  124.         hm.put("_input_charset",httpRequest.getCharacterEncoding());//采用相同的编码方式  
  125.         hm.put("body","您在www.xxx.com上的订单");//填写在跳到支付宝页面上显示的付款内容信息  
  126.         hm.put("discount","-5");//填写折扣信息 -5表示抵扣5元  
  127.         hm.put("logistics_fee","10");//物流费用  
  128.         hm.put("logistics_payment","BUYER_PAY");//物流费用支付人 BUYER_PAY=买家支付物流费用  
  129.         hm.put("logistics_type","EXPRESS");//物流方式  
  130.         hm.put("notify_url","http://www.xxx.com/notifyurl.jsp");//客户付款后,支付宝调用的页面  
  131.         hm.put("out_trade_no",order.getId());//外部交易号,最好具有唯一性,在获取支付宝发来的付款信息时使用.  
  132.         hm.put("partner",partnerId);//partnerId(合作伙伴ID)  
  133.         hm.put("agent",partnerId);//partnerId(合作伙伴ID)  
  134.         hm.put("payment_type","1");//支付类型 1=商品购买,2=服务购买,...  
  135.         hm.put("price","105.30");//订单金额信息  
  136.         hm.put("quantity","1");//订单商品数量,一般都是写1,它是按照整个订单包来计算  
  137.         hm.put("return_url","http://www.xxx.com/ReturnUrl.jsp");//客户付款成功后,显示给客户的页面  
  138.         hm.put("seller_email","alipay@xxx.com");//你的支付宝账户email  
  139.         hm.put("service","create_direct_pay_by_user");//create_direct_pay_by_user=直接付款,trade_create_by_buyer 担保付款   
  140.         hm.put("subject","www.xxx.com的订单");//填写在跳到支付宝页面上显示的付款标题信息  
  141.         String payGateway = "https://www.alipay.com/cooperate/gateway.do?";//跳转到支付宝的url头  
  142.         return makeUrl(hm,securityCode,httpRequest.getCharacterEncoding(),payGateway);//securityCode(安全码)   
  143.     }  
  144.       
  145.       
  146.     /**
  147.      * 根据传入的参数生成alipay的支付URL
  148.      * @param hm 参数值
  149.      * @param securityCode 安全码
  150.      * @param charset 编码
  151.      * @param payGateway 支付宝gateway
  152.      * @return
  153.      */  
  154.     public static String makeUrl(HashMap hm,String securityCode,String charset,String payGateway) throws Exception{  
  155.         List keys = new ArrayList(hm.keySet());  
  156.         Collections.sort(keys);//支付宝要求参数必须按字母排序  
  157.         StringBuffer content = new StringBuffer();  
  158.         for (int i = 0; i < keys.size(); i++) {  
  159.             content.append((String) keys.get(i));  
  160.             content.append("=");  
  161.             content.append((String) hm.get((String) keys.get(i)));  
  162.             if (i != keys.size() - 1) {  
  163.                 content.append("&");  
  164.             }  
  165.         }  
  166.         content.append(securityCode);  
  167.         String sign = md5(content.toString(),charset);  
  168.         content.delete(0,content.length());  
  169.         content.append(payGateway);  
  170.         for (int i = 0; i < keys.size(); i++) {  
  171.             content.append(keys.get(i));  
  172.             content.append("=");  
  173.             content.append(URLEncoder.encode((String) hm.get(keys.get(i)), charset));  
  174.             content.append("&");  
  175.         }  
  176.         content.append("sign=");  
  177.         content.append(sign);  
  178.         content.append("&sign_type=MD5");  
  179.         keys.clear();  
  180.         keys = null;  
  181.         return content.toString();  
  182.     }  
  183.       
  184.     /**
  185.      * 生成md5编码字符串.
  186.      * @param str 源字符串
  187.      * @param charset 编码方式
  188.      * @return
  189.      *
  190.      */  
  191.     public static String md5(String str,String charset) {  
  192.         if (str == null)  
  193.             return null;  
  194.         char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',  
  195.                 'a', 'b', 'c', 'd', 'e', 'f' };  
  196.          
  197.         MessageDigest md5MessageDigest = null;  
  198.         byte[] md5Bytes = null;  
  199.         char md5Chars[] = null;  
  200.         byte[] strBytes = null;  
  201.         try {  
  202.             strBytes = str.getBytes(charset);  
  203.             md5MessageDigest = MessageDigest.getInstance("MD5");  
  204.             md5MessageDigest.update(strBytes);  
  205.             md5Bytes = md5MessageDigest.digest();  
  206.             int j = md5Bytes.length;  
  207.             md5Chars = new char[j * 2];  
  208.             int k = 0;  
  209.             for (int i = 0; i < j; i++) {  
  210.                 byte md5Byte = md5Bytes[i];  
  211.                 md5Chars[k++] = hexDigits[md5Byte >>> 4 & 0xf];  
  212.                 md5Chars[k++] = hexDigits[md5Byte & 0xf];  
  213.             }  
  214.             return new String(md5Chars);  
  215.         } catch (NoSuchAlgorithmException e) {  
  216.             //Log.output(e.toString(), Log.STD_ERR);  
  217.             return null;  
  218.         } catch (UnsupportedEncodingException e) {  
  219.             //Log.output(e.toString(), Log.STD_ERR);  
  220.             return null;  
  221.         } finally {  
  222.             md5MessageDigest = null;  
  223.             strBytes = null;  
  224.             md5Bytes = null;  
  225.         }  
  226.     }  
  227.   
  228.   
  229. 当客户通过接口url付款后,支付宝会自动的去调用前面提供的[notify_url]参数中的url.   
  230.   
  231. (2)支付宝将付款信息返回给系统   
  232. 当客户付款后,支付宝就会自动调用上面表单提供的[notify_url],下面是一个[notifyurl.jsp]的一个例子:   
  233. Html代码   
  234. <%@ page contentType="text/html;charset=UTF-8"%><%@ page import="com.soft4j.AlipayMgr"%><%     
  235.     String ret = AlipayMgr.insert(request);     
  236.     if(ret==null){     
  237.         out.print("success");//成功接收支付宝发来的付款信息     
  238.     }else{     
  239.         out.print("fail");//出错     
  240.     }     
  241. %>   
  242.   
  243. <%@ page contentType="text/html;charset=UTF-8"%><%@ page import="com.soft4j.AlipayMgr"%><%  
  244.     String ret = AlipayMgr.insert(request);  
  245.     if(ret==null){  
  246.         out.print("success");//成功接收支付宝发来的付款信息  
  247.     }else{  
  248.         out.print("fail");//出错  
  249.     }  
  250. %>  
  251.   
  252. 如果确认收到支付宝发来的客户付款信息,则返回"success",这样子支付宝就知道系统已经收到信息了;否则返回"fail",这样支付宝会过一段时间后再次发来。其实,只有当支付宝收到"success"的返回信息后才会停止发送付款信息,否则会自动的每隔一段时间就调用上面   
  253. 的[notify_url]通信接口。   
  254.   
  255. (3)系统处理支付宝发来的付款信息   
  256.   
  257. Java代码   
  258. /*   
  259. * Created on 2005-6-12   
  260. * Author stephen   
  261. * Email zhoujianqiang AT gmail DOT com   
  262. * CopyRight(C)2005-2008 , All rights reserved.   
  263. */   
  264. package com.soft4j;     
  265.    
  266. import java.sql.Connection;     
  267. import java.sql.SQLException;     
  268. import java.util.Enumeration;     
  269. import java.util.Vector;     
  270. import javax.servlet.http.HttpServletRequest;     
  271.    
  272. /**   
  273. * 支付宝付款通知接口.   
  274. *   
  275. * @author stephen   
  276. * @version 1.0.0   
  277. */   
  278. public final class NotifyUrlMgr {     
  279.          
  280.          
  281.     public static String insert(HttpServletRequest httpRequest) {     
  282.             
  283.         //定义变量和进行必要的初始化工作     
  284.         Enumeration parameterNames = null;     
  285.         String parameterName = null;     
  286.         String parameterValue = null;     
  287.         int count = 0;     
  288.         Vector[] params = null;     
  289.         Vector vParameterName = new Vector();     
  290.         Vector vParameterValue = new Vector();     
  291.             
  292.         try {     
  293.             String orderId = httpRequest.getParameter("out_trade_no");//订单号     
  294.             if(orderId==null||"".equals(orderId)) orderId="-1";     
  295.             parameterNames = httpRequest.getParameterNames();     
  296.             boolean isPrint = false;     
  297.             while (parameterNames.hasMoreElements()) {//循环收取支付宝发来的所有参数信息     
  298.                 parameterName = (String) parameterNames.nextElement();     
  299.                 parameterValue = httpRequest.getParameter(parameterName);     
  300.                 if(parameterValue==null) parameterValue="";     
  301.                 vParameterName.add(parameterName);     
  302.                 vParameterValue.add(parameterValue);     
  303.                 count++;     
  304.             }     
  305.                  
  306.             //这里添加对收到信息的处理:一般是将这些信息存入数据库,然后对客户的订单进行处理.     
  307.                  
  308.             return null;     
  309.         } catch (Exception e) {     
  310.             return e.toString();     
  311.         } finally {     
  312.             //     
  313.         }     
  314.     }     
  315.    
  316. }   
  317.   
  318. /*
  319. * Created on 2005-6-12
  320. * Author stephen
  321. * Email zhoujianqiang AT gmail DOT com
  322. * CopyRight(C)2005-2008 , All rights reserved.
  323. */  
  324. package com.soft4j;  
  325.   
  326. import java.sql.Connection;  
  327. import java.sql.SQLException;  
  328. import java.util.Enumeration;  
  329. import java.util.Vector;  
  330. import javax.servlet.http.HttpServletRequest;  
  331.   
  332. /**
  333. * 支付宝付款通知接口.
  334. *  
  335. * @author stephen
  336. * @version 1.0.0
  337. */  
  338. public final class NotifyUrlMgr {  
  339.       
  340.       
  341.     public static String insert(HttpServletRequest httpRequest) {  
  342.          
  343.         //定义变量和进行必要的初始化工作  
  344.         Enumeration parameterNames = null;  
  345.         String parameterName = null;  
  346.         String parameterValue = null;  
  347.         int count = 0;  
  348.         Vector[] params = null;  
  349.         Vector vParameterName = new Vector();  
  350.         Vector vParameterValue = new Vector();  
  351.          
  352.         try {  
  353.             String orderId = httpRequest.getParameter("out_trade_no");//订单号  
  354.             if(orderId==null||"".equals(orderId)) orderId="-1";  
  355.             parameterNames = httpRequest.getParameterNames();  
  356.             boolean isPrint = false;  
  357.             while (parameterNames.hasMoreElements()) {//循环收取支付宝发来的所有参数信息  
  358.                 parameterName = (String) parameterNames.nextElement();  
  359.                 parameterValue = httpRequest.getParameter(parameterName);  
  360.                 if(parameterValue==null) parameterValue="";  
  361.                 vParameterName.add(parameterName);  
  362.                 vParameterValue.add(parameterValue);  
  363.                 count++;  
  364.             }  
  365.               
  366.             //这里添加对收到信息的处理:一般是将这些信息存入数据库,然后对客户的订单进行处理.  
  367.               
  368.             return null;  
  369.         } catch (Exception e) {  
  370.             return e.toString();  
  371.         } finally {  
  372.             //  
  373.         }  
  374.     }  
  375.   
  376. }  
复制代码