公司项目框架是spring+struts2+mybatis。
最近,因公司项目需要用到微信支付,第一次接触走了很多弯路,在看了很多大神的demo之后,终于搞定了。记住这不是微信公众号支付,是PC端扫二维码跟手机端H5点击支付按钮的微信支付。
需要用到的工具包有生成二维码的工具包。
这里我用的是谷歌的ZXing包——core-3.2.1.jar,这个可以上百度去找,很容易下载。
首先是工具包(建个util包全装起来),里面引入的包都挺好找的
访问微信支付地址需要用到
package com.yc.weixinutil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtil {
//private static final Log logger = Logs.get();
private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
private final static String DEFAULT_ENCODING = "UTF-8";
public static String postData(String urlStr, String data){
return postData(urlStr, data, null);
}
public 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) {
//logger.error("Error connecting to " + urlStr + ": " + e.getMessage());
System.out.println("Error connecting to " + urlStr + ": " + e.getMessage());
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
}
}
return null;
}
}
这个是谷歌生成二维码的类
package com.yc.weixinutil;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.google.zxing.common.BitMatrix;
public class MatrixToImageWriter {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private MatrixToImageWriter() {
}
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format "
+ format + " to " + file);
}
}
public static void writeToStream(BitMatrix matrix, String format,
OutputStream stream) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format "
+ format);
}
}
}
千篇一律的MD5转码
package com.yc.weixinutil;
import java.security.MessageDigest;
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" };
}
生成微信签名
package com.yc.weixinutil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
public class PayToolUtil {
/**
* 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
*
* @return boolean
*/
public static boolean isTenpaySign(String characterEncoding,
SortedMap
微信支付需要用到的常量
package com.yc.weixinutil;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class PayConfigUtil {
// 这个就是自己要保管好的私有Key了(切记只能放在自己的后台代码里,不能放在任何可能被看到源代码的客户端程序中)
// 每次自己Post数据给API的时候都要用这个key来对所有字段进行签名,生成的签名会放在Sign这个字段,API收到Post数据的时候也会用同样的签名算法对Post过来的数据进行签名和验证
// 收到API的返回的时候也要用这个key来对返回的数据算下签名,跟API的Sign数据进行比较,如果值不一致,有可能数据被第三方给篡改
// API_KEY 在微信商户号上获取,不懂找度娘
public static String API_KEY = "XXXXXXXXXXXXXXXXXX";
// 微信分配的公众号ID(开通公众号之后可以获取到)
public static String APP_ID = "wx97a1ceeXXXXXXXXX";
// 微信支付分配的商户号ID(开通公众号的微信支付功能之后可以获取到)
public static String MCH_ID = "123456789012";
// 机器IP
public static String CREATE_IP = getLocalHostAddress();
// 回调地址,很重要
public static String NOTIFY_URL = "http://www.回调域名.com/加你的回调地址";
// 获取微信支付返回xml的地址
public static String UFDODER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public static String getLocalHostAddress() {
InetAddress addr = null;
try {
// 获取本机的相关信息并保存在addr
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return addr.getHostAddress().toString();
}
}
将参数封装成xml,这里需用到jar包——jdom4.jar,找度娘下载
package com.yc.weixinutil;
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 org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class XMLUtil {
/**
* 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
*
* @param strxml
* @return
* @throws JDOMException
* @throws IOException
*/
public static Map doXMLParse(String strxml) throws JDOMException,
IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if (null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
//-----------------------2018-07-21---------------------------------------------
// 参考 http://www.cnblogs.com/hero123/p/9282753.html
// 这是优先选择. 如果不允许DTDs (doctypes) ,几乎可以阻止所有的XML实体攻击
String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
builder.setFeature(FEATURE, true);
FEATURE = "http://xml.org/sax/features/external-general-entities";
builder.setFeature(FEATURE, false);
FEATURE = "http://xml.org/sax/features/external-parameter-entities";
builder.setFeature(FEATURE, false);
FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
builder.setFeature(FEATURE, false);
System.out.println("2018-07-21 加入了修复XXE攻击漏洞");
//------------------------------------------------------------------------------
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if (children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = XMLUtil.getChildrenText(children);
}
m.put(k, v);
}
// 关闭流
in.close();
return m;
}
/**
* 获取子结点的xml
*
* @param children
* @return String
*/
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if (!children.isEmpty()) {
Iterator it = children.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("<" + name + ">");
if (!list.isEmpty()) {
sb.append(XMLUtil.getChildrenText(list));
}
sb.append(value);
sb.append("" + name + ">");
}
}
return sb.toString();
}
}
开始上代码,这是正题。我将生成二维码,执行微信支付,还有回调地址都放同一controller,这样方便我。温馨提示,记得配置action
package com.yc.business.controller;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.jdom.JDOMException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.yc.adapter.CommonAdapter;
import com.yc.controller.BaseController;
import com.yc.util.JSONUtil;
import com.yc.weixinutil.HttpUtil;
import com.yc.weixinutil.MatrixToImageWriter;
import com.yc.weixinutil.PayConfigUtil;
import com.yc.weixinutil.PayToolUtil;
import com.yc.weixinutil.XMLUtil;
public class WeixinPayController extends BaseController {
/**
*
*/
private static final long serialVersionUID = 1L;
private CommonAdapter commonAdapter;
private Map paramMap = new HashMap();
private Map resultMap = new HashMap();
/**
* 微信支付二维码生成
*/
public void qrcode() {
//doEncoding();
try {
String bId = (String)paramMap.get("bId");
// 获取支付url
String text = weixinPay(bId);
// 根据url来生成生成二维码
int width = 300;
int height = 300;
// 二维码的图片格式
String format = "gif";
Hashtable hints = new Hashtable();
// 内容所使用编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix;
try {
bitMatrix = new MultiFormatWriter().encode(text,
BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format,
response.getOutputStream());
} catch (WriterException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 执行微信支付
* */
public static String weixinPay(String bId) {
// 以下的各种参数,不懂得在微信支付开发文档里面可以查找
String out_trade_no = "yc3312" + System.currentTimeMillis(); // 订单号
// (调整为自己的生产逻辑)
// 账号信息
String appid = PayConfigUtil.APP_ID; // appid
// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
String mch_id = PayConfigUtil.MCH_ID; // 商户号
String key = PayConfigUtil.API_KEY; // key
String currTime = PayToolUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = PayToolUtil.buildRandom(4) + "";
String nonce_str = strTime + strRandom; // 随机字符串
// 获取发起电脑 ip
String spbill_create_ip = PayConfigUtil.CREATE_IP;
// 回调接口
String notify_url = PayConfigUtil.NOTIFY_URL;
// 这里说明支付是什么类型,NATIVE(二维码),MWEB(H5)
String trade_type = "NATIVE";
SortedMap packageParams = new TreeMap();
packageParams.put("appid", appid);
// 这里可以传你要执行业务需要的参数,可以尝试传个MAP过去,我也没试过
packageParams.put("attach", bId);
packageParams.put("mch_id", mch_id);
packageParams.put("nonce_str", nonce_str);
packageParams.put("body", "测试"); // (调整为自己的名称)
packageParams.put("out_trade_no", out_trade_no);
packageParams.put("total_fee", "1"); // 价格的单位为分
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
packageParams.put("trade_type", trade_type);
// 签名
String sign = PayToolUtil.createSign("UTF-8", packageParams, key);
packageParams.put("sign", sign);
// 将参数转换成xml
String requestXML = PayToolUtil.getRequestXml(packageParams);
// 访问支付地址
String resXml = HttpUtil
.postData(PayConfigUtil.UFDODER_URL, requestXML);
Map map = new HashMap();
try {
map = XMLUtil.doXMLParse(resXml);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 获取支付的url
String urlCode = (String) map.get("code_url");
return urlCode;
}
/**
* 回调方法,修改业务,返回成功信息给微信支付
* */
public void weixinNotify() {
// 读取参数
InputStream inputStream;
try {
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 m = new HashMap();
m = XMLUtil.doXMLParse(sb.toString());
// 过滤空 设置 TreeMap
SortedMap packageParams = new TreeMap();
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
String parameter = (String) it.next();
String parameterValue = m.get(parameter);
String v = "";
if (null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
// 账号信息
String key = PayConfigUtil.API_KEY; // key
// 判断签名是否正确
if (PayToolUtil.isTenpaySign("UTF-8", packageParams, key)) {
// ------------------------------
// 处理业务开始
// ------------------------------
String resXml = "";
if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
// 这里是支付成功
// ////////执行自己的业务逻辑////////////////
//String mch_id = (String) packageParams.get("mch_id");
//String openid = (String) packageParams.get("openid");
//String is_subscribe = (String) packageParams.get("is_subscribe");
//String out_trade_no = (String) packageParams.get("out_trade_no");
//String total_fee = (String) packageParams.get("total_fee");
// 获取刚刚设置的ID
String bId = (String) packageParams.get("attach");
// ////////执行自己的业务逻辑////////////////
// 暂时使用最简单的业务逻辑来处理:只是将业务处理结果保存到session中
// (根据自己的实际业务逻辑来调整,很多时候,我们会操作业务表,将返回成功的状态保留下来)
paramMap.put("currentStatus", 1);
paramMap.put("bId", bId);
commonAdapter.doRunUpdateSql(paramMap, "print.UPDATE_RECORD_PRINT_BY_ID");
// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
resXml = ""
+ " "
+ " "
+ " ";
} else {
resXml = ""
+ " "
+ " "
+ " ";
}
// ------------------------------
// 处理业务完毕
// ------------------------------
try {
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("通知签名验证失败");
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/***
* 轮询方法
*/
public void haPay(){
//doEncoding();
try {
Map map = commonAdapter.queryEntity4Map(paramMap, "print.QUERY_RECORD_PRINT_BY_BID");
resultMap.put("result",map.get("CURRENTSTATUS"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.doOutResult(JSONUtil.doConvertObject2Json(resultMap));
}
public CommonAdapter getCommonAdapter() {
return commonAdapter;
}
public void setCommonAdapter(CommonAdapter commonAdapter) {
this.commonAdapter = commonAdapter;
}
public Map getParamMap() {
return paramMap;
}
public void setParamMap(Map paramMap) {
this.paramMap = paramMap;
}
public Map getResultMap() {
return resultMap;
}
public void setResultMap(Map resultMap) {
this.resultMap = resultMap;
}
}
网页代码
这里需要用到两个js。layer.js、jquery-3.3.1.min.js
点击触发payMoney方法
var t1 = 0;
/*
* 点击支付
*/
function patMoney(par){
var bId = $(par).parent().find("input").val();
top.layer.open({
area : [ '300px', '300px' ],
type : 2,
closeBtn : false,
title : false,
shift : 2,
shadeClose : true,
content : '<%=basePath%>page/weixin/qrcode?paramMap.bId=' + bId,
end : function (){
window.clearInterval(t1);
}
});
// 支付进行时,会一直轮询
t1 = window.setInterval("modifyStatus('"+ bId +"')",3000);
};
function modifyStatus(bId){
var url = '<%=basePath%>page/weixin/haPay';
//轮询是否已经付费
$.ajax({
type : 'post',
url : url,
data : {"paramMap.bId" : bId},
dataType: "json",
cache : false,
async : true,
success : function(res) {
// 我的数据返回的是状态1,不明看controller
// 当该状态为1时,关闭模态框,刷新网页
if(res.result == "1"){
top.layer.closeAll();
window.clearInterval(t1);
location.reload();
}
},
error : function() {
layer.msg("执行错误!", 8);
}
});
}
以上就是二维码支付的全部了。
因为公司框架的原因。controller的执行微信支付方法,我写在了jsp上。基本一样,就是加多了一个点击支付完成后,微信帮你返回的地址。
页面名称:weixinpay.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.yc.weixinutil.*" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="org.jdom.JDOMException" %>
<%@ page import="java.io.*" %>
<%
String out_trade_no = "yc3312" + System.currentTimeMillis(); // 订单号
// (调整为自己的生产逻辑)
// 账号信息
String appid = PayConfigUtil.APP_ID; // appid
// String appsecret = PayConfigUtil.APP_SECRET; // appsecret
String mch_id = PayConfigUtil.MCH_ID; // 商业号
String key = PayConfigUtil.API_KEY; // key
String currTime = PayToolUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = PayToolUtil.buildRandom(4) + "";
String nonce_str = strTime + strRandom;
// ip地址获取
String basePath = request.getServerName() + ":"
+ request.getServerPort();
// 获取发起电脑 ip
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getRemoteAddr();
}
String spbill_create_ip = ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
// 回调接口
String notify_url = PayConfigUtil.NOTIFY_URL;
String trade_type = "MWEB";
SortedMap packageParams = new TreeMap();
packageParams.put("appid", appid);
packageParams.put("mch_id", mch_id);
packageParams.put("attach", request.getParameter("bId"));
packageParams.put("nonce_str", nonce_str);
packageParams.put("body", "打印文件支付"); // (调整为自己的名称)
packageParams.put("out_trade_no", out_trade_no);
packageParams.put("total_fee", "1"); // 价格的单位为分
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
packageParams.put("trade_type", trade_type);
packageParams.put("scene_info","{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://www.myssci.com\",\"wap_name\": \"奥科\"}}");
String sign = PayToolUtil.createSign("UTF-8", packageParams, key);
packageParams.put("sign", sign);
String requestXML = PayToolUtil.getRequestXml(packageParams);
String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL,
requestXML);
Map map = new HashMap();
try {
map = XMLUtil.doXMLParse(resXml);
System.out.println(resXml);
//确认支付过后跳的地址,需要经过urlencode处理
String urlString = URLEncoder.encode("http://www.域名.com/返回的页面路径", "GBK");
String mweb_url = map.get("mweb_url") + "&redirect_url=" + urlString;
response.sendRedirect(mweb_url);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>
当然,页面上的只有一个按钮而已,我调用了这个方法
/*
* 点击支付
*/
function patMoney(par){
var bId = $(par).parent().find("input").val();
window.location.href = basePath + "weixinPay.jsp?bId="+bId;
};
H5支付也完成了。
第一次开发,难免很多东西不会,建议准备好需要用到的东西在来开发(必须有域名)。
微信二维码、H5支付或者是其他支付,只是修改一下trade_type 这个变量就可以调取,还有的话就是回调的方式不同,比如H5 支付完成后需要跳转页面,就需要写好URL跳转。以上的工具类,大部分都可以在网上找到,需要注意的是里面有的类需要JAR包的支持。
第一次写,我也不知道写的怎么样。希望你们都能测试成功。