step-by-step集成阿里巴巴支付宝接口

来源:互联网 发布:sql server 2014教程 编辑:程序博客网 时间:2024/05/17 23:39

关于支付宝的一些信息可以直接访问支付宝网站https://www.alipay.com/。

国内电子商务系统实现的基本流程如下:
客户在系统内下订单 -> 系统根据订单生成支付宝接口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);).

Java代码
  1. /**  
  2.      * 根据订单生成支付宝接口URL.  
  3.      * @param httpRequest  
  4.      * @param order 订单实例  
  5.      * @return  
  6.      * @throws Exception  
  7.      */  
  8.     public static String makeOrderAlipayUrl(HttpServletRequest httpRequest,Order order) throws Exception {   
  9.         HashMap hm = new HashMap();   
  10.         hm.put("_input_charset",httpRequest.getCharacterEncoding());//采用相同的编码方式   
  11.         hm.put("body","您在www.xxx.com上的订单");//填写在跳到支付宝页面上显示的付款内容信息   
  12.         hm.put("discount","-5");//填写折扣信息 -5表示抵扣5元   
  13.         hm.put("logistics_fee","10");//物流费用   
  14.         hm.put("logistics_payment","BUYER_PAY");//物流费用支付人 BUYER_PAY=买家支付物流费用   
  15.         hm.put("logistics_type","EXPRESS");//物流方式   
  16.         hm.put("notify_url","http://www.xxx.com/notifyurl.jsp");//客户付款后,支付宝调用的页面   
  17.         hm.put("out_trade_no",order.getId());//外部交易号,最好具有唯一性,在获取支付宝发来的付款信息时使用.   
  18.         hm.put("partner",partnerId);//partnerId(合作伙伴ID)   
  19.         hm.put("agent",partnerId);//partnerId(合作伙伴ID)   
  20.         hm.put("payment_type","1");//支付类型 1=商品购买,2=服务购买,...   
  21.         hm.put("price","105.30");//订单金额信息   
  22.         hm.put("quantity","1");//订单商品数量,一般都是写1,它是按照整个订单包来计算   
  23.         hm.put("return_url","http://www.xxx.com/ReturnUrl.jsp");//客户付款成功后,显示给客户的页面   
  24.         hm.put("seller_email","alipay@xxx.com");//你的支付宝账户email   
  25.         hm.put("service","create_direct_pay_by_user");//create_direct_pay_by_user=直接付款,trade_create_by_buyer 担保付款    
  26.         hm.put("subject","www.xxx.com的订单");//填写在跳到支付宝页面上显示的付款标题信息   
  27.         String payGateway = "https://www.alipay.com/cooperate/gateway.do?";//跳转到支付宝的url头   
  28.         return makeUrl(hm,securityCode,httpRequest.getCharacterEncoding(),payGateway);//securityCode(安全码)    
  29.     }   
  30.        
  31.        
  32.     /**  
  33.      * 根据传入的参数生成alipay的支付URL  
  34.      * @param hm 参数值  
  35.      * @param securityCode 安全码  
  36.      * @param charset 编码  
  37.      * @param payGateway 支付宝gateway  
  38.      * @return  
  39.      */  
  40.     public static String makeUrl(HashMap hm,String securityCode,String charset,String payGateway) throws Exception{   
  41.         List keys = new ArrayList(hm.keySet());   
  42.         Collections.sort(keys);//支付宝要求参数必须按字母排序   
  43.         StringBuffer content = new StringBuffer();   
  44.         for (int i = 0; i < keys.size(); i++) {   
  45.             content.append((String) keys.get(i));   
  46.             content.append("=");   
  47.             content.append((String) hm.get((String) keys.get(i)));   
  48.             if (i != keys.size() - 1) {   
  49.                 content.append("&");   
  50.             }   
  51.         }   
  52.         content.append(securityCode);   
  53.         String sign = md5(content.toString(),charset);   
  54.         content.delete(0,content.length());   
  55.         content.append(payGateway);   
  56.         for (int i = 0; i < keys.size(); i++) {   
  57.             content.append(keys.get(i));   
  58.             content.append("=");   
  59.             content.append(URLEncoder.encode((String) hm.get(keys.get(i)), charset));   
  60.             content.append("&");   
  61.         }   
  62.         content.append("sign=");   
  63.         content.append(sign);   
  64.         content.append("&sign_type=MD5");   
  65.         keys.clear();   
  66.         keys = null;   
  67.         return content.toString();   
  68.     }   
  69.        
  70.     /**  
  71.      * 生成md5编码字符串.  
  72.      * @param str 源字符串  
  73.      * @param charset 编码方式  
  74.      * @return  
  75.      *  
  76.      */  
  77.     public static String md5(String str,String charset) {   
  78.         if (str == null)   
  79.             return null;   
  80.         char hexDigits[] = { '0''1''2''3''4''5''6''7''8''9',   
  81.                 'a''b''c''d''e''f' };   
  82.            
  83.         MessageDigest md5MessageDigest = null;   
  84.         byte[] md5Bytes = null;   
  85.         char md5Chars[] = null;   
  86.         byte[] strBytes = null;   
  87.         try {   
  88.             strBytes = str.getBytes(charset);   
  89.             md5MessageDigest = MessageDigest.getInstance("MD5");   
  90.             md5MessageDigest.update(strBytes);   
  91.             md5Bytes = md5MessageDigest.digest();   
  92.             int j = md5Bytes.length;   
  93.             md5Chars = new char[j * 2];   
  94.             int k = 0;   
  95.             for (int i = 0; i < j; i++) {   
  96.                 byte md5Byte = md5Bytes[i];   
  97.                 md5Chars[k++] = hexDigits[md5Byte >>> 4 & 0xf];   
  98.                 md5Chars[k++] = hexDigits[md5Byte & 0xf];   
  99.             }   
  100.             return new String(md5Chars);   
  101.         } catch (NoSuchAlgorithmException e) {   
  102.             //Log.output(e.toString(), Log.STD_ERR);   
  103.             return null;   
  104.         } catch (UnsupportedEncodingException e) {   
  105.             //Log.output(e.toString(), Log.STD_ERR);   
  106.             return null;   
  107.         } finally {   
  108.             md5MessageDigest = null;   
  109.             strBytes = null;   
  110.             md5Bytes = null;   
  111.         }   
  112.     }  



当客户通过接口url付款后,支付宝会自动的去调用前面提供的[notify_url]参数中的url.

(2)支付宝将付款信息返回给系统
当客户付款后,支付宝就会自动调用上面表单提供的[notify_url],下面是一个[notifyurl.jsp]的一个例子:

Html代码
  1. <%@ page contentType="text/html;charset=UTF-8"%><%@ page import="com.soft4j.AlipayMgr"%><%   
  2.     String ret = AlipayMgr.insert(request);   
  3.     if(ret==null){   
  4.         out.print("success");//成功接收支付宝发来的付款信息   
  5.     }else{   
  6.         out.print("fail");//出错   
  7.     }   
  8. %>  


如果确认收到支付宝发来的客户付款信息,则返回"success",这样子支付宝就知道系统已经收到信息了;否则返回"fail",这样支付宝会过一段时间后再次发来。其实,只有当支付宝收到"success"的返回信息后才会停止发送付款信息,否则会自动的每隔一段时间就调用上面
的[notify_url]通信接口。

(3)系统处理支付宝发来的付款信息

Java代码
  1. /*  
  2.  * Created on 2005-6-12  
  3.  * Author stephen  
  4.  * Email zhoujianqiang AT gmail DOT com  
  5.  * CopyRight(C)2005-2008 , All rights reserved.  
  6.  */  
  7. package com.soft4j;   
  8.   
  9. import java.sql.Connection;   
  10. import java.sql.SQLException;   
  11. import java.util.Enumeration;   
  12. import java.util.Vector;   
  13. import javax.servlet.http.HttpServletRequest;   
  14.   
  15. /**  
  16.  * 支付宝付款通知接口.  
  17.  *   
  18.  * @author stephen  
  19.  * @version 1.0.0  
  20.  */  
  21. public final class NotifyUrlMgr {   
  22.        
  23.        
  24.     public static String insert(HttpServletRequest httpRequest) {   
  25.            
  26.         //定义变量和进行必要的初始化工作   
  27.         Enumeration parameterNames = null;   
  28.         String parameterName = null;   
  29.         String parameterValue = null;   
  30.         int count = 0;   
  31.         Vector[] params = null;   
  32.         Vector vParameterName = new Vector();   
  33.         Vector vParameterValue = new Vector();   
  34.            
  35.         try {   
  36.             String orderId = httpRequest.getParameter("out_trade_no");//订单号   
  37.             if(orderId==null||"".equals(orderId)) orderId="-1";   
  38.             parameterNames = httpRequest.getParameterNames();   
  39.             boolean isPrint = false;   
  40.             while (parameterNames.hasMoreElements()) {//循环收取支付宝发来的所有参数信息   
  41.                 parameterName = (String) parameterNames.nextElement();   
  42.                 parameterValue = httpRequest.getParameter(parameterName);   
  43.                 if(parameterValue==null) parameterValue="";   
  44.                 vParameterName.add(parameterName);   
  45.                 vParameterValue.add(parameterValue);   
  46.                 count++;   
  47.             }   
  48.                
  49.             //这里添加对收到信息的处理:一般是将这些信息存入数据库,然后对客户的订单进行处理.   
  50.                
  51.             return null;   
  52.         } catch (Exception e) {   
  53.             return e.toString();   
  54.         } finally {   
  55.             //   
  56.         }   
  57.     }   
  58.   
  59. }  

http://stephen830.javaeye.com/blog/254827

这样系统可以在客户使用支付宝付款后,自动的根据支付宝发来的付款信息确认客户的付款情况,并进行相应的后续操作