Java支付宝接口

JrmfjRmf 2016-05-17

转载:http://programer-wf.iteye.com/blog/682694

网上关于Java支付宝接口的文章很多,都大同小异,但是具体到代码中,还是不太一样,对于以前没有调试的新手来说还是很费解的,这是通过调试认为比较有用的版本,贴在这里供大家参考。 


1、从本站提交到支付宝: 

/** 
     * 将订单提交支付宝进行网上支付 
     */ 
    public ActionForward submitAlipayUrl(ActionMapping mapping, 
            ActionForm form, HttpServletRequest request, 
            HttpServletResponse response) throws Exception { 
        String orderNo = request.getParameter("orderNo");//订单编号 
        HashMap hm = new HashMap(); 
        hm.put("_input_charset", "utf-8");// 采用相同的编码方式 
        hm.put("body", "企鹅个性化图书订单,订单号:" + orderNo);// 填写在跳到支付宝页面上显示的付款内容信息 
        hm.put("notify_url", "http://127.0.0.1:8888/mypenguin/orders.do?method=AlipayNotify");// 客户付款后,支付宝调用的页面 
        hm.put("out_trade_no", orderNo);// 外部交易号,最好具有唯一性,在获取支付宝发来的付款信息时使用. 
        hm.put("partner", "2088002302055380");// partnerId(合作伙伴ID) 
        //hm.put("agent", "2088002302055380");// partnerId(合作伙伴ID) 
        hm.put("payment_type", "1");// 支付类型 1=商品购买,2=服务购买,... 
        //hm.put("price", "178.00");// 订单金额信息 
        hm.put("total_fee", "178.00");// 订单金额和信息 
        //hm.put("quantity", "1");// 订单商品数量,一般都是写1,它是按照整个订单包来计算 
        hm.put("return_url", "http://127.0.0.1:8888/mypenguin/orders.do?method=AlipayReturn");// 客户付款成功后,显示给客户的页面 
        hm.put("show_url", "http://127.0.0.1:8888/mypenguin/books.do?method=list&kindId=1");//展示地址,即在支付页面时,商品名称旁边的“详情”的链接地址。 
        hm.put("seller_email", "[email protected]");// 你的支付宝账户email 
        hm.put("service", "create_direct_pay_by_user");// create_direct_pay_by_user=直接付款,trade_create_by_buyer=担保付款 
        hm.put("subject", "企鹅个性化图书订单号:" + orderNo);// 填写在跳到支付宝页面上显示的付款标题信息 
        String payGateway = "https://www.alipay.com/cooperate/gateway.do";// 跳转到支付宝的url头 
        String securityCode="7nj9sczcnfc4n8366j46mrzsbqjksmzn";//securityCode(安全码); 
        String sign = makeUrl(hm,securityCode,"utf-8",payGateway);//securityCode(安全码); 
        hm.put("sign", sign); 
        hm.put("sign_type", "MD5"); 
        PrintWriter out = response.getWriter(); 

        out.println("<form name='alipaysubmit' method='post'  action='https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8' >"); 
        out.println("<input type='hidden' name='service' value='" + hm.get("service") + "'>"); 
        out.println("<input type='hidden' name='partner' value='" + hm.get("partner") + "'>"); 
        out.println("<input type='hidden' name='seller_email' value='" + hm.get("seller_email") + "'>"); 
        out.println("<input type='hidden' name='out_trade_no' value='" + hm.get("out_trade_no") + "'>"); 
        out.println("<input type='hidden' name='subject' value='" + hm.get("subject") + "'>"); 
        out.println("<input type='hidden' name='body' value='" + hm.get("body") + "'>"); 
        out.println("<input type='hidden' name='total_fee' value='" + hm.get("total_fee") + "'>"); 
        out.println("<input type='hidden' name='show_url' value='" + hm.get("show_url") + "'>"); 
        out.println("<input type='hidden' name='return_url' value='" + hm.get("return_url") + "'>"); 
        out.println("<input type='hidden' name='notify_url' value='" + hm.get("notify_url") + "'>"); 
        out.println("<input type='hidden' name='payment_type' value='1'>"); 
        out.println("<input type='hidden' name='sign' value='" + hm.get("sign") + "'>"); 
        out.println("<input type='hidden' name='sign_type' value='" + hm.get("sign_type") + "'>"); 
        out.println("</form>"); 
        out.println("<script>"); 
        out.println("  document.alipaysubmit.submit()"); 
        out.println("</script>"); 
        return null; 
    } 

/** 
          * 根据传入的参数生成Alipay的支付URL 
          * @param hm 参数值 
          * @param securityCode 安全码 
          * @param charset 编码 
          * @param payGateway 支付宝gateway 
          * @return 
          */  
         public static String makeUrl(HashMap hm,String securityCode,String charSet,String payGateway) throws Exception{  
             List keys = new ArrayList(hm.keySet());  
             Collections.sort(keys);//支付宝要求参数必须按字母排序  
             StringBuffer content = new StringBuffer();  
             for (int i = 0; i < keys.size(); i++) {  
                 content.append((String) keys.get(i));  
                 content.append("=");  
                 content.append((String) hm.get((String) keys.get(i)));  
                 if (i != keys.size() - 1) {  
                     content.append("&");  
                 }  
             } 
             content.append(securityCode);    
             String sign = DataUtil.MD5Encode(content.toString(), charSet);  //MD5加密 
             return sign;  
         } 

2、return_url的内容: 
/** 
     * 支付宝支付完成以后,当前窗口会从支付宝的页面跳转回这个页面。该页面称作“返回页”, 
     * 是同步被支付宝服务器所调用,可当作是支付完成后的提示信息页,如“您的某某某订单,多少金额已支付成功”。 
     */ 
    public ActionForward AlipayReturn(ActionMapping mapping, 
            ActionForm form, HttpServletRequest request, 
            HttpServletResponse response) throws Exception { 
        String alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify"; 
        //String alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";//此路径是在上面链接地址无法起作用时替换使用。 
        alipayNotifyURL = alipayNotifyURL+ "&partner=2088002302055380&notify_id="+ request.getParameter("notify_id"); 
     // 获取支付宝ATN返回结果,true是正确的订单信息,false 是无效的 
        String responseTxt = check(alipayNotifyURL); 
        // 获得POST 过来参数设置到新的requestParams中 
        Map requestParams = request.getParameterMap(); 
        List keys = new ArrayList(requestParams.keySet()); 
        Collections.sort(keys); 
        StringBuffer content = new StringBuffer();  
        for (int i = 0; i < keys.size(); i++) { 
            String key=(String) keys.get(i); 
            if(!key.equals("")&&!key.equals("sign")&&!key.equals("sign_type")){ 
                content.append((String) keys.get(i));  
                content.append("=");  
                content.append((String)requestParams.get((String) keys.get(i)));  
                if (i != keys.size() - 1) {  
                    content.append("&");  
                } 
            } 
        } 
        String securityCode="7nj9sczcnfc4n8366j46mrzsbqjksmzn";//securityCode(安全码); 
        content.append(securityCode);  
        String mysign = DataUtil.MD5Encode(content.toString(), "utf-8");  
        System.out.println("--------------------------content="+content); 
        System.out.println("--------------------------mysign="+mysign); 
        System.out.println("--------------------------sign="+request.getParameter("sign")); 
          if (mysign.equals(request.getParameter("sign")) && responseTxt.equals("true") ){  
                 if (request.getParameter("trade_status").equalsIgnoreCase("TRADE_FINISHED")){ 
         // 可以做重定向,也可以用来虚拟物品发货 
                 } 
                 return mapping.findForward("payOK");//交易成功 
          }else{ 
              return mapping.findForward("payFail");//交易失败 
          } 
    } 

3、notify_url的内容: 
/** 
     * 通知返回URL,仅适用于异步返回处理结果的接口。有些服务是无法立即返回处理结果的,那么需要通过这个URL将处理结果异步返回给合作伙伴 
     */ 
    public ActionForward AlipayNotify(ActionMapping mapping, 
            ActionForm form, HttpServletRequest request, 
            HttpServletResponse response) throws Exception { 
        String alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?service=notify_verify"; 
        //String alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";//此路径是在上面链接地址无法起作用时替换使用。 
        alipayNotifyURL = alipayNotifyURL+ "&partner=2088002302055380&notify_id="+ request.getParameter("notify_id"); 
     // 获取支付宝ATN返回结果,true是正确的订单信息,false 是无效的 
        String responseTxt = check(alipayNotifyURL); 
        // 获得POST 过来参数设置到新的requestParams中 
        Map requestParams = request.getParameterMap(); 
        List keys = new ArrayList(requestParams.keySet()); 
        Collections.sort(keys); 
        StringBuffer content = new StringBuffer();  
        for (int i = 0; i < keys.size(); i++) { 
            String key=(String) keys.get(i); 
            if(!key.equals("")&&!key.equals("sign")&&!key.equals("sign_type")){ 
                content.append((String) keys.get(i));  
                content.append("=");  
                content.append((String)requestParams.get((String) keys.get(i)));  
                if (i != keys.size() - 1) {  
                    content.append("&");  
                } 
            } 
        } 
        String securityCode="7nj9sczcnfc4n8366j46mrzsbqjksmzn";//securityCode(安全码); 
        content.append(securityCode);  
        String mysign = DataUtil.MD5Encode(content.toString(), "utf-8");  
        System.out.println("--------------------------content="+content); 
        System.out.println("--------------------------mysign="+mysign); 
        System.out.println("--------------------------sign="+request.getParameter("sign")); 
          if (mysign.equals(request.getParameter("sign")) && responseTxt.equals("true") ){  
                 if (request.getParameter("trade_status").equalsIgnoreCase("TRADE_FINISHED")){ 
                     // 可以做重定向,也可以用来虚拟物品发货 
                 } 
                 return mapping.findForward("payOK"); 
          }else{ 
              return mapping.findForward("payFail"); 
          } 
    } 

/** 
  * @param myUrl 
     * 
     * @param url 
     * 
     * @return 获取url内容 
     */ 
  public static String check(String urlvalue ) { 

   String inputLine = ""; 
  try 
  { 
   URL url = new URL(urlvalue); 
   
   HttpURLConnection urlConnection  = (HttpURLConnection)url.openConnection(); 
   
   BufferedReader in  = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
  
   String stTemp = ""; 
         while((stTemp = in.readLine()) != null) 
         { 
            System.out.println(stTemp); 
            inputLine = inputLine + stTemp; 
         } 
  } 
  catch(Exception e) 
  { 
   e.printStackTrace(); 
  } 
  return inputLine; 
 

相关推荐

迷彩 / 0评论 2020-01-14