微信公衆號退款開發

博主是小菜鳥,這篇文章僅是本身開發的隨筆記錄,不足博友能夠指出來,一塊兒進步php

一、【微信支付】公衆號支付開發者文檔連接地址java

https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4node

調用微信退款接口,須要發送特定的xml格式字符串到到微信退款接口;web

二、微信申請退款須要雙向證書數據庫

JAVA只須要使用apiclient_cert.p12便可,證書從apache

https://pay.weixin.qq.com/index.php/core/home/login?return_url=%2Fjson

微信商戶平臺-》帳戶設置-》 API安全 中下載的,下載後解壓到本地一個英文命名的文件夾下;api

三、證書解壓以後安全

以下圖,安裝證書,雙擊apiclient_cert.p12,一直下一步到以下頁面微信

密碼爲商戶號(mch_id),一直下一步,直至提示導入成功,至此證書安裝成功。

四、代碼

 4.1工具類(xml、map格式轉換以及簽名)

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.etom.itoilet.constants.WXPayConstants;
import com.etom.itoilet.constants.WXPayConstants.SignType;

/**
* 微信支付工具類
*
* @author hongzm
*
* @date 2017年7月17日 上午10:30:00
*/
public class WXPayUtil {
/**
* XML格式字符串轉換爲Map
*
* @param strXML XML字符串
* @return XML數據轉換後的Map
* @throws Exception
*/
public static Map<String, String> xmlToMap(String strXML) throws Exception {
  try {
    Map<String, String> data = new HashMap<String, String>();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
    org.w3c.dom.Document doc = documentBuilder.parse(stream);
    doc.getDocumentElement().normalize();
    NodeList nodeList = doc.getDocumentElement().getChildNodes();
    for (int idx = 0; idx < nodeList.getLength(); ++idx) {
      Node node = nodeList.item(idx);
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        org.w3c.dom.Element element = (org.w3c.dom.Element) node;
        data.put(element.getNodeName(), element.getTextContent());
      }
    }
    try {
      stream.close();
    } catch (Exception ex) {
      // do nothing
    }
    return data;
  } catch (Exception ex) {
    WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
    throw ex;
  }

}

/**
* 將Map轉換爲XML格式的字符串
*
* @param data Map類型數據
* @return XML格式的字符串
* @throws Exception
*/
public static String mapToXml(Map<String, String> data) throws Exception {
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
  org.w3c.dom.Document document = documentBuilder.newDocument();
  org.w3c.dom.Element root = document.createElement("xml");
  document.appendChild(root);
  for (String key: data.keySet()) {
    String value = data.get(key);
    if (value == null) {
      value = "";
    }
    value = value.trim();
    org.w3c.dom.Element filed = document.createElement(key);
    filed.appendChild(document.createTextNode(value));
    root.appendChild(filed);
  }
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer transformer = tf.newTransformer();
  DOMSource source = new DOMSource(document);
  transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  StringWriter writer = new StringWriter();
  StreamResult result = new StreamResult(writer);
  transformer.transform(source, result);
  String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
  try {
    writer.close();
  }catch (Exception ex) {
  }
  return output;
}


/**
* 生成帶有 sign 的 XML 格式字符串
*
* @param data Map類型數據
* @param key API密鑰
* @return 含有sign字段的XML
*/
public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
  return generateSignedXml(data, key, "MD5");
}

/**
* 生成帶有 sign 的 XML 格式字符串
*
* @param data Map類型數據
* @param key API密鑰
* @param signType 簽名類型
* @return 含有sign字段的XML
*/
public static String generateSignedXml(final Map<String, String> data, String key, SignType signType) throws Exception {
  String sign = generateSignature(data, key, "MD5");
  data.put("sign", sign);
  return mapToXml(data);
}


/**
* 判斷簽名是否正確
*
* @param xmlStr XML格式數據
* @param key API密鑰
* @return 簽名是否正確
* @throws Exception
*/
public static boolean isSignatureValid(String xmlStr, String key) throws Exception {
  Map<String, String> data = xmlToMap(xmlStr);
  if (!data.containsKey("sign") ) {
    return false;
  }
  String sign = data.get("sign");
  return generateSignature(data, key).equals(sign);
}

/**
* 判斷簽名是否正確,必須包含sign字段,不然返回false。使用MD5簽名。
*
* @param data Map類型數據
* @param key API密鑰
* @return 簽名是否正確
* @throws Exception
*/
public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
  return isSignatureValid(data, key,"MD5");
}

/**
* 判斷簽名是否正確,必須包含sign字段,不然返回false。
*
* @param data Map類型數據
* @param key API密鑰
* @param signType 簽名方式
* @return 簽名是否正確
* @throws Exception
*/
public static boolean isSignatureValid(Map<String, String> data, String key, SignType signType) throws Exception {
  if (!data.containsKey("sign") ) {
    return false;
  }
  String sign = data.get("sign");
  return generateSignature(data, key, signType).equals(sign);
}

/**
* 生成簽名
*
* @param data 待簽名數據
* @param key API密鑰
* @return 簽名
*/
public static String generateSignature(final Map<String, String> data, String key) throws Exception {
  return generateSignature(data, key, "MD5");
}

/**
* 生成簽名. 注意,若含有sign_type字段,必須和signType參數保持一致。
*
* @param data 待簽名數據
* @param key API密鑰
* @param signType 簽名方式
* @return 簽名
*/
public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception {
  Set<String> keySet = data.keySet();
  String[] keyArray = keySet.toArray(new String[keySet.size()]);
  Arrays.sort(keyArray);
  StringBuilder sb = new StringBuilder();
  for (String k : keyArray) {
    if (k.equals("sign")) {
      continue;
    }
    if (data.get(k).trim().length() > 0) // 參數值爲空,則不參與簽名
    sb.append(k).append("=").append(data.get(k).trim()).append("&");
  }
  sb.append("key=").append(key);
  return MD5(sb.toString()).toUpperCase();
}


/**
* 獲取隨機字符串 Nonce Str
*
* @return String 隨機字符串
*/
public static String generateNonceStr() {
  return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
}


/**
* 生成 MD5
*
* @param data 待處理數據
* @return MD5結果
*/
public static String MD5(String data) throws Exception {
  java.security.MessageDigest md = MessageDigest.getInstance("MD5");
  byte[] array = md.digest(data.getBytes("UTF-8"));
  StringBuilder sb = new StringBuilder();
  for (byte item : array) {
    sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
  }
  return sb.toString().toUpperCase();
}

/**
* 日誌
* @return
*/
public static Logger getLogger() {
  Logger logger = LoggerFactory.getLogger("wxpay java sdk");
  return logger;
}

/**
* 獲取當前時間戳,單位秒
* @return
*/
public static long getCurrentTimestamp() {
  return System.currentTimeMillis()/1000;
}

/**
* 獲取當前時間戳,單位毫秒
* @return
*/
public static long getCurrentTimestampMs() {
  return System.currentTimeMillis();
}

/**
* 生成 uuid, 即用來標識一筆單,也用作 nonce_str
* @return
*/
public static String generateUUID() {
  return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
}

}

 

/**
 * 微信支付常量
 */
public class WXPayConstants {

    public enum SignType {
        MD5, HMACSHA256
    }

    public static final String FAIL = "FAIL";
    public static final String SUCCESS = "SUCCESS";
    public static final String HMACSHA256 = "HMAC-SHA256";
    public static final String MD5 = "MD5";
    // 簽名
    public static final String FIELD_SIGN = "sign";
    // 簽名類型
    public static final String FIELD_SIGN_TYPE = "sign_type";
    // 交易類型
    public static final String JSAPI = "JSAPI";// 公衆號支付
    public static final String NATIVE = "NATIVE";// 原生掃碼支付
    public static final String APP = "APP";// app支付

}

 

4.2 微信退款(參數根據開發文檔,代碼裏紅色是必需)

微信退款的,maven還有導入兩個包

網址:http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

/***
* 提交退款處理
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/submitrefund.json")
@ResponseBody
public Map<String, Object> applyForRefun(HttpServletRequest request, HttpServletResponse response) {
  // 訂單的主鍵
  String pk_easyhouse_salelog = "";
  // 退款處理緣由(不是必須,若傳入,則會在下發給用戶的退款中顯示)
  String dispose_reason = "";
  // 銷售狀態:贊成退款:3,拒絕退款:4
  Integer sale_type = "";
  // 根據訂單pk獲取訂單VO
  EasyhouseSalelogVO sale = "";
  String xmlStr = "";
  String resultXml = "";
  Map<String, String> resultMap = new HashMap<String, String>();
  // 贊成退款
  if (sale_type == 3) {
    // 公衆帳號ID:登錄微信公衆號後臺-開發-基本配置
    String appid = "";
    // 微信支付商戶號: mch_id-登錄微信支付後臺,便可看到
    String mch_id = "";
    // 隨機字符串,長度要求在32位之內,調用工具類中的隨機數生成方法
    String nonce_str = WXPayUtil.generateNonceStr();
    // 微信訂單號 或者商戶訂單號,二選一,這裏用微信訂單號
    String transaction_id = sale.getWx_order_num();
    // 商戶退款單號,同一單號屢次請求,只退款一次
    String out_refund_no = WXPayUtil.generateUUID();
    String price = sale.getProduct_saleprice().toString();
    Double total_price = Double.valueOf(price);
    // 訂單總金額
    String total_fee = Integer.toString((int) (total_price * 100));
    // 退款總金額
    String refund_fee = Integer.toString((int) (total_price * 100));
    // 退款緣由,會在下發給用戶的退款消息中體現(可不傳入)
    String refund_desc = sale.getRefund_reason();
    // API密鑰(設置路徑:微信商戶平臺(pay.weixin.qq.com)-->帳戶設置-->API安全-->密鑰設置)
    String key = WXPayConstants.KEY;
    // 將得到的信息存入Map集合中
    Map<String, String> map = new HashMap<String, String>();
    map.put("appid", appid);
    map.put("mch_id", mch_id);
    map.put("nonce_str", nonce_str);
    map.put("transaction_id", transaction_id);
    map.put("out_refund_no", out_refund_no);
    map.put("total_fee", total_fee);
    map.put("refund_fee", refund_fee);
    map.put("refund_desc", refund_desc);
    try {
      // 調用工具類,將Map集合轉化爲帶簽名sign的XML格式字符串
      xmlStr = WXPayUtil.generateSignedXml(map, key);
      // 調用微信退款接口地址
      String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
      // 調用雙向證書,返回xml格式狀態碼
      resultXml = ClientCustomSSL.doRefund(url, xmlStr);
      // 將返回結果轉換成Map集合
      resultMap = WXPayUtil.xmlToMap(resultXml);
    } catch (Exception e) {
      logger.debug("調用退款接口失敗");
    }
  // 微信端返回字符串爲成功時,退款成功,更新數據
  if (resultMap.get("return_code").equals(WXPayConstants.SUCCESS)&& resultMap.get("result_code").equals(WXPayConstants.SUCCESS)) {

    // 退款成功時,在此處更改訂單的狀態,並更新數據庫對應信息

    sale.setSale_type(Integer.valueOf(BasicConstants.NUMBER_SALE_TYPE_REFUNDED));
    logger.debug("退款成功");
    //更新公衆號粉絲表的退款總額、消費總額
    FansInfoVO fansInfoVO = userCenterService.getUserInfo(sale.getOpenid());
    fansInfoVO.setStatus(VOStatus.UPDATED);
    fansInfoVO.setRefund_sum(fansInfoVO.getRefund_sum().add(new UFDouble(refund_fee.toString())));
    fansInfoVO.setConsume_sum(fansInfoVO.getConsume_sum().sub(new UFDouble(refund_fee.toString())));
    salelogService.saveOrUpdate(fansInfoVO);
  } else {

    // 退款失敗時,在此處設置相應信息,更新相應記錄
    sale.setSale_type(Integer.valueOf(BasicConstants.NUMBER_SALE_TYPE_REFUNDFAIL));
    logger.debug("退款失敗");
    // 記錄退款失敗緣由
    dispose_reason += "," + resultMap.get("err_code_des");
    }
  } else {
    // 退款失敗
    sale.setSale_type(Integer.valueOf(BasicConstants.NUMBER_SALE_TYPE_REFUNDFAIL));
    logger.debug("拒絕退款,退款失敗");
}

  //執行數據庫更新動做
  sale.setStatus(VOStatus.UPDATED);
  sale.setDispose_reason(dispose_reason);
  // 處理人
  sale.setPk_user(WebUtilsFactory.getInstance().getLoginInfo().getPk_user());
  // 保存退款處理時間
  sale.setDispose_time(new UFDateTime(System.currentTimeMillis()));
  int resultVO = salelogService.saveOrUpdate(sale);
  if (resultVO == 0) {
    return this.genAjaxResponse(false, "處理失敗!", null);
  }
  return this.genAjaxResponse(true, "處理成功!", null);
}

4.3 調用證書類,類裏面須要指向證書安裝的路徑

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.nw.web.utils.WebUtilsFactory;

import com.etom.itoilet.constants.WXGlobal;


/**
* 微信退款
* 建立一個自定義的SSLContext安全鏈接
*
*/
public class ClientCustomSSL {

public static String doRefund(String url,String data) throws Exception {
  //指定讀取證書格式爲PKCS12(注意PKCS12證書 是從微信商戶平臺-》帳戶設置-》 API安全 中下載的)
  KeyStore keyStore = KeyStore.getInstance("PKCS12");
  String fileName = "/cert/apiclient_cert.p12"; //文件名
  // 指定證書路徑
  String path = "";
  //讀取本機存放的PKCS12證書文件
  FileInputStream instream = new FileInputStream(new File(path));

  //好比安裝在D:/pkcs12/apiclient_cert.p12狀況下,就能夠寫成以下語句
  //FileInputStream instream = new FileInputStream(new File("D:/pkcs12/apiclient_cert.p12"));
  try {
    //指定PKCS12的密碼(商戶ID)
    keyStore.load(instream, WXGlobal.getMch_id().toCharArray());
  } finally {
    instream.close();
  }
  SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WXGlobal.getMch_id().toCharArray()).build();
  //指定TLS版本
  SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
  //設置httpclient的SSLSocketFactory
  CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
  try {
    HttpPost httpost = new HttpPost(url); // 設置響應頭信息
    httpost.addHeader("Connection", "keep-alive");
    httpost.addHeader("Accept", "*/*");
    httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    httpost.addHeader("Host", "api.mch.weixin.qq.com");
    httpost.addHeader("X-Requested-With", "XMLHttpRequest");
    httpost.addHeader("Cache-Control", "max-age=0");
    httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
    httpost.setEntity(new StringEntity(data, "UTF-8"));
    CloseableHttpResponse response = httpclient.execute(httpost);
  try {
    HttpEntity entity = response.getEntity();
    String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
    EntityUtils.consume(entity);
    return jsonStr;
  } finally {
    response.close();
  }
  } finally {
    httpclient.close();
  }
  }

}

以上內容只是小編給你們列出開發項目中實現公衆號退款的核心代碼,你們根據需求適當的添加,修改,刪除代碼。若是你們在參考本段代碼的過程當中發現有任何疑問歡迎給我留言,小編會看到會及時回覆你們的

相關文章
相關標籤/搜索