天天看點

2021-7-10 微信退款java實作

接着上一篇微信H5支付後來。

@ResponseBody
    @GetMapping("refund")
    public String Refund(@RequestParam("orderId")String orderId,@RequestParam("refundId")String refundId) throws Exception {
            Integer total_fee = 1;   //付款金額
            Integer refund_fee = 1;  //退款的金額
            SortedMap<String,String> map = new TreeMap<>();
            String appid = weChatConfig.appid;
            String mch_id = weChatConfig.merId;
            String nonce_str =CommonUtils.generateUUID();
            String out_refund_no = refundId;//UtilUuId.get18UUID();
            map.put("appid", appid);
            map.put("mch_id", mch_id);
            map.put("nonce_str", nonce_str);
            map.put("sign_type", "MD5");
          //  map.put("transaction_id", ""); //微信支付單号 和 商家訂單号 2選一
            map.put("out_trade_no",orderId );
            map.put("out_refund_no",out_refund_no);
            map.put("total_fee", total_fee.toString());
            map.put("refund_fee", refund_fee.toString());
            String sign = WXPayUtil.createSign(map, weChatConfig.key);
            map.put("sign",sign);

            String xml = WXPayUtil.mapToXml(map);
            log.info("payXml: "+xml);
            String createOrderURL = "https://api.mch.weixin.qq.com/secapi/pay/refund";//微信統一下單接口
            try {
                //預下單 擷取接口位址
                Map map1 = weChatPayService.doRefund(mch_id,createOrderURL, xml);//注意了退款.p12證書在這裡面配置,官方文檔沒有怎麼詳細說明,是以很多同學很頭大。
                String return_code = (String) map1.get("return_code");
                String return_msg = (String) map1.get("return_msg");
                System.out.println(return_msg);
                if ("SUCCESS".equals(return_code) && "OK".equals(return_msg)) {
                    return "ok";//JsonResult.ok("success").put("out_refund_no", out_refund_no);
                } else {
                    return "---------統一退單接口出錯";//JsonResult.error("統一退單接口出錯");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "統一退單接口出錯";//JsonResult.error("統一退單接口出錯");
            }

    }
           
/**
     *
     * @param mchId 商戶ID
     * @param url 請求URL
     * @param data 退款參數
     * @return
     * @throws Exception
     */
    public  Map doRefund(String mchId, String url, String data) throws Exception {
        /**
         * 注意PKCS12證書 是從微信商戶平台-》賬戶設定-》 API安全 中下載下傳的
         */
        KeyStore keyStore = KeyStore.getInstance("PKCS12");//證書格式
        //這裡自行實作我是使用資料庫配置将證書上傳到了伺服器可以使用 FileInputStream讀取本地檔案
        FileInputStream fis=new FileInputStream("E:\\WXCertUtil\\cert\\apiclient_cert.p12");
        try {
            //這裡寫密碼..預設是你的MCHID
            keyStore.load(fis, mchId.toCharArray());
        } finally {
            fis.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadKeyMaterial(keyStore, mchId.toCharArray())
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .build();
        try {
            HttpPost httpost = new HttpPost(url);
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            System.out.println("---------------------------------------------------");
            try {
                HttpEntity entity = response.getEntity();
                //接受到傳回資訊
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                System.out.println(jsonStr);
                Map<String, String> map =  WXPayUtil.xmlToMap(jsonStr);
                return map;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }