1. 程式人生 > >微信掃碼支付 java版

微信掃碼支付 java版

最近做一個PC端網上商城,需要微信掃碼支付,幾經摸索,終於搞出來了,現將程式碼貼下,以供參考!

1.掃碼支付演示
這裡寫圖片描述
這裡寫圖片描述
看起來很簡單,其實實現起來也不難,soEasy!
2.將生成二維碼的js匯入到專案
jquery.qrcode.min.js
3.在後臺建一個微信引數配置
這裡寫圖片描述
支付連結: http://www.xxxxxx.com/mobile/ec/pay/tp006MobileEcPaymentAction_payNotify.action
4.程式碼實現
4.1*微支付實體類*WxPayConfig*
public class WxPayConfig extends BaseEntity {

private static final long serialVersionUID = 1L;

/** appid */
private String appId;
/** 商戶號 */
private String mchId;
/** 訂單名稱 */
private String body;
/** 裝置資訊 */
private String deviceInfo;
/** 交易型別 */
private String tradeType;
/** 支付連結 */
private String notifyUrl;
/** 店鋪伺服器ip */
private String spbillCreateIp;
/** 支付祕鑰 */
private String privateKey;
/** 商戶證書 */
private String securityCertificate;
/** 退款資金來源    
*   REFUND_SOURCE_UNSETTLED_FUNDS---未結算資金退款(預設使用未結算資金退款)
*   REFUND_SOURCE_RECHARGE_FUNDS ---可用餘額退款    
*/
private String refundAccount;

public WxPayConfig(){}

public String getAppId() {
    return appId;
}

public void setAppId(String appId) {
    this.appId = appId;
}

public String getMchId() {
    return mchId;
}

public void setMchId(String mchId) {
    this.mchId = mchId;
}

public String getBody() {
    return body;
}

public void setBody(String body) {
    this.body = body;
}

public String getDeviceInfo() {
    return deviceInfo;
}

public void setDeviceInfo(String deviceInfo) {
    this.deviceInfo = deviceInfo;
}

public String getTradeType() {
    return tradeType;
}

public void setTradeType(String tradeType) {
    this.tradeType = tradeType;
}

public String getNotifyUrl() {
    return notifyUrl;
}

public void setNotifyUrl(String notifyUrl) {
    this.notifyUrl = notifyUrl;
}

public String getSpbillCreateIp() {
    return spbillCreateIp;
}

public void setSpbillCreateIp(String spbillCreateIp) {
    this.spbillCreateIp = spbillCreateIp;
}

public String getPrivateKey() {
    return privateKey;
}

public void setPrivateKey(String privateKey) {
    this.privateKey = privateKey;
}

public String getSecurityCertificate() {
    return securityCertificate;
}

public void setSecurityCertificate(String securityCertificate) {
    this.securityCertificate = securityCertificate;
}

public String getRefundAccount() {
    return refundAccount;
}

public void setRefundAccount(String refundAccount) {
    this.refundAccount = refundAccount;
}

}
4.2選擇微信支付
這裡寫圖片描述

public String weixinJsPayPrepare(){     
    if(StrUtils.objectIsNotNull(id)){
        try{
            Object cusObj = getSession().getAttribute(CustomerConstant.CUSTOMER);
            if(null != cusObj && cusObj instanceof EcCustomer){
                microShopId = getSessionString(PcMicroShopConstant.MMS_MICROSHOP_ID);
                if(StrUtils.objectIsNull(microShopId)){
                    return "404";
                }
                microShop = microShopService.findEntityById(MicroShop.class, microShopId);
                WxPayConfig wxPayConfig = microShopService.findWxPayConfigByMicroShopId(microShopId);
                if(null == wxPayConfig || StrUtils.objectIsNull(wxPayConfig.getAppId()) || StrUtils.objectIsNull(wxPayConfig.getMchId()) || StrUtils.objectIsNull(wxPayConfig.getPrivateKey())){
                    System.out.println("error:後臺微信支付配置資料不全!");
                }else{
                    /*id = id.replaceAll("\r|\n", "");*/
                    order = microShopService.findEntityById(EcOrder.class, id);
                    if(null != order){
                        Double totalPrice = order.getTotalPrice();
                        if(totalPrice > 0){
                             // 賬號資訊
                             String appId = wxPayConfig.getAppId();
                             //商業號
                             String mch_id = wxPayConfig.getMchId();
                             //支付祕鑰
                             //String key = wxPayConfig.getPrimaryKey();
                             String key = "7db5da60334a97c301323b46e57b1498";
                             String spbill_create_ip = getIpAddr(getRequest());
                             Double order_price = order.getTotalPrice();
                             int price =(int) (order_price *100);
                             String out_trade_no = order.getCode();
                             String nonce_str = getRandomStringByLength(32);
                             /** 設定url 必填,不能修改 */
                             StringBuffer rn_url = getRequest().getRequestURL();  
                             String contextUrl = rn_url.delete(rn_url.length() - getRequest().getRequestURI().length(), rn_url.length()).append(getRequest().getContextPath()).toString(); 
                            //回撥介面 
                             String notify_url = contextUrl +"/pc/ec/pay/tp002PcEcPaymentActiondian!getPayBack.action"; 
                             String trade_type = "NATIVE"; 

                             SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>(); 
                             packageParams.put("appid", appId);  
                             packageParams.put("mch_id", mch_id);  
                             packageParams.put("nonce_str", nonce_str);  
                             packageParams.put("body", "訂單支付");  
                             packageParams.put("out_trade_no", out_trade_no);//訂單號
                             packageParams.put("total_fee", price+"");//支付金額
                             packageParams.put("spbill_create_ip", spbill_create_ip);//發起者ip 
                             packageParams.put("notify_url", notify_url);  
                             packageParams.put("trade_type", trade_type);
                             String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);
                             packageParams.put("sign", sign); 

                             String requestXML = PayCommonUtil.getRequestXml(packageParams);  
                             System.out.println(requestXML);  

                             String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);  
                             System.out.println(resXml);

                             Map map = XMLUtil.doXMLParse(resXml);
                             String urlCode = (String) map.get("code_url");  
                             System.out.println(urlCode);
                             if(StrUtils.objectIsNotNull(urlCode)){
                                 order.setQrCodePath(urlCode);
                                 order.setLastModifyDate(new Date());
                                 order =microShopService.merge(order);
                                 /*商品*/
                                 List<EcShopProduct> ecProductList = new ArrayList<EcShopProduct>();
                                 List<EcOrderItemGroup> groupList = microShopService.findAllByEntityClassAndAttribute(EcOrderItemGroup.class, "ecOrder.id", order.getId());
                                 if(null != groupList && groupList.size() > 0){
                                     for (EcOrderItemGroup group : groupList) {
                                         List<EcOrderItem> orderItems = microShopService.findAllByEntityClassAndAttribute(EcOrderItem.class, "ecOrderItemGroup.id", group.getId());
                                         if(null != orderItems && orderItems.size() > 0){
                                             for (EcOrderItem ecOrderItem : orderItems) {
                                                  EcShopProduct eShopProduct = ecOrderItem.getEcShopProduct();
                                                  ecProductList.add(eShopProduct);
                                            } 
                                         }
                                    }
                                 }
                                 if(null != ecProductList && ecProductList.size() > 0){
                                     getRequest().setAttribute("ecProductList", ecProductList);
                                 }
                             }

                        }
                    }
                }   
            }else{
                return "login";
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    return "weixinPay";
}
/*回撥介面*/
public void getPayBack() throws Exception{

    //讀取引數
    InputStream inputStream ;
    StringBuffer sb = new StringBuffer();
    inputStream = getRequest().getInputStream();
    String s ;
    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    while ((s = in.readLine()) != null){
        sb.append(s);
    }
    in.close();
    inputStream.close();

    //解析xml成map
    Map<String, String> m = new HashMap<String, String>();
    m = XMLUtil.doXMLParse(sb.toString());
    System.out.println(m+"------------------------");
    //過濾空 設定 TreeMap
    SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();      
    Iterator it = m.keySet().iterator();
    while (it.hasNext()) {
        String parameter = (String) it.next();
        String parameterValue = m.get(parameter);

        String v = "";
        if(null != parameterValue) {
            v = parameterValue.trim();
        }
        packageParams.put(parameter, v);
    }
    // 賬號資訊
    WxPayConfig wxPayConfig = microShopService.findWxPayConfigByMicroShopId(microShopId);
    String key = wxPayConfig.getPrimaryKey();

    logger.info(packageParams.toString());
    //判斷簽名是否正確
    if(PayCommonUtil.isTenpaySign("UTF-8", packageParams,key)) {
         //處理業務開始
         String resXml = "";
         String resultStatus = (String) packageParams.get("result_code");
         if("SUCCESS".equals(resultStatus)){
               // 這裡是支付成功
               //////////執行自己的業務邏輯////////////////
               String mch_id = (String)packageParams.get("mch_id");
               String openid = (String)packageParams.get("openid");
               String is_subscribe = (String)packageParams.get("is_subscribe");
               String out_trade_no = (String)packageParams.get("out_trade_no");

               String total_fee = (String)packageParams.get("total_fee");

               logger.info("mch_id:"+mch_id);
               logger.info("openid:"+openid);
               logger.info("is_subscribe:"+is_subscribe);
               logger.info("out_trade_no:"+out_trade_no);
               logger.info("total_fee:"+total_fee);
               //////////執行自己的業務邏輯////////////////

         }else{
             logger.info("支付失敗,錯誤資訊:" + packageParams.get("err_code"));
             System.out.println(packageParams.get("err_code"));
             resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[報文為空]]></return_msg>" + "</xml> ";
         }
        //------------------------------
        //處理業務完畢
        //------------------------------
        BufferedOutputStream out = new BufferedOutputStream(getResponse().getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }else{
        logger.info("通知簽名驗證失敗");
    }
}
/*微信支付處理業務*/
public String checkPay(){
    try {
         microShopId = getSessionString(PcMicroShopConstant.MMS_MICROSHOP_ID);
         WxPayConfig wxPayConfig = microShopService.findWxPayConfigByMicroShopId(microShopId);
         if(null == wxPayConfig || StrUtils.objectIsNull(wxPayConfig.getAppId()) || 
             StrUtils.objectIsNull(wxPayConfig.getMchId()) || 
             StrUtils.objectIsNull(wxPayConfig.getPrivateKey())){
             System.out.println("error:後臺微信支付配置資料不全!");
         }else{
              if(StrUtils.objectIsNotNull(id)){
                  order = microShopService.findEntityById(EcOrder.class, id);
                  if(null != order){
                         String appId = wxPayConfig.getAppId();
                         String mch_id = wxPayConfig.getMchId();
                         String out_trade_no = order.getCode();
                         //String key = wxPayConfig.getPrimaryKey();
                         String key = "7db5da60334a97c301323b46e57b1498";
                         String nonce_str = getRandomStringByLength(32);
                         SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();  
                         packageParams.put("appid", appId);  
                         packageParams.put("mch_id", mch_id);  
                         packageParams.put("nonce_str", nonce_str);  
                         packageParams.put("out_trade_no", out_trade_no); 
                         String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);
                         packageParams.put("sign", sign);
                         String requestXML = PayCommonUtil.getRequestXml(packageParams);
                         String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/orderquery", requestXML);

                         Map map = XMLUtil.doXMLParse(resXml);  
                         String trade_state = (String) map.get("trade_state");

                         if("SUCCESS".equals(trade_state)){
                              EcOrderItemGroup eoig = microShopService.findEntityByAttribute(EcOrderItemGroup.class, "ecOrder.id", id);
                              eoig.setPaymentStatus(PaymentStatusConstant.EO_PS_HASTOPAY);
                              eoig.setDealStatus(DealStatusConstant.EO_DS_HASCONFIRMED);
                              eoig = ecOrderItemGroupService.merge(eoig);
                              setMessage("1:"+"訂單支付狀態更新成功!");
                         }else{
                             setMessage("0:"+"訂單支付失敗!");
                         }
                  }
              } 
         }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return UPDATE;
}
/*獲取隨機字串長度*/
private static String getRandomStringByLength(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
}

4.3 微信支付頁面
這裡寫圖片描述
4.3.1 js相關程式碼

$(function(){
    var str = $("#urlCode").val();
    str = toUtf8(str);

    $("#code").qrcode({
        render: "table",
        width: 300,
        height:300,
        text: str
    });
})
setInterval("checkPay()",1000*1);
function checkPay(){
    var orderId = $("#orderId").val();
    $.ajax({
        url : '${base}/pc/ec/pay/tp002PcEcPaymentAction_checkPay.action',
        cache : false,
        data : {
            "id" : orderId
        },
        success : function(result) {
            var r = result.split(":");
            if(Number(r[0]) > 0){
                /*支付成功跳轉頁面*/
                document.location.href = "${base}/pc/ec/order/tp002PcEcOrderAction_goEcOrderSuccess.action?orderId="+orderId;
            }

        }
    })
}

function toUtf8(str) {   
    var out, i, len, c;   
    out = "";   
    len = str.length;   
    for(i = 0; i < len; i++) {   
        c = str.charCodeAt(i);   
        if ((c >= 0x0001) && (c <= 0x007F)) {   
            out += str.charAt(i);   
        } else if (c > 0x07FF) {   
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));   
            out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));   
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));   
        } else {   
            out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));   
            out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));   
        }   
    }   
    return out;   
}  

注意引入jquery.qrcode.min.js
以上就是微信掃碼支付的全部程式碼,我也該休息會了