微信公众号退款开发
Posted how-to-say-how-to-do
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信公众号退款开发相关的知识,希望对你有一定的参考价值。
博主是小菜鸟,这篇文章仅是自己开发的随笔记录,不足博友可以指出来,一起进步
1、【微信支付】公众号支付开发者文档链接地址
https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
调用微信退款接口,需要发送特定的xml格式字符串到到微信退款接口;
2、微信申请退款需要双向证书,
JAVA只需要使用apiclient_cert.p12即可,证书从
https://pay.weixin.qq.com/index.php/core/home/login?return_url=%2F
微信商户平台-》账户设置-》 API安全 中下载的,下载后解压到本地一个英文命名的文件夹下;
3、证书解压之后
如下图,安装证书,双击apiclient_cert.p12,一直下一步到如下页面
密码为商户号(mch_id),一直下一步,直至提示导入成功,至此证书安装成功。
4、代码
4.1工具类
package com.etom.itoilet.util;
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, SignType.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, signType);
data.put(WXPayConstants.FIELD_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(WXPayConstants.FIELD_SIGN) ) {
return false;
}
String sign = data.get(WXPayConstants.FIELD_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, SignType.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(WXPayConstants.FIELD_SIGN) ) {
return false;
}
String sign = data.get(WXPayConstants.FIELD_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, SignType.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(WXPayConstants.FIELD_SIGN)) {
continue;
}
if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
if (SignType.MD5.equals(signType)) {
return MD5(sb.toString()).toUpperCase();
}
else if (SignType.HMACSHA256.equals(signType)) {
return HMACSHA256(sb.toString(), key);
}
else {
throw new Exception(String.format("Invalid sign_type: %s", signType));
}
}
/**
* 获取随机字符串 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();
}
/**
* 生成 HMACSHA256
* @param data 待处理数据
* @param key 密钥
* @return 加密结果
* @throws Exception
*/
public static String HMACSHA256(String data, String key) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
byte[] array = sha256_HMAC.doFinal(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);
}
}
4.2 微信退款(参数根据开发文档,代码里面并不是全部必需)
/***
* 提交退款处理
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/submitrefund.json")
@ResponseBody
public Map<String, Object> applyForRefun(HttpServletRequest request, HttpServletResponse response) {
// 订单的主键
String pk_easyhouse_salelog = request.getParameter(EasyhouseSalelogVO.PK_EASYHOUSE_SALELOG);
// 退款处理原因(不是必须,若传入,则会在下发给用户的退款中显示)
String dispose_reason = request.getParameter(EasyhouseSalelogVO.DISPOSE_REASON);
// 销售状态:同意退款:3,拒绝退款:4
Integer sale_type = Integer.valueOf(request.getParameter(EasyhouseSalelogVO.SALE_TYPE));
// 根据pk获取VO
EasyhouseSalelogVO sale = NWDao.getInstance().queryByPK(EasyhouseSalelogVO.class, pk_easyhouse_salelog);
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 = WXPayConstants.DOMAIN_API + WXPayConstants.REFUND_URL_SUFFIX;
// 调用双向证书,返回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 调用证书类,类里面需要指向证书安装的路径
package com.etom.itoilet.util;
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 = WebUtilsFactory.getInstance().getClientConfigPath() + fileName;
//读取本机存放的PKCS12证书文件
FileInputStream instream = new FileInputStream(new File(path));
//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();
}
}
}
以上是关于微信公众号退款开发的主要内容,如果未能解决你的问题,请参考以下文章
如何使用jsp开发微信公众平台,或者使用java语言开发公众平台