微信扫码支付 java版

最近做一个PC端网上商城,需要微信扫码支付,几经摸索,终于搞出来了,现将代码贴下,以供参考!

1.扫码支付演示
微信扫码支付 java版_第1张图片
微信扫码支付 java版_第2张图片
看起来很简单,其实实现起来也不难,soEasy!
2.将生成二维码的js导入到项目
jquery.qrcode.min.js
3.在后台建一个微信参数配置
微信扫码支付 java版_第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 packageParams = new TreeMap(); 
                             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 ecProductList = new ArrayList();
                                 List groupList = microShopService.findAllByEntityClassAndAttribute(EcOrderItemGroup.class, "ecOrder.id", order.getId());
                                 if(null != groupList && groupList.size() > 0){
                                     for (EcOrderItemGroup group : groupList) {
                                         List 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 m = new HashMap();
    m = XMLUtil.doXMLParse(sb.toString());
    System.out.println(m+"------------------------");
    //过滤空 设置 TreeMap
    SortedMap packageParams = new TreeMap();      
    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 = "" + ""
                        + "" + " ";
         }
        //------------------------------
        //处理业务完毕
        //------------------------------
        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 packageParams = new TreeMap();  
                         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 微信支付页面
微信扫码支付 java版_第4张图片
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
以上就是微信扫码支付的全部代码,我也该休息会了

你可能感兴趣的:(电商网站)