溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在Java中使用SSM框架實(shí)現(xiàn)一個(gè)微信退款功能

發(fā)布時(shí)間:2021-04-13 16:51:57 來(lái)源:億速云 閱讀:162 作者:Leah 欄目:編程語(yǔ)言

本篇文章為大家展示了怎么在Java中使用SSM框架實(shí)現(xiàn)一個(gè)微信退款功能,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

String outTradeNo = request.getParameter("outTradeNo");// 獲取商戶訂單號(hào)
 
 Integer totalFee = Integer.parseInt(request.getParameter("totalFee"));// 獲取支付金額
 
 Map<String, String> getMap = new HashMap<String, String>();
 // 獲得當(dāng)前目錄
 String path = request.getSession().getServletContext().getRealPath("/");
 
 Date now = new Date();
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 可以方便地修改日期格式
 String outRefundNo = "NO" + dateFormat.format(now);

提供的參數(shù)有訂單號(hào)這個(gè)是支付成功之后生成的唯一號(hào)碼,然后是獲取到用戶支付的金額這兩個(gè)參數(shù)都是由支付之后的訂單上面獲得的。下面那個(gè)path則是保存微信安全證書(shū)文件的位置,這里提一下要實(shí)現(xiàn)微信退款和微信企業(yè)轉(zhuǎn)賬功能是需要到微信商戶平臺(tái)去下載安全證書(shū)的,然后把證書(shū)放在項(xiàng)目的WEB-INF/目錄下即可。

RefundReqData refundReqData = new RefundReqData();
 refundReqData.setAppid(Configure.getAppID());
 refundReqData.setMch_id(Configure.getMch_id());
 refundReqData.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
 refundReqData.setOut_trade_no(outTradeNo);
 refundReqData.setOut_refund_no(outRefundNo);
 refundReqData.setTotal_fee(totalFee);
 refundReqData.setRefund_fee(refundFee);
 refundReqData.setOp_user_id(Configure.getMch_id());
 refundReqData.setNotify_url("https://weixin.qq.com/notify/");
    String sign = Signature.getSign(refundReqData);// 生成簽名
 refundReqData.setSign(sign);

獲取到需要的參數(shù)之后呢,我在這里使用了一個(gè)退款的實(shí)體類把這些參數(shù)保存到了我的實(shí)體類里面方便后面的簽名加密。

ArrayList<String> list = new ArrayList<String>();
    @SuppressWarnings("rawtypes")
 Class cls = o.getClass();
    Field[] fields = cls.getDeclaredFields();
    for (Field f : fields) {
      f.setAccessible(true);
      if (f.get(o) != null && f.get(o) != "") {
       String name = f.getName();
       XStreamAlias anno = f.getAnnotation(XStreamAlias.class);
       if(anno != null)
       name = anno.value();
        list.add(name + "=" + f.get(o) + "&");
      }
    }
    int size = list.size();
    String [] arrayToSort = list.toArray(new String[size]);
    Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < size; i ++) {
      sb.append(arrayToSort[i]);
    }
    String result = sb.toString();
    result += "key=" + Configure.getKey();
    System.out.println("簽名數(shù)據(jù):"+result);
    result = MD5Util.MD5Encode(result,"utf-8").toUpperCase();
    return result;

這個(gè)是我簽名加密的方法,把數(shù)據(jù)加密之后會(huì)成為一個(gè)很長(zhǎng)的字符串,但是官方提供的退款接口是沒(méi)辦法解析你這個(gè)超長(zhǎng)字符串的數(shù)據(jù)的,所以我們要把這個(gè)字符串變成官方接口認(rèn)識(shí)的數(shù)據(jù)格式也就是xml格式。

private static XStream xstream = new XStream(new XppDriver() {
     public HierarchicalStreamWriter createWriter(Writer out) {
       return new PrettyPrintWriter(out) {
         // 對(duì)所有xml節(jié)點(diǎn)的轉(zhuǎn)換都增加CDATA標(biāo)記
         boolean cdata = true;
 
         //@SuppressWarnings("unchecked")
         public void startNode(String name, Class clazz) {
           super.startNode(name, clazz);
         }
 
         protected void writeText(QuickWriter writer, String text) {
           if (cdata) {
             writer.write("<![CDATA[");
             writer.write(text);
             writer.write("]]>");
           } else {
             writer.write(text);
           }
         }
       };
     }
   });

這一段代碼是我把字符串格式的數(shù)據(jù)轉(zhuǎn)換成xml格式的方法。再把xml格式的數(shù)據(jù)保存在一個(gè)字符串里面,這個(gè)時(shí)候我們開(kāi)始向官方接口發(fā)送數(shù)據(jù)。

 public String httpsRequest(String url, String xmlObj, String path) throws Exception {
 // 加載證書(shū)
 initCert(path);
 
 String result = null;
 
 HttpPost httpPost = new HttpPost(url);
 
 // 得指明使用UTF-8編碼,否則到API服務(wù)器XML的中文不能被成功識(shí)別
 StringEntity postEntity = new StringEntity(xmlObj, "UTF-8");
 httpPost.addHeader("Content-Type", "text/xml");
 httpPost.setEntity(postEntity);
 
 // 設(shè)置請(qǐng)求器的配置
 httpPost.setConfig(requestConfig);
 
 try {
  HttpResponse response = httpClient.execute(httpPost);
 
  HttpEntity entity = response.getEntity();
 
  result = EntityUtils.toString(entity, "UTF-8");
 
 } catch (ConnectionPoolTimeoutException e) {
  e.printStackTrace();
 } catch (ConnectTimeoutException e) {
  e.printStackTrace();
 
 } catch (SocketTimeoutException e) {
  e.printStackTrace();
 
 } catch (Exception e) {
  e.printStackTrace();
 
 } finally {
  httpPost.abort();
 }
 
 return result;
 }

通過(guò)Https往API post xml數(shù)據(jù)。

RefundRequest refundRequest = new RefundRequest();
  String result = refundRequest.httpsRequest("https://api.mch.weixin.qq.com/secapi/pay/refund", info, path);
 
  getMap = MobiMessage.parseXml(new String(result.toString().getBytes(), "utf-8"));
  System.out.println(getMap + "............getMap");
  json.put("return_msg", getMap.get("return_msg"));
  json.put("return_code", getMap.get("return_code"));
  json.put("outTradeNo", outTradeNo);

這一段就是給接口發(fā)送數(shù)據(jù)的代碼(官方api接口,xml數(shù)據(jù),證書(shū)的位置),然后我們接受接口返回的信息通過(guò)返回的return_msg和return_code來(lái)判斷是否退款成功。

好了,微信退款就是這樣完全可以照著代碼把流程讀出來(lái)很清晰明了也很簡(jiǎn)單,代碼能力稍強(qiáng)的都看得懂,我主要是給大家提供一個(gè)思路。如果有同學(xué)沒(méi)看懂也沒(méi)關(guān)系下面是該項(xiàng)目的源碼地址大家可以去下載退款的源代碼都在里面:wechat_jb51.rar

PS:總結(jié)一下我在做微信退款的時(shí)候遇到的問(wèn)題:
1.遇到了一個(gè)"Keystore password was incorrect"這個(gè)問(wèn)題,原因這個(gè)退款所需要的證書(shū)不正確,這個(gè)證書(shū)是需要從微信平臺(tái)去下載這個(gè)證書(shū);
2.一定要注意在支付時(shí)的訂單號(hào)碼和退款時(shí)的訂單號(hào)碼是一致的,我碰到的這個(gè)問(wèn)題是在支付時(shí),把訂單號(hào)碼和微信返回的交易號(hào)碼存數(shù)據(jù)庫(kù)時(shí)弄反了,導(dǎo)致微信找不到這筆訂單;
3.另外碰到的問(wèn)題是退款在獲取證書(shū)的時(shí)候,證書(shū)的路徑不對(duì),導(dǎo)致沒(méi)有獲取到證書(shū),所以退款失敗,所以還要檢查證書(shū)是否存在,證書(shū)的路徑是否正確,還要留意服務(wù)器上能否獲取到證書(shū)。

上述內(nèi)容就是怎么在Java中使用SSM框架實(shí)現(xiàn)一個(gè)微信退款功能,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI