微信支付開發(只針對公衆號裏的h5支付JSAPI)

微信支付後臺:

https://pay.weixin.qq.com

只有這裏設置了,程序中才能使用這個key

 /**
     * 微信支付統一下單接口
     *
     * @param userOrder 訂單信息
     * @return
     * @throws Exception
     */
    public WebResult weixinPay(UserOrder userOrder, String payType, String ip) throws Exception {
        System.out.println("請求參數如下:");
        System.out.println("訂單信息:"+userOrder.toString());
        System.out.println("支付方式payType:"+payType);
        System.out.println("-----------------------傳遞來的真實ip:------------" + ip);
        // 賬號信息
        String appId = Configure.getAppid();
        // 商業號
        String mchId = Configure.getMchid();
        // key
        String key = Configure.getKey();
        // 隨機字符串
        String currTime = PayCommonUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = PayCommonUtil.buildRandom(4) + "";
        String nonceStr = strTime + strRandom;
        // 商品名稱
        String body = "LOVZVZU-商城";//這裏非常重要,騰訊有格式要求
        // 價格 注意:價格的單位是分
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);



        //多比子訂單
        Double totalprice = 0d;
        List<UserOrder> userOrders = orderService.select(1, 1,
        null, null, null,
        null, null, null,
                userOrder.getOrderno(), null);
        for (int i = 0; i < userOrders.size(); i++) {
            UserOrder userOrder1 = userOrders.get(i);
             totalprice += userOrder1.getPrice();
        }
        System.out.println("訂單總額度:"+totalprice);

        List<AdminUser> userByWxid = adminUserService.findUserByWxid(userOrder.getCustomeropenid());
        if (userByWxid != null&&userByWxid.size()>0) {
            AdminUser adminUser = userByWxid.get(0);
            Double balance = adminUser.getBalance();
            System.out.println("用戶餘額:"+balance);
            if (balance>=totalprice){
                totalprice = 0d;
            }else {
                totalprice = totalprice - balance;
            }
        }
        System.out.println("最後需要支付額度:"+totalprice);
        /**
         *  1、交易金額
         *         交易金額默認爲人民幣交易,接口中參數支付金額單位爲【分】,參數值不能帶小數。對賬單中的交易金額單位爲【元】。
         *
         *         外幣交易的支付金額精確到幣種的最小單位,參數值不能帶小數點。
          */

        String orderPrice = nf.format(totalprice.doubleValue()*100);

        // 查詢訂單數據表獲取訂單信息
        // 回調接口
        String notify_url = "http://xxxxxx/payWeixin/weixinNotify";
        String time_start = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.DATE, 1);
        String time_expire = new SimpleDateFormat("yyyyMMddHHmmss").format(ca.getTime());

        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
                                packageParams.put("appid", appId);
                                packageParams.put("mch_id", mchId);
                                packageParams.put("nonce_str", nonceStr);
                                packageParams.put("body", body);
                                packageParams.put("out_trade_no", userOrder.getOrderno());
                                packageParams.put("total_fee", orderPrice);
                                packageParams.put("spbill_create_ip", ip);
                                packageParams.put("notify_url", notify_url);
                                packageParams.put("time_start", time_start);
                                packageParams.put("time_expire", time_expire);
        if (Configure.PAY_TYPE_SCAN.equals(payType)) {// 掃碼支付
            System.out.println("111111111111111掃碼支付");
            packageParams.put("trade_type", "NATIVE");
        } else if (Configure.PAY_TYPE_H5.equals(payType)) {// h5支付
            System.out.println("2222222222222222----h5支付");
            packageParams.put("trade_type", "MWEB");
            packageParams.put("scene_info", "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"https://www.roseonly.com\",\"wap_name\": \"roseonly一生只送一人\"}}");
        } else if (Configure.PAY_TYPE_WX.equals(payType)) {// 公衆號支付
            System.out.println("3333333333333333公衆號支付");
            packageParams.put("trade_type", "JSAPI");
            packageParams.put("openid", userOrder.getCustomeropenid());
//            UserLogin user = userLoginService.get(userOrders.getUserid().longValue());
//            if (user != null) {
//                if (user.getWeixinId() != null) {
//                    packageParams.put("openid", user.getWeixinId());
//                }
//            }
        }
        String sign = PayCommonUtil.createSign("UTF-8", packageParams, key);
        packageParams.put("sign", sign);

        String requestXML = PayCommonUtil.getRequestXml(packageParams);
        System.out.println("請求xml::::" + requestXML);
        String resXml = HttpUtil.postData(Configure.UNIFIED_ORDER_URL, requestXML);
        System.out.println("返回xml::::" + resXml);
        Map<String, String> map = XMLUtil.doXMLParse(resXml);


//        if (Configure.PAY_TYPE_SCAN.equals(payType)) {
//            String urlCode = map.get("code_url");
//            System.out.println("打印掃碼支付返回信息:::::" + urlCode);
//            return urlCode;
//        } else if (Configure.PAY_TYPE_H5.equals(payType)) {
//            String mweb_url = map.get("mweb_url");
//            System.out.println("打印h5支付返回信息 :::::" + mweb_url);
//            return mweb_url;
//        } else
            if (Configure.PAY_TYPE_WX.equals(payType)) {

            map.get("return_code").equals("return_code");

            String timeStamp = getTimeStamp();
            String packageValue = "prepay_id=" + map.get("prepay_id");
            JsAPIPayMsg payMsg = new JsAPIPayMsg();
                        payMsg.setAppId(appId);
                        payMsg.setTimeStamp(timeStamp);
                        payMsg.setNonceStr(map.get("nonce_str"));
                        payMsg.setPackageValue(packageValue);
                        payMsg.setSignType(Configure.PAY_SIGN_TYPE);

            //獲取簽名
            SortedMap<Object, Object> perpayParams = new TreeMap<Object, Object>();
                                        perpayParams.put("appId",       payMsg.getAppId());
                                        perpayParams.put("timeStamp",   payMsg.getTimeStamp());
                                        perpayParams.put("nonceStr",    payMsg.getNonceStr());
                                        perpayParams.put("package",     payMsg.getPackageValue());
                                        perpayParams.put("signType",    payMsg.getSignType());
            String paySign = PayCommonUtil.createSign("UTF-8", perpayParams, key);
            payMsg.setPaySign(paySign);

            String jsonString = JSON.toJSONString(payMsg);



            WebResult webResult = new WebResult();
            String return_code = map.get("return_code");
            if (return_code.toUpperCase().equals("FAIL")){
                String return_msg = map.get("return_msg");
                webResult = new WebResult(2,"失敗",return_msg);
            }else{
                webResult = new WebResult(1,"成功",payMsg);
            }
//            return webResult.toString();



            System.out.println("打印公衆號支付返回信息 :::::" + webResult.toString());
            return webResult;
        } else {
            return null;
        }
    }

下面是一個示例:

請求xml::::

{
    "appid":"wxsdsdfsfs",
    "body":"ZU-商城",
    "mch_id":"sdsdfsdf",
    "nonce_str":"2148063991",
    "notify_url":"http://xxxxxxxx/payWeixin/weixinNotify",
    "openid":"o_XBZ6AS9TzzJ19odkw310UHXNyY",
    "out_trade_no":"201905162148060001",
    "sign":"ECAD32EDBBCB0F69482CC85818093262",
    "spbill_create_ip":"101.30.55.30",
    "time_expire":"20190517214806",
    "time_start":"20190516214806",
    "total_fee":"10",
    "trade_type":"JSAPI"

返回xml::::

{
    "return_code":"SUCCESS",
    "return_msg":"OK",
    "appid":"wx39sdsdsdfdsf8",
    "mch_id":"15sdfsdfs521",
    "nonce_str":"pz8rjFwzwP3SmIAu",
    "sign":"F9E748398DE5AD4E64FADB5B38988028",
    "result_code":"SUCCESS",
    "prepay_id":"wx16214807119260b53874258e3836952547",
    "trade_type":"JSAPI"
}

 

 /**
     * 微信支付回調方法
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void weixin_notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("++++++++++微信支付回調+++++++++++++");
        // 讀取參數
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        inputStream = request.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());

        // 過濾空 設置 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);
        }

        // 賬號信息
        String key = Configure.getKey(); // key
        String out_trade_no = (String) packageParams.get("out_trade_no");
        // logger.info(packageParams);
        // 判斷簽名是否正確
        if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {
            // 處理業務開始
            String resXml = "";
            if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                System.out.println("回調:支付成功");
                System.out.println(" 返回參數如下:");
                String mch_id = (String) packageParams.get("mch_id");
                String openid = (String) packageParams.get("openid");
                String is_subscribe = (String) packageParams.get("is_subscribe");

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

                System.out.println("mch_id:" + mch_id);
                System.out.println("openid:" + openid);
                System.out.println("is_subscribe:" + is_subscribe);
                System.out.println("out_trade_no:" + out_trade_no);
                System.out.println("total_fee:" + total_fee);
                System.out.println("bank_type:" + bank_type);
                System.out.println("transaction_id:" + transaction_id);

                // ////////執行自己的業務邏輯////////////////
//                UserOrder userOrder = this.orderService.selectById(Integer.parseInt(out_trade_no));
                System.out.println("///////執行自己的業務邏輯//////////");
                List<UserOrder> userOrders = orderService.select(1, 100,
                        null, null, null,
                        null, null,
                        null, out_trade_no, null);
                Double totalprice = 0d;
                Boolean canpay = true;
                String customeropenid = null;

                if (userOrders != null && userOrders.size() > 0) {
                    for (int i = 0; i < userOrders.size(); i++) {
                        UserOrder userOrder = userOrders.get(i);
                        if (userOrder.getCustomeropenid()!=null&&!userOrder.getCustomeropenid().equals("")){
                            customeropenid = userOrder.getCustomeropenid();
                        }
                        totalprice += userOrder.getPrice();
                        //狀態檢查
//                        if (!userOrder.getStatus().equals(UserOrder.STATUS_WAITFORPAY)) {
//                            canpay = false;
//                        }
                    }


                    List<AdminUser> userByWxid = adminUserService.findUserByWxid(customeropenid);
                    if (userByWxid != null&&userByWxid.size()>0) {
                        AdminUser adminUser = userByWxid.get(0);
                        Double balance = adminUser.getBalance();
                        if (balance>=totalprice){
                            totalprice = 0d;
                        }else {
                            totalprice = totalprice - balance;
                        }
                    }



                    if (canpay) {// 說明還沒被處理過orderPrice
                        System.out.println("訂單都處於待支付狀態,可正常支付");

                        //我這裏的業務,應該是多個單加在一起
                        double orderPrice = totalprice;

                        double wxPayPrice = Double.parseDouble(total_fee) / 100;//獲取支付金額

                        System.out.println("該訂單應支付:"+orderPrice+"    用戶微信支付:"+wxPayPrice);
                        if (wxPayPrice == orderPrice) {
                            System.out.println("微信同步通知交易金額驗證通過- 訂單號:" + out_trade_no + " 訂單價:" + orderPrice + "微信返回支付:" + total_fee);
//                            payAlipayService.pay(out_trade_no, openid, transaction_id, request, "10");
                            //自己的業務邏輯
                            for (int i = 0; i < userOrders.size(); i++) {
                                UserOrder userOrder = userOrders.get(i);

                                OrderController orderController = new OrderController();
                                boolean b = orderController.payOrderCallback(userOrder);
                                if (!b) {
                                    System.out.println("訂單回調業務出錯,下面是訂單信息");
                                    System.out.println(userOrder.toString());
                                }
                            }


                            resXml = "<xml>"
                                    + "<return_code><![CDATA[SUCCESS]]></return_code>"
                                    + "<return_msg><![CDATA[支付成功]]></return_msg>"
                                    + "</xml> ";
                        } else {
                            System.out.println("微信同步通知交易金額不一致-- 訂單號:" + out_trade_no + " 訂單價:" + orderPrice + "微信返回支付:" + total_fee);


                            resXml = "<xml>"
                                    + "<return_code><![CDATA[FAIL]]></return_code>"
                                    + "<return_msg><![CDATA[金額不一致]]></return_msg>"
                                    + "</xml> ";
                        }
                    } else {
                        System.out.println("微信同步通知處理結果-訂單狀態已經被更改" + out_trade_no);
                        resXml = "<xml>"
                                + "<return_code><![CDATA[FAIL]]></return_code>"
                                + "<return_msg><![CDATA[狀態已更改]]></return_msg>"
                                + "</xml> ";
                    }
                } else {
                    System.out.println("微信同步通知該訂單號不存在-" + out_trade_no);
                    resXml = "<xml>"
                            + "<return_code><![CDATA[FAIL]]></return_code>"
                            + "<return_msg><![CDATA[訂單號不存在]]></return_msg>"
                            + "</xml> ";
                }
            } else {
                System.out.println("支付失敗,錯誤信息:" + packageParams.get("err_code") + "-----訂單號:::" + out_trade_no
                        + "*******支付失敗時間::::" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

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

                resXml = "<xml>"
                        + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[" + err_code
                        + "]]></return_msg>" + "</xml> ";

            }
            // 處理業務完畢
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } else {
            System.out.println("通知簽名驗證失敗---時間::::" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }
    }

 

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