Java實現WEB端支付寶,電腦/手機雙端支付

思路:先判斷設備是手機還是電腦

orderForm爲自習封裝的訂單對象

boolean phone = CheckMobile.isPhone(req.getHeader("USER-AGENT"));
if (phone) {
	wapPay(req, resp, orderForm); // 手機付款
} else {
	tradePayment(req, resp, orderForm); // pc付款
}

貼上CheckMobile類

import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  /**
   * 
   * @author 網絡
   * @info 本類用於是否是移動設備訪問
   */
public class CheckMobile {  
       
    // \b 是單詞邊界(連着的兩個(字母字符 與 非字母字符) 之間的邏輯上的間隔),    
    // 字符串在編譯時會被轉碼一次,所以是 "\\b"    
    // \B 是單詞內部邏輯間隔(連着的兩個字母字符之間的邏輯上的間隔)    
    static String phoneReg = "\\bNokia|SAMSUNG|MIDP-2|CLDC1.1|SymbianOS|MAUI|UNTRUSTED/1.0"  
    +"|Windows CE|iPhone|iPad|Android|BlackBerry|UCWEB|ucweb|BREW|J2ME|YULONG|YuLong|COOLPAD|TIANYU|TY-"  
    +"|K-Touch|Haier|DOPOD|Lenovo|LENOVO|HUAQIN|AIGO-|CTC/1.0"  
    +"|CTC/2.0|CMCC|DAXIAN|MOT-|SonyEricsson|GIONEE|HTC|ZTE|HUAWEI|webOS|GoBrowser|IEMobile|WAP2.0\\b";    
    static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"   
            +"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";    
       
    //移動設備正則匹配:手機端、平板  
    static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);    
    static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);    
         
    /** 
     * 檢測是否是移動設備訪問 
     *  
     * @Title: isPhone 
     * @Date : 2018-7-7 下午01:29:07 
     * @param userAgent 瀏覽器標識 
     * @return true:移動設備接入,false:pc端接入 
     */  
    public static boolean isPhone(String userAgent){    
        if(null == userAgent){    
            userAgent = "";    
        }    
        // 匹配    
        Matcher matcherPhone = phonePat.matcher(userAgent);    
        Matcher matcherTable = tablePat.matcher(userAgent);    
        if(matcherPhone.find() || matcherTable.find()){    
            return true;    
        } else {    
            return false;    
        }    
    }  
}

手機付款(在手機端會有支付寶會自動打開支付寶)

// **手機支付寶付款----------------------------------------------------------
	public void wapPay(HttpServletRequest request, HttpServletResponse response,OrderForm orderForm) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		// 訂單號
		//String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
		
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				PaymentConfig.APP_ID, PaymentConfig.MERCHANT_PRIVATE_KEY, "json", "utf-8",
				PaymentConfig.ALIPAY_PUBLIC_KEY, "RSA2"); // 獲得初始化的AlipayClient
		AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();// 創建API對應的request
		alipayRequest.setReturnUrl("http://xxx/alipay?command=returnUrl");
		alipayRequest.setNotifyUrl("http://xxx/alipay?command=notifyUrl");// 在公共參數中設置回跳和通知地址
		alipayRequest.setBizContent("{" + " \"out_trade_no\":\"" + orderForm.getoTradeNo() + "\"," + " \"total_amount\":\"" + orderForm.getoPrice() + "\","
				+ " \"subject\":\"美食訂單\"," + " \"product_code\":\"QUICK_WAP_PAY\"" + " }");// 填充業務參數
		String form = "";
		try {
			form = alipayClient.pageExecute(alipayRequest).getBody(); // 調用SDK生成表單
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(form);// 直接將完整的表單html輸出到頁面
		response.getWriter().flush();
		response.getWriter().close();
	}

pc端支付,(這裏經過大量封裝,僅供參考,請自行斟酌)

public void tradePayment(HttpServletRequest request, HttpServletResponse response,OrderForm orderForm) throws IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		AlipayService alipayService = new AlipayServiceImpl();
		AliPayMent aliPayMent = new AliPayMent();

		// 商戶訂單號
		aliPayMent.setOutTradeNo(orderForm.getoTradeNo());
		// 付款金額
		aliPayMent.setTotalAmount(orderForm.getoPrice()+"");
		// 訂單名稱 aliPayMent.setSubject();
		aliPayMent.setSubject("美食訂單");
		// 商品描述
		aliPayMent.setBody("zxcxz");
		String result = alipayService.tradePayment(aliPayMent);
		// System.out.println(result);
		PrintWriter out = response.getWriter();
		response.setContentType("text/html;charset=UTF-8");
		out.write(result);
		out.flush();
		out.close();
	}

支付回調請參考官方文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章