java實現在線支付

國內電子商務系統實現的基本流程如下: 
客戶在系統內下訂單 -> 系統根據訂單生成支付寶接口url -> 客戶通過url使用支付寶(網上銀行)付款 -> 支付寶將客戶的付款完成信息發送給電子商務系統 -> 系統收到支付寶信息後確定客戶訂單已經付款 -> 進行發貨等後續流程。

在開始下面的內容之前,你要先有一個支付寶賬戶,如果要集成支付寶接口,你還必須申請開通服務(關於如何開通,可以直接到支付寶網站上申請).在服務開通後,支付寶會給你2個字符串編號:1個partnerId(合作伙伴ID),還有1個securityCode(安全碼).當你拿到這2個碼的時候就可以開始下面的內容了.
(1)如何調用支付寶接口?(將客戶的訂單信息按照既定的規則生成一個url跳轉到支付寶網站) 

通過下面方法[makeOrderAlipayUrl(HttpServletRequest httpRequest,Order order)]的調用得到支付寶的url,然後進行跳轉(response.sendRedirect(url);).

[html] view plaincopy
  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","[email protected]");//你的支付寶賬戶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.      * 根據傳入的參數生成alipay的支付URL      
  32.      * @param hm 參數值      
  33.      * @param securityCode 安全碼      
  34.      * @param charset 編碼      
  35.      * @param payGateway 支付寶gateway      
  36.      * @return      
  37.      */       
  38.     public static String makeUrl(HashMap hm,String securityCode,String charset,String payGateway) throws Exception{        
  39.         List keys = new ArrayList(hm.keySet());        
  40.         Collections.sort(keys);//支付寶要求參數必須按字母排序        
  41.         StringBuffer content = new StringBuffer();        
  42.         for (int i = 0; i < keys.size(); i++) {        
  43.             content.append((String) keys.get(i));        
  44.             content.append("=");        
  45.             content.append((String) hm.get((String) keys.get(i)));        
  46.             if (i != keys.size() - 1) {        
  47.                 content.append("&");        
  48.             }        
  49.         }        
  50.         content.append(securityCode);        
  51.         String sign = md5(content.toString(),charset);        
  52.         content.delete(0,content.length());        
  53.         content.append(payGateway);        
  54.         for (int i = 0; i < keys.size(); i++) {        
  55.             content.append(keys.get(i));        
  56.             content.append("=");        
  57.             content.append(URLEncoder.encode((String) hm.get(keys.get(i)), charset));        
  58.             content.append("&");        
  59.         }        
  60.         content.append("&sign_type=MD5");        
  61.         keys.clear();        
  62.         keys = null;        
  63.         return content.toString();        
  64.     }        
  65.     /**      
  66.      * 生成md5編碼字符串.      
  67.      * @param str 源字符串      
  68.      * @param charset 編碼方式      
  69.      * @return      
  70.      *      
  71.      */       
  72.     public static String md5(String str,String charset) {        
  73.         if (str == null)        
  74.             return null;        
  75.         char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',        
  76.                 'a', 'b', 'c', 'd', 'e', 'f' };        
  77.         MessageDigest md5MessageDigest = null;        
  78.         byte[] md5Bytes = null;        
  79.         char md5Chars[] = null;        
  80.         byte[] strBytes = null;        
  81.         try {        
  82.             strBytes = str.getBytes(charset);        
  83.             md5MessageDigest = MessageDigest.getInstance("MD5");        
  84.             md5MessageDigest.update(strBytes);        
  85.             md5Bytes = md5MessageDigest.digest();        
  86.             int j = md5Bytes.length;        
  87.             md5Chars = new char[j * 2];        
  88.             int k = 0;        
  89.             for (int i = 0; i < j; i++) {        
  90.                 byte md5Byte = md5Bytes;        
  91.                 md5Chars[k++] = hexDigits[md5Byte >>> 4 & 0xf];        
  92.                 md5Chars[k++] = hexDigits[md5Byte & 0xf];        
  93.             }        
  94.             return new String(md5Chars);        
  95.         } catch (NoSuchAlgorithmException e) {        
  96.             //Log.output(e.toString(), Log.STD_ERR);        
  97.             return null;        
  98.         } catch (UnsupportedEncodingException e) {        
  99.             //Log.output(e.toString(), Log.STD_ERR);        
  100.             return null;        
  101.         } finally {        
  102.             md5MessageDigest = null;        
  103.             strBytes = null;        
  104.             md5Bytes = null;        
  105.         }        
  106.     }    

當客戶通過接口url付款後,支付寶會自動的去調用前面提供的[notify_url]參數中的url. 

(2)支付寶將付款信息返回給系統 
當客戶付款後,支付寶就會自動調用上面表單提供的[notify_url],下面是一個[notifyurl.jsp]的一個例子:

[html] view plaincopy
  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] view plaincopy
  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. import java.sql.Connection;        
  9. import java.sql.SQLException;        
  10. import java.util.Enumeration;        
  11. import java.util.Vector;        
  12. import javax.servlet.http.HttpServletRequest;        
  13. /**     
  14.  * 支付寶付款通知接口.     
  15.  *      
  16.  * @author stephen     
  17.  * @version 1.0.0     
  18.  */       
  19. public final class NotifyUrlMgr {        
  20.     public static String insert(HttpServletRequest httpRequest) {        
  21.         //定義變量和進行必要的初始化工作        
  22.         Enumeration parameterNames = null;        
  23.         String parameterName = null;        
  24.         String parameterValue = null;        
  25.         int count = 0;        
  26.         Vector[] params = null;        
  27.         Vector vParameterName = new Vector();        
  28.         Vector vParameterValue = new Vector();        
  29.         try {        
  30.             String orderId = httpRequest.getParameter("out_trade_no");//訂單號        
  31.             if(orderId==null||"".equals(orderId)) orderId="-1";        
  32.             parameterNames = httpRequest.getParameterNames();        
  33.             boolean isPrint = false;        
  34.             while (parameterNames.hasMoreElements()) {//循環收取支付寶發來的所有參數信息        
  35.                 parameterName = (String) parameterNames.nextElement();        
  36.                 parameterValue = httpRequest.getParameter(parameterName);        
  37.                 if(parameterValue==null) parameterValue="";        
  38.                 vParameterName.add(parameterName);        
  39.                 vParameterValue.add(parameterValue);        
  40.                 count++;        
  41.             }        
  42.             //這裏添加對收到信息的處理:一般是將這些信息存入數據庫,然後對客戶的訂單進行處理.        
  43.             return null;        
  44.         } catch (Exception e) {        
  45.             return e.toString();        
  46.         } finally {         
  47.         }        
  48.     }        
  49. }   
發佈了19 篇原創文章 · 獲贊 59 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章