首先是要配置好相关参数,以及一些工具类
public class weChatPayConfig {
public static final String DOMAIN = "";
public static final String APP_ID = "";
public static final String APP_SECRET = "";
public static final String API_KEY = "";
public static final String MCH_ID = ""; //商户号
public static final String URL_UNIFIED_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public static String UFDODER_URL="https://api.mch.weixin.qq.com/pay/unifiedorder"; //统一下单地址
public static String QUERY_URL= "https://api.mch.weixin.qq.com/pay/orderquery"; //订单查询地址
public static String CLOSE_URL= "https://api.mch.weixin.qq.com/pay/closeorder";//订单关闭地址
public static String REFOUND_URL= "https://api.mch.weixin.qq.com/secapi/pay/refund";//申请退款地址
public static String REFOUNDQUERY_URL= "https://api.mch.weixin.qq.com/pay/refundquery";//退款查询地址
public static String DOWNLOADBILL_URL= "https://api.mch.weixin.qq.com/pay/downloadbill";//下载对账单地址
public static String DOWNLOADFOUNDBILL_URL="https://api.mch.weixin.qq.com/pay/downloadfundflow";//下载资金账单地址
public static final String URL_NOTIFY = "";
public static final String TIME_FORMAT = "yyyyMMddHHmmss";
public static final int TIME_EXPIRE = 2;
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import org.apache.log4j.Logger;
/**
* @author hxm19
*http 请求工具类
*/
public class httpUtil {
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds 连接超时的时间
private final static String DEFAULT_ENCODING = "UTF-8"; //字符串编码
private static Logger log =Logger.getLogger(httpUtil.class);
public static String postData(String urlStr, String data){
return postData(urlStr, data, null);
}
/**
* post请求
* @param urlStr
* @param data
* @param contentType
* @return
*/
private static String postData(String urlStr, String data, String contentType) {
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setReadTimeout(CONNECT_TIMEOUT);
if(contentType != null)
conn.setRequestProperty("content-type", contentType);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
if(data == null)
data = "";
writer.write(data);
writer.flush();
writer.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\r\n");
}
return sb.toString();
} catch (IOException e) {
log.info("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
}
import java.security.MessageDigest;
/**
* Md5加密类
*/
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
"e", "f" };
}
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import org.apache.log4j.Logger;
public class PayForUtil {
private static Logger lg=Logger.getLogger(PayForUtil.class);
/**
* 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
* @return boolean
*/
public static boolean isTenpaySign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(!"sign".equals(k) && null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
//算出摘要
String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();
return tenpaySign.equals(mysign);
}
/**
* @author chenp
* @Description:sign签名
* @param characterEncoding
* 编码格式
* @param parameters
* 请求参数
* @return
*/
public static String createSign(String characterEncoding, SortedMap<Object, Object> packageParams, String API_KEY) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
/**
* @author chenp
* @Description:将请求参数转换为xml格式的string
* @param parameters
* 请求参数
* @return
*/
public static String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 取出一个指定长度大小的随机正整数.
*
* @param length
* int 设定所取出随机数的长度。length小于11
* @return int 返回生成的随机数。
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 获取当前时间 yyyyMMddHHmmss
* @author chenp
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
* 获取本机IP地址
* @author chenp
* @return
*/
public static String localIp(){
String ip = null;
Enumeration allNetInterfaces;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
for (InterfaceAddress add : InterfaceAddress) {
InetAddress Ip = add.getAddress();
if (Ip != null && Ip instanceof Inet4Address) {
ip = Ip.getHostAddress();
}
}
}
} catch (SocketException e) {
lg.warn("获取本机Ip失败:异常信息:"+e.getMessage());
}
return ip;
}
}
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLUtil {
public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
documentBuilderFactory.setFeature(FEATURE, true);
FEATURE = "http://xml.org/sax/features/external-general-entities";
documentBuilderFactory.setFeature(FEATURE, false);
FEATURE = "http://xml.org/sax/features/external-parameter-entities";
documentBuilderFactory.setFeature(FEATURE, false);
FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
documentBuilderFactory.setFeature(FEATURE, false);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
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) {
throw ex;
}
}
}
本次测试微信统一下单接口使用的是SSM框架
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface weChatPayService {
/**
* 获取微信支付二维码url
* @param params
* @return
*/
public String getCode(Map<String,String> params ) throws Exception;
/**
* 根据url转换为二维码图片
* @param url 微信返回的订单支付路径
* @param response
*/
public void encodeQrcode(String url, HttpServletResponse response);
/**
* 微信支付回调方法
* @param request
* @param response
* @throws Exception
*/
public void wechatNotify(HttpServletRequest request,HttpServletResponse response) throws Exception;
/**
* 微信支付查询方法
* @param params 包含商品订单号或微信订单号,二者必须有一个,官方推荐微信订单号
* @throws Exception
*/
public String query(Map<String,String> params) throws Exception;
/**
* 微信支付关闭订单
* @param out_trade_no 商户订单号
* @throws Exception
*/
public String close(String out_trade_no) throws Exception;
}
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import com.AlipayWeChatPay.config.PayForUtil;
import com.AlipayWeChatPay.config.XMLUtil;
import com.AlipayWeChatPay.config.httpUtil;
import com.AlipayWeChatPay.config.weChatPayConfig;
import com.AlipayWeChatPay.service.weChatPayService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
@Service
public class weChatPayServiceImpl implements weChatPayService {
public static Logger lg = Logger.getLogger(weChatPayServiceImpl.class);
private static final int BLACK = 0xff000000;
private static final int WHITE = 0xFFFFFFFF;
/*
* 获取二维码url
*
* @see com.wechat.service.weChatPayService#getCode(java.util.Map)
*/
@Override
public String getCode(Map<String, String> params) throws Exception {
// 账户信息
String appid = weChatPayConfig.APP_ID;
String mch_id = weChatPayConfig.MCH_ID;
String key = weChatPayConfig.API_KEY;
String notify_url = weChatPayConfig.URL_UNIFIED_ORDER;
String ufdoder_url = weChatPayConfig.UFDODER_URL;
String trade_type = "NATIVE";
// 时间
String currTime = PayForUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = PayForUtil.buildRandom(4) + "";
String nonce_str = strTime + strRandom;
// 参数封装
SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
packageParams.put("appid", appid);
packageParams.put("mch_id", mch_id);
packageParams.put("nonce_str", nonce_str);// 随机字符串
packageParams.put("body", params.get("productName"));// 支付的商品名称
packageParams.put("out_trade_no", params.get("Out_trade_no"));// 商户订单号【备注:每次发起请求都需要随机的字符串,否则失败。】
packageParams.put("total_fee", params.get("total_fee"));// 支付金额
packageParams.put("spbill_create_ip", PayForUtil.localIp());// 客户端主机
packageParams.put("notify_url", notify_url);
packageParams.put("trade_type", trade_type);
packageParams.put("attach", params.get("Attach"));// 额外的参数【业务类型+会员ID+支付类型】
String sign = PayForUtil.createSign("UTF-8", packageParams, key); // 获取签名
packageParams.put("sign", sign);
String requestXML = PayForUtil.getRequestXml(packageParams);// 将请求参数转换成String类型
lg.info("微信支付请求参数的报文" + requestXML);
String resXml = httpUtil.postData(ufdoder_url, requestXML); // 解析请求之后的xml参数并且转换成String类型
Map map = XMLUtil.xmlToMap(resXml);
lg.info("微信支付响应参数的报文" + resXml);
String urlCode = (String) map.get("code_url");
return urlCode;
}
/**
* 将路径生成二维码图片
*
* @author chenp
* @param content
* @param response
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void encodeQrcode(String content, HttpServletResponse response) {
if (StringUtils.isBlank(content))
return;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
BitMatrix bitMatrix = null;
try {
bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 250, 250, hints);
BufferedImage image = toBufferedImage(bitMatrix);
// 输出二维码图片流
try {
ImageIO.write(image, "png", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
} catch (WriterException e1) {
e1.printStackTrace();
}
}
/**
* 类型转换
*
* @author chenp
* @param matrix
* @return
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
}
}
return image;
}
// 特殊字符处理
public static String UrlEncode(String src) throws UnsupportedEncodingException {
return URLEncoder.encode(src, "UTF-8").replace("+", "%20");
}
/*
* 微信支付回调
*
* @see com.wechat.service.weChatPayService#wechatNotify(javax.servlet.http.
* HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public void wechatNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 读取参数
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.xmlToMap(sb.toString());
// 过滤空 设置 TreeMap
SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
Iterator<String> it = m.keySet().iterator();
while (it.hasNext()) {
String parameter = it.next();
String parameterValue = m.get(parameter);
String v = "";
if (null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
// 微信支付的API密钥
String key = weChatPayConfig.API_KEY; // key
lg.info("微信支付返回回来的参数:" + packageParams);
// 判断签名是否正确
if (PayForUtil.isTenpaySign("UTF-8", packageParams, key)) {
// 处理业务开始
String resXml = "";
if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
// 这里是支付成功
// 执行自己的业务逻辑开始
String app_id = (String) packageParams.get("appid");
String mch_id = (String) packageParams.get("mch_id");
String openid = (String) packageParams.get("openid");
String is_subscribe = (String) packageParams.get("is_subscribe");// 是否关注公众号
// 附加参数【商标申请_0bda32824db44d6f9611f1047829fa3b_15460】--【业务类型_会员ID_订单号】
String attach = (String) packageParams.get("attach");
// 商户订单号
String out_trade_no = (String) packageParams.get("out_trade_no");
// 付款金额【以分为单位】
String total_fee = (String) packageParams.get("total_fee");
// 微信生成的交易订单号
String transaction_id = (String) packageParams.get("transaction_id");// 微信支付订单号
// 支付完成时间
String time_end = (String) packageParams.get("time_end");
lg.info("app_id:" + app_id);
lg.info("mch_id:" + mch_id);
lg.info("openid:" + openid);
lg.info("is_subscribe:" + is_subscribe);
lg.info("out_trade_no:" + out_trade_no);
lg.info("total_fee:" + total_fee);
lg.info("额外参数_attach:" + attach);
lg.info("time_end:" + time_end);
// 执行自己的业务逻辑结束
lg.info("支付成功");
// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
} else {
lg.info("支付失败,错误信息:" + packageParams.get("err_code"));
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
}
// 处理业务完毕
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
} else {
lg.info("通知签名验证失败");
}
}
/*
* 微信支付查询方法
*
* @see com.AlipayWeChatPay.service.weChatPayService#query(java.util.Map)
*/
@Override
@Nullable
public String query(Map<String, String> params) throws Exception {
// 商品订单号和微信订单号
String out_trade_no = params.get("out_trade_no");
String transaction_id = params.get("transaction_id");
if (StringUtils.isBlank(out_trade_no) && StringUtils.isBlank(transaction_id)) {
return "微信订单号和商品订单号不能都为空";
}
// 时间,生成随机数
String currTime = PayForUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = PayForUtil.buildRandom(4) + "";
String nonce_str = strTime + strRandom;
// 参数封装
SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
packageParams.put("appid", weChatPayConfig.APP_ID);
packageParams.put("mch_id", weChatPayConfig.MCH_ID);
packageParams.put("nonce_str", nonce_str);
if (!StringUtils.isBlank(out_trade_no)) {
packageParams.put("out_trade_no", out_trade_no);
}
if (!StringUtils.isBlank(transaction_id)) {
packageParams.put("transaction_id", transaction_id);
}
String sign = PayForUtil.createSign("UTF-8", packageParams, weChatPayConfig.API_KEY); // 获取签名
packageParams.put("sign", sign);
String resquestXML = PayForUtil.getRequestXml(packageParams);
lg.info("请求参数报文:" + resquestXML);
String responseXml = httpUtil.postData(weChatPayConfig.QUERY_URL, resquestXML);
Map map = XMLUtil.xmlToMap(responseXml);
lg.info("微信支付响应参数的报文" + responseXml);
lg.info(map);
String result = (String) map.get("trade_state_desc");
return result;
}
/*
* 微信关闭订单
*
* @see com.AlipayWeChatPay.service.weChatPayService#close(java.util.Map)
*/
@Override
public String close(String out_trade_no) throws Exception {
// 时间,生成随机字符串
String currTime = PayForUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = PayForUtil.buildRandom(4) + "";
String nonce_str = strTime + strRandom;
// 参数封装
SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
packageParams.put("appid", weChatPayConfig.APP_ID);
packageParams.put("mch_id", weChatPayConfig.MCH_ID);
packageParams.put("nonce_str", nonce_str);
packageParams.put("out_trade_no", out_trade_no);
String sign = PayForUtil.createSign("UTF-8", packageParams, weChatPayConfig.API_KEY); // 获取签名
packageParams.put("sign", sign);
String resquestXML = PayForUtil.getRequestXml(packageParams);
lg.info("请求参数报文:" + resquestXML);
String responseXml = httpUtil.postData(weChatPayConfig.QUERY_URL, resquestXML);
Map map = XMLUtil.xmlToMap(responseXml);
lg.info("微信支付响应参数的报文" + responseXml);
lg.info(map);
String result = (String) map.get("result_code");
return result;
}
}
将自己的参数放进去应该就可以调用微信支付接口,其中借鉴了一些他人的方法,最终功能仅仅只是调用,相关逻辑可自行添加