淺談支付寶第三方支付

技術點(九):支付寶第三方支付
2)demo中必改參數:
java類AlipayConfig:
由公司提供參數:
合做身份者ID,以2088開頭由16位純數字組成的字符串:partner = "8888888888";
MD5密鑰,安全檢驗碼,由數字和字母組成的32位字符串:key = "xxxxxxxx";
固定參數:
簽名方式:sign_type = "MD5";
調試用,建立TXT日誌文件夾路徑:log_path = "D:\\";
字符編碼格式 目前支持 gbk 或 utf-8:input_charset = "utf-8";
3)demo所需jar
commons-codec-1.6.jar
commons-httpclient-3.0.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
jaxen-1.1-beta-6.jar
4)環境要求
java編譯(支持jdk1.6和jdk1.7)
tomcat運行環境目前支持jdk1.6以上版本
5)集成過程
1.將上述demo修改完成後,打成jar放到項目中。
2.編寫支付訂單邏輯,例如:
/**
     * guowb
     * 20150713
     * 訂單支付
     */
    public String getPayOrder(){
        try {
            Object  userId =  request.getSession().getAttribute("userId");
            if(userId!=null){
                boolean isNot = frontOrderService.getByOrderNo(order.getOrder_no(),userId.toString());
                if(isNot){//存在
                    Order o = frontOrderService.getByOrder(order);
                    if(o.getPay_status().equals("2")){//已支付
                        request.setAttribute("msg", "訂單已支付過了!");
                    }else{
                        //支付類型
                        String payment_type = "1";
                        //必填,不能修改
                        //服務器異步通知頁面路徑
                        String projectPath = ResourceUtil.getProjectPath();//獲取項目訪問路徑
 
                        String notify_url = projectPath+"/vkeplus/frontPayAction!notify_url.action";
                        //需http://格式的完整路徑,不能加?id=123這類自定義參數
 
                        //頁面跳轉同步通知頁面路徑
                        String return_url = projectPath+"/vkeplus/frontPayAction!return_alipay.action";
                        //需http://格式的完整路徑,不能加?id=123這類自定義參數,不能寫成 http://localhost/
 
                        //商戶訂單號
                        String out_trade_no = o.getOrder_no();
                        //商戶網站訂單系統中惟一訂單號,必填
 
                        //訂單名稱
                        String subject = o.getOrder_name();
                        //必填
 
                        //付款金額
                        String total_fee = o.getOrder_money()+"";
                        //必填
 
                        //訂單描述
 
                        String body = o.getOrder_remarks();
                        //商品展現地址
                        //String show_url = new String(request.getParameter("WIDshow_url").getBytes("ISO-8859-1"),"UTF-8");
                        //需以http://開頭的完整路徑,例如: http://www.商戶網址.com/myorder.html
 
                        //防釣魚時間戳
                        String anti_phishing_key = "";
                        //若要使用請調用類文件submit中的query_timestamp函數
 
                        //客戶端的IP地址
                        String exter_invoke_ip = this.getIpAddr(request);
                        //非局域網的外網IP地址,如:221.0.0.1
 
                        //把請求參數打包成數組
                        Map<String, String> sParaTemp = new HashMap<String, String>();
                        sParaTemp.put("service", "create_direct_pay_by_user");
                        sParaTemp.put("partner", AlipayConfig.partner);
                        sParaTemp.put("seller_email", AlipayConfig.seller_email);
                        sParaTemp.put("_input_charset", AlipayConfig.input_charset);
                        sParaTemp.put("payment_type", payment_type);
                        sParaTemp.put("notify_url", notify_url);
                        sParaTemp.put("return_url", return_url);
                        sParaTemp.put("out_trade_no", out_trade_no);
                        sParaTemp.put("subject", subject);
                        sParaTemp.put("total_fee", total_fee);
                        sParaTemp.put("body", body);
                        sParaTemp.put("show_url", "");
                        sParaTemp.put("anti_phishing_key", anti_phishing_key);
                        sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
 
 
 
                        //創建請求
                        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp,"get","確認");
                        request.setAttribute("sHtmlText", sHtmlText);
                    }
                }else{
                    request.setAttribute("msg", "訂單不存在!");
                }
            }else{
                request.setAttribute("msg", "用戶不在登錄狀態,請從新登錄!");
            }
        } catch (Exception e) {
            payLog.error(ExceptionUtil.getExceptionMessage(e));
        }
        return "pay";
    }
3.匯付寶支付完成後的同步和異步通知
/**
     *//***********頁面功能說明***********
     * 該頁面可在本機電腦測試
     * TRADE_FINISHED(表示交易已經成功結束,並不能再對該交易作後續操做);
     * TRADE_SUCCESS(表示交易已經成功結束,能夠對該交易作後續操做,如:分潤、退款等);
     * guowb
     * 20150714
     * 支付寶頁面跳轉同步通知
     */
    @Deprecated
    public String return_alipay(){
        try {
            //獲取支付寶GET過來反饋信息
            Map<String,String> params = new HashMap<String,String>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //亂碼解決,這段代碼在出現亂碼時使用。若是mysign和sign不相等也可使用這段代碼轉化
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
 
            //獲取支付寶的通知返回參數,可參考技術文檔中頁面跳轉同步通知參數列表(如下僅供參考)//
            //商戶訂單號
 
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
 
            //支付寶交易號
 
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
 
            //交易狀態
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
 
 
            //交易金額 
            String total_fee =  new String(request.getParameter("total_fee").getBytes("ISO-8859-1"),"UTF-8");
            String buyer_email = new String(request.getParameter("buyer_email").getBytes("ISO-8859-1"),"UTF-8");
 
            //客戶端ip
            String exter_invoke_ip = this.getIpAddr(request);
 
            //獲取支付寶的通知返回參數,可參考技術文檔中頁面跳轉同步通知參數列表(以上僅供參考)//
 
            //計算得出通知驗證結果
            boolean verify_result = AlipayNotify.verify(params);
 
            if(verify_result){//驗證成功
                boolean isNot = frontOrderService.getByOrderNo(out_trade_no,null);
                if(isNot){//存在\
                    order.setOrder_no(out_trade_no);
                    Order o = frontOrderService.getByOrder(order);
                    if(o.getPay_status().equals("2")){//已支付
                        request.setAttribute("total_fee", total_fee);
                        request.setAttribute("order_no", out_trade_no);
                        request.setAttribute("platformType", o.getPlatformType());
                        return "pay_success";
                    }else{
                        //——請根據您的業務邏輯來編寫程序(如下代碼僅做參考)——
                        if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
 
                            List<Ordergools>  ogList  = ordergoolsService.getOrdergoolsList(o.getId());
                            if(ogList!=null && ogList.size()>0){
                                for(int i=0;i<ogList.size();i++){
                                    if(!ogList.get(i).getVideoId().equals("0")){//不等於0 購買的視頻
                                        Video v = videoService.getById(ogList.get(i).getVideoId(), null);
                                        if(v==null){
                                            String msg = "error:[002]沒有該視頻,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                                            request.setAttribute("msg", msg);
                                            return "return_alipay";
                                        }
                                    }else{//
                                        if(ogList.get(i).getGoodsType().equals("2")){//課程
                                            Course c = courseService.getCourserById(ogList.get(i).getGoodsId());
                                            if(c==null){
                                                String msg = "error:[003]沒有該課程,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                                                request.setAttribute("msg", msg);
                                                return "return_alipay";
                                            }
                                        }else if(ogList.get(i).getGoodsType().equals("0")){//套餐
                                            Meal m = frontMealService.getById(ogList.get(i).getGoodsId());
                                            if(m==null){
                                                String msg = "error:[003]沒有該套餐,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                                                request.setAttribute("msg", msg);
                                                return "return_alipay";
                                            }
                                        }
                                    }
                                }
                            }
                            Date t = new Date();
                            try{
 
                                Order order = new Order();
                                //修改訂單狀態
                                order.setPay_status("2");//支付成功!
                                order.setOrder_status("1");//訂單狀態 完成
                                order.setPay_number(buyer_email);//支付者帳戶
                                order.setPnumber(trade_no);//第三方支付訂單號
                                order.setPmoney(Double.parseDouble(total_fee)*100);//到帳金額 
                                order.setPtime(t);
                                order.setPtype("1");//支付寶支付
                                order.setUser_ip(exter_invoke_ip);//用戶支付IP
                                frontOrderService.edit(o,order);
 
                                //fxw 20151117  支付訂單到PHP
                                //參數集
                                String parm = "out_trade_no="+out_trade_no;//訂單號
                                parm +="&buyer_email="+URLEncoder.encode(buyer_email,"utf-8");//支付者帳戶
                                parm +="&trade_no="+trade_no;//第三方支付訂單號
                                parm +="&total_fee="+total_fee;//到帳金額 (單位:分)
                                parm +="&exter_invoke_ip="+exter_invoke_ip;//Ip
 
                                HttpUtil.httpURLConnectionPOST(PhpParam.PAY_ORDER, parm);
 
 
                                int i=Math.round(Float.parseFloat(total_fee));//按消費金額取整
 
                                //購買送積分 fxw 20150915
                                ScoreDetail sd = new ScoreDetail();
                                User user = new User();
                                user.setCid(o.getUserId());
                                sd.setUserid(o.getUserId());
                                sd.setUsername(frontUserService.getUserById(user).getCname());
                                sd.setStatus(0);//消費
                                sd.setScorevalue(i);//金額
                                sd.setUri("/frontPayAction");
                                scoreDetailService.givingScore(sd);
 
                            } catch (Exception e) {
                                payLog.error(ExceptionUtil.getExceptionMessage(e));
                                String msg = "error:[005]訂單狀態修改失敗,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                                request.setAttribute("msg", msg);
                                return "return_alipay";
                            }
                            //發送郵件
                            String toEmail = ResourceUtil.toEmail();//接收郵件郵箱
                            String subject = "用戶成功提交了訂單【"+out_trade_no+"】的支付寶交易確認";
                            StringBuffer sb=new StringBuffer("<b>用戶成功提交了訂單【"+out_trade_no+"】的支付寶交易確認</b><br><br>");
                            sb.append("<table border=\"1\"><tr><td width=\"100px\">訂單號:</td><td width=\"400px\">"+out_trade_no+"</td></tr>");
                            sb.append("<tr><td>支付寶交易號:</td><td>"+trade_no+"</td></tr>");
                           // java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");  
                           // sb.append("<tr><td>實際需支付金額:</td><td>¥"+df.format(o.getOrder_money()/100)+"</td></tr>");
                            sb.append("<tr><td>實際需支付金額:</td><td>¥"+total_fee+"</td></tr>");
                            sb.append("<tr><td>確認金額:</td><td>¥"+total_fee+"</td></tr>");
                            sb.append("<tr><td>付款方式:</td><td>支付寶</td></tr>");
                            sb.append("<tr><td>支付者賬號:</td><td>"+buyer_email+"</td></tr>");
                            sb.append("<tr><td>下單時間:</td><td>"+TimeUtil.dateString(o.getOrder_time())+"</td></tr>");
                            sb.append("<tr><td>付款時間:</td><td>"+TimeUtil.dateString(t)+"</td></tr>");
                            sb.append("</table><br><br>");
 
                            SendEmail.send(toEmail,subject, sb.toString());//發送
 
                            request.setAttribute("total_fee", total_fee);
                            request.setAttribute("order_no", out_trade_no);
                            request.setAttribute("platformType", o.getPlatformType());
                            return "pay_success";
 
                        }else{
                            String msg = "error:[006]交易途中出現錯誤致使交易失敗,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                            request.setAttribute("msg", msg);
                            return "return_alipay";
                        }
                    }
                }else{
                    String msg = "error:[001]查無此訂單信息,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                    request.setAttribute("msg", msg);
                }
            }else{
                String msg = "error:[007]支付寶驗證失敗,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                request.setAttribute("msg", msg);
                return "return_alipay";
            }
        } catch (Exception e) {
            String msg = "error:[008]支付異常,請聯繫客服處理";
            request.setAttribute("msg", msg);
        }
        return "return_alipay";
    }
    /**
     * //***********頁面功能說明***********
     * 該頁面不能在本機電腦測試,請到服務器上作測試。請確保外部能夠訪問該頁面。
     * 該頁面調試工具請使用寫文本函數logResult,該函數在com.alipay.util文件夾的AlipayNotify.java類文件中
     * 若是沒有收到該頁面返回的 success 信息,支付寶會在24小時內按必定的時間策略重發通知
     * guowb
     * 20150715
     * 支付寶服務器異步通知
     */
    public void notify_url(){
        //記錄日誌 入文件
        PayLog pl = new PayLog();
        pl.setPayType("1");
        try{
            PrintWriter out=ServletActionContext.getResponse().getWriter(); 
 
             //獲取支付寶POST過來反饋信息
            Map<String,String> params = new HashMap<String,String>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //亂碼解決,這段代碼在出現亂碼時使用。若是mysign和sign不相等也可使用這段代碼轉化
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
                params.put(name, valueStr);
            }
 
            //獲取支付寶的通知返回參數,可參考技術文檔中頁面跳轉同步通知參數列表(如下僅供參考)//
            //商戶訂單號
 
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            pl.setVyankeOrder(out_trade_no);
            //支付寶交易號
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            pl.setThirdPartOrder(trade_no);
            //交易狀態
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
 
            //交易金額
            String total_fee =  new String(request.getParameter("total_fee").getBytes("ISO-8859-1"),"UTF-8");
            pl.setOrderMoney(total_fee);//交易金額(元)
            String buyer_email = new String(request.getParameter("buyer_email").getBytes("ISO-8859-1"),"UTF-8");
 
            //客戶端ip
            String exter_invoke_ip = this.getIpAddr(request);
 
            //獲取支付寶的通知返回參數,可參考技術文檔中頁面跳轉同步通知參數列表(以上僅供參考)//
 
            if(AlipayNotify.verify(params)){//驗證成功
                boolean isNot = frontOrderService.getByOrderNo(out_trade_no,null);
                if(isNot){//存在\
                    order.setOrder_no(out_trade_no);
                    Order o = frontOrderService.getByOrder(order);
                    pl.setOrderName(o.getOrder_name());//訂單名
                    pl.setGoodsName(o.getOrder_remarks());//訂單備註
 
                    if(o.getPay_status().equals("2")){//已支付
                        String msg = "error:[000]已支付過,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                        request.setAttribute("msg", msg);
                        out.println("fail"); 
                    }else{
                    //判斷該筆訂單是否在商戶網站中已經作過處理
                    //若是沒有作過處理,根據訂單號(out_trade_no)在商戶網站的訂單系統中查到該筆訂單的詳細,並執行商戶的業務程序
                    //若是有作過處理,不執行商戶的業務程序
                    /*if(trade_status.equals("TRADE_FINISHED")){
                            //注意:
                            //退款日期超過可退款期限後(如三個月可退款),支付寶系統發送該交易狀態通知
                        } else if (trade_status.equals("TRADE_SUCCESS")){
                            //注意:
                            //付款完成後,支付寶系統發送該交易狀態通知
                        }
                     */
                        //——請根據您的業務邏輯來編寫程序(如下代碼僅做參考)——
                        if(trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")){
                            pl.setPayStatus("0");//支付成功
                            List<Ordergools>  ogList  = ordergoolsService.getOrdergoolsList(o.getId());
                            if(ogList!=null && ogList.size()>0){
                                for(int i=0;i<ogList.size();i++){
                                    if(!ogList.get(i).getVideoId().equals("0")){//不等於0 購買的視頻
                                        Video v = videoService.getById(ogList.get(i).getVideoId(), null);
                                        if(v==null){
                                            String msg = "error:[002]沒有該視頻,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                                            request.setAttribute("msg", msg);
                                            out.println("fail"); 
                                        }
                                    }else{//
                                        if(ogList.get(i).getGoodsType().equals("2")){//課程
                                            Course c = courseService.getCourserById(ogList.get(i).getGoodsId());
                                            if(c==null){
                                                String msg = "error:[003]沒有該課程,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                                                request.setAttribute("msg", msg);
                                                out.println("fail"); 
                                            }else {
                                                //by lwj : 2015/9/1 ( 購買數量更新 )
                                                String update = this.courseService
                                                        .updateView_BuyNums(new Course(ogList.get(i).getGoodsId(),"buy"));
                                                payLog.info("當前課程:"+ogList.get(i).getGoodsId()+",購買數量更新狀態:" + update);
                                            }
                                        }else if(ogList.get(i).getGoodsType().equals("0")){//套餐
                                            Meal m = frontMealService.getById(ogList.get(i).getGoodsId());
                                            if(m==null){
                                                String msg = "error:[003]沒有該套餐,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                                                request.setAttribute("msg", msg);
                                                out.println("fail"); 
                                            }
                                        }
                                    }
                                }
                            }
                            Date t = new Date();
                            try{
 
                                Order order = new Order();
                                //修改訂單狀態
                                order.setPay_status("2");//支付成功!
                                order.setOrder_status("1");//訂單狀態 完成
                                order.setPay_number(buyer_email);
                                order.setPnumber(trade_no);
                                order.setPmoney(Double.parseDouble(total_fee)*100);//
                                order.setPtime(t);
 
                                pl.setOrderTime(DateUtils.format(t, "yyyy-MM-dd HH:mm:ss"));//日誌
                                order.setPtype("1");//支付寶支付
                                order.setUser_ip(exter_invoke_ip);//用戶支付IP
                                frontOrderService.edit(o,order);
 
                                //fxw 20151117  支付訂單到PHP
                                //參數集
                                String parm = "out_trade_no="+out_trade_no;//訂單號
                                parm +="&buyer_email="+URLEncoder.encode(buyer_email,"utf-8");//支付者帳戶
                                parm +="&trade_no="+trade_no;//第三方支付訂單號
                                parm +="&total_fee="+total_fee;//到帳金額 (單位:分)
                                parm +="&exter_invoke_ip="+exter_invoke_ip;//Ip
 
                                //調用PHP同步接口
                                String callback =HttpUtil.httpURLConnectionReturnPOST(PhpParam.PAY_ORDER, parm);
                                JSONObject resJson = AppJson.toJson((callback.replace("callback(", "")).replace(")", ""));
                                String ret = resJson.getString("ret");
                                //PHP返回狀態:0同步成功;1添加失敗;2已購買;3課程不存在;4用戶不存在5:課程ID爲空
                                if(!"0".equals(ret)){
                                    //添加同步失敗記錄
                                    System.out.println("同步失敗---編碼爲"+ret);
                                    //經過條件查詢用戶
                                    User syncuser = userService.getUserByName(o.getUsername());
                                    //同步出錯添加同步記錄表
                                    SyncDataInfo su = new SyncDataInfo();
                                    //用戶名
                                    su.setUsername(syncuser.getCname());
                                    //同步狀態
                                    su.setStatus(ret);
                                    //用戶手機號
                                    su.setMobilephone(syncuser.getUserInfo().getPhone());
                                    //同步類型:訂單支付同步
                                    su.setSynctype("2");
                                    su.setRemark("系統同步訂單支付狀態");//修改
                                    syncDataInfoService.addSyncDataInfo(su);
                                }
                                int i=Math.round(Float.parseFloat(total_fee));//按消費金額取整
 
                                //購買送積分 fxw 20150915
                                ScoreDetail sd = new ScoreDetail();
                                User user = new User();
                                user.setCid(o.getUserId());
                                sd.setUserid(o.getUserId());
                                User userById = frontUserService.getUserById(user);
                                sd.setUsername(userById.getCname()); // 用戶名
 
                                pl.setUsername(userById.getCname());//日誌:用戶名
 
                                UserInfo userInfo = userById.getUserInfo();
                                if(userInfo!=null){
                                    pl.setPhone(userInfo.getPhone());//日誌:手機號
                                }
                                sd.setStatus(0);//消費
                                sd.setScorevalue(i);//金額
                                sd.setUri("/frontPayAction");
                                scoreDetailService.givingScore(sd);
 
                            } catch (Exception e) {
                                payLog.error(ExceptionUtil.getExceptionMessage(e));
                                String msg = "error:[005]訂單狀態修改失敗,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                                request.setAttribute("msg", msg);
                                out.println("fail"); 
                            }
                            //發送郵件
                            String toEmail = ResourceUtil.toEmail();//接收郵件郵箱
                            String subject = "用戶成功提交了訂單【"+out_trade_no+"】的支付寶交易確認";
                            StringBuffer sb=new StringBuffer("<b>用戶成功提交了訂單【"+out_trade_no+"】的支付寶交易確認</b><br><br>");
                            sb.append("<table border=\"1\"><tr><td width=\"100px\">訂單號:</td><td width=\"400px\">"+out_trade_no+"</td></tr>");
                            sb.append("<tr><td>支付寶交易號:</td><td>"+trade_no+"</td></tr>");
                           // java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");  
                           // sb.append("<tr><td>實際需支付金額:</td><td>¥"+df.format(o.getOrder_money()/100)+"</td></tr>");
                            sb.append("<tr><td>實際需支付金額:</td><td>¥"+total_fee+"</td></tr>");
                            sb.append("<tr><td>確認金額:</td><td>¥"+total_fee+"</td></tr>");
                            sb.append("<tr><td>付款方式:</td><td>支付寶</td></tr>");
                            sb.append("<tr><td>支付者賬號:</td><td>"+buyer_email+"</td></tr>");
                            sb.append("<tr><td>下單時間:</td><td>"+TimeUtil.dateString(o.getOrder_time())+"</td></tr>");
                            sb.append("<tr><td>付款時間:</td><td>"+TimeUtil.dateString(t)+"</td></tr>");
                            sb.append("</table><br><br>");
 
                            SendEmail.send(toEmail,subject, sb.toString());//發送
 
                            String msg = "success:支付成功,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                            request.setAttribute("msg", msg);
                            out.println("success");  
 
                        }else{
                            pl.setPayStatus("1");//支付失敗
                            String msg = "error:[006]交易途中出現錯誤致使交易失敗,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                            request.setAttribute("msg", msg);
                            out.println("fail"); 
                        }
                    }
                }else{
                    String msg = "error:[001]查無此訂單信息,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                    request.setAttribute("msg", msg);
                    out.println("fail"); 
                }
            }else{//驗證失敗
                String msg = "error:[007]支付寶驗證失敗,請聯繫客服處理,您的訂單號爲:"+out_trade_no+",支付寶單號爲:"+trade_no+",交易狀態爲:"+trade_status;
                request.setAttribute("msg", msg);
                out.println("fail"); 
            }
        } catch (Exception e) {
            String msg = "error:[008]支付異常,請聯繫客服處理";
            request.setAttribute("msg", msg);
        }
        //記錄日誌 
        System.out.println("記錄日誌:--------------");
        payLog.debug("記錄日誌:--------------");
        payLog.debug(pl.toString());
    }
4.獲取用戶IP:
/**
     * @author guowb
     * @date 20160617
     * @desc 獲取客戶端ip
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("PRoxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
5.涉及到的頁面
alipayapi.jsp
<%
/* *
 *功能:即時到帳交易接口接入頁
 *版本:3.3
 *日期:2012-08-14
 *說明:
 *如下代碼只是爲了方便商戶測試而提供的樣例代碼,商戶能夠根據本身網站的須要,按照技術文檔編寫,並不是必定要使用該代碼。
 *該代碼僅供學習和研究支付寶接口使用,只是提供一個參考。
 
 *************************注意*****************
 *若是您在接口集成過程當中遇到問題,能夠按照下面的途徑來解決
 *一、商戶服務中心( https://b.alipay.com/support/helperApply.htm?action=consultationApply),提交申請集成協助,咱們會有專業的技術工程師主動聯繫您協助解決
 *三、支付寶論壇( http://club.alipay.com/read-htm-tid-8681712.html
 *若是不想使用擴展功能請把擴展功能參數賦空值。
 **********************************************
 */
%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="cn.com.atobo.vyanke.alipay.config.*"%>
<%@ page import="cn.com.atobo.vyanke.alipay.util.*"%>
<%@ page import="java.util.HashMap"%>
<%@ page import="java.util.Map"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>支付寶即時到帳交易接口</title>
    </head>
    <body>
    ${sHtmlText}
    </body>
</html>
notify_url.jsp
<%
/* *
 功能:支付寶服務器異步通知頁面
 版本:3.3
 日期:2012-08-17
 說明:
 如下代碼只是爲了方便商戶測試而提供的樣例代碼,商戶能夠根據本身網站的須要,按照技術文檔編寫,並不是必定要使用該代碼。
 該代碼僅供學習和研究支付寶接口使用,只是提供一個參考。
 
 //***********頁面功能說明***********
 建立該頁面文件時,請留心該頁面文件中無任何HTML代碼及空格。
 該頁面不能在本機電腦測試,請到服務器上作測試。請確保外部能夠訪問該頁面。
 該頁面調試工具請使用寫文本函數logResult,該函數在com.alipay.util文件夾的AlipayNotify.java類文件中
 若是沒有收到該頁面返回的 success 信息,支付寶會在24小時內按必定的時間策略重發通知
 //********************************
 * */
%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="cn.com.atobo.vyanke.alipay.config.*"%>
<%@ page import="cn.com.atobo.vyanke.alipay.util.*"%>
<%
%>
return_url.jsp
<%
/* *
 功能:支付寶頁面跳轉同步通知頁面
 版本:3.2
 日期:2011-03-17
 說明:
 如下代碼只是爲了方便商戶測試而提供的樣例代碼,商戶能夠根據本身網站的須要,按照技術文檔編寫,並不是必定要使用該代碼。
 該代碼僅供學習和研究支付寶接口使用,只是提供一個參考。
 
 //***********頁面功能說明***********
 該頁面可在本機電腦測試
 可放入HTML等美化頁面的代碼、商戶業務邏輯程序代碼
 TRADE_FINISHED(表示交易已經成功結束,並不能再對該交易作後續操做);
 TRADE_SUCCESS(表示交易已經成功結束,能夠對該交易作後續操做,如:分潤、退款等);
 //********************************
 * */
%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="java.util.Map"%>
<%@ page import="cn.com.atobo.vyanke.alipay.config.*"%>
<%@ page import="cn.com.atobo.vyanke.alipay.util.*"%>
<html>
  <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>支付寶頁面跳轉同步通知頁面</title>
  </head>
  <body>
    ${msg}
  </body>
</html>
pay_success.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri=" http://java.sun.com/jsp/jstl/core"%>
 
<c:set value="${platformType}" var="f"></c:set>
<c:set value="${pageContext.request.contextPath}" var="p"></c:set>
 
<link rel="stylesheet" type="text/css" href="${p}/vyanke/css/main.css?1.07" />
<c:if test="${f==2}">
<jsp:include page="${p}/qua/layout/tcertHeader.jsp"></jsp:include>
</c:if>
<c:if test="${f==1}">
<jsp:include page="${p}/vyike/layout/header.jsp"></jsp:include>
</c:if>
<c:if test="${f==0}">
<jsp:include page="${p}/vyanke/layout/newHeader.jsp"></jsp:include>
</c:if>
 
 
<div class="container shop-success">  
   <div class="border-box"> 
       <div class="border-head">
          <h1 class="pic">
             <span>支付成功!</span>
          </h1>
          <p>共計支付金額<span class="col-red"><em>¥</em>${total_fee }</span>元</p>
       </div>
       <div class="border-txt">
          <p class="col">如下1個訂單已經支付成功&nbsp;&nbsp;共計<span class="col-gre">¥${total_fee }</span>元</p>
          <p>訂單號:<span class="col-red">${order_no }</span>&nbsp;&nbsp;&nbsp;&nbsp;在線支付:¥${total_fee }元</p>
       </div>
       <div class="border-but">
          <c:if test="${f==2}">
            <a href="javascript:void(0);" onclick="doSearchCourseList('0010300101001',${f});" class="red-but">繼續購買</a>
          </c:if>
          <c:if test="${f==0}">
               <a href="javascript:void(0);" onclick="doSearchCourseList('0',${f});" class="red-but">繼續購買</a>
          </c:if>
          <a href="/vkeplus/mycourse-${f}.html""  class="red-a">進入"個人課程">></a>
       </div>
   </div>
</div>
 
 <c:if test="${f==2}">
<jsp:include page="${p}/qua/layout/tcertFooter.jsp"></jsp:include>
</c:if>
<c:if test="${f==1}">
    <jsp:include page="${p}/vyike/layout/footer.jsp"></jsp:include>
</c:if>
<c:if test="${f==0}">
 <jsp:include page="${p}/vyanke/layout/newFooter.jsp"></jsp:include>       
</c:if>
相關文章
相關標籤/搜索