JAVA微信开发(三), 微信支付

证实过可以用的微信支付2020.04.30

1.__开发前先从公众号查出APPID和APPSECRE
2.注册url的域名: 公众号-设置-公众号设置-功能设置
3.注册的url是你的项目根路径,不是回调路径
4.一般将MP_*****.txt放在web或webapp中,微信会从注册的url中找到这个文件
在这里插入图片描述

5.登录微信支付商户平台: 产品中心-开发配置-支付配置
6.查出微信商户号密钥: 账户中心-API安全
在这里插入图片描述
7.授权支付页面: 如需要首页弹出微信支付.则配置首页地址

在这里插入图片描述

8.微信的签名,第一次接触出错概率很高,需要多加注意

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.weixin4j.WeixinSupport;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/weixin")
public class WeixinController extends WeixinSupport {
	// 微信商户号appid
	private static final String appid = "wx*************";
	// 微信支付的商户id
	public static final String mch_id = "17**********";
	// 微信支付的商户密钥
	public static final String key = "ae********************";
	// 告知用户支付的项目
	public static final String title = "每日鲜奶快送";
    // 支付金额(单位: 分)
	public static final Integer total_fee = 500;
    // 支付成功后的服务器回调url
	public static final String notify_url = "项目根路径/weixin/wxNotify";
	// 交易类型,支付的固定值为JSAPI
	public static final String TRADETYPE = "JSAPI";
	//微信支付地址
	public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    // 签名方式,固定值
	public static final String SIGNTYPE = "MD5";
	
	/**
	 * 发起微信支付
	 * 
	 * @param openid   支付者的openid
	 * @param request
	 * @return
	 */
	@RequestMapping("/wxPay")
	public Json wxPay(String openid, HttpServletRequest request) {
		Json json = new Json();
		try {
			// 生成的随机字符串
			String nonce_str = StringUtils.getRandomStringByLength(32);
			// 获取本机的ip地址
			String spbill_create_ip = IpUtils.getIpAddr(request);
			// 商户订单号
			String orderNo = new Date().getTime() + "";


			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("body", title);
			map.put("out_trade_no", orderNo);
			map.put("total_fee", total_fee + "");
			map.put("spbill_create_ip", spbill_create_ip);
			map.put("notify_url", notify_url );
			map.put("trade_type", TRADETYPE);
			map.put("openid", openid);
			// 除去数组中的空值和签名参数
			map = PayUtil.paraFilter(map);
			String prestr = PayUtil.createLinkString(map);

			// MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
			String mysign = PayUtil.sign(prestr, key , "utf-8").toUpperCase();
			System.out.println("第一次签名:" + mysign + "=========");

			// 拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
			String xml = "<xml>" +
					"<appid>" + appid + "</appid>" +
					"<body><![CDATA[" + title + "]]></body>" +
					"<mch_id>" + mch_id + "</mch_id>" +
					"<nonce_str>" + nonce_str + "</nonce_str>" +
					"<notify_url>" + notify_url + "</notify_url>" +
					"<openid>" + openid + "</openid>" +
					"<out_trade_no>" + orderNo + "</out_trade_no>" +
					"<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" +
					"<total_fee>" + total_fee + "</total_fee>" +
					"<trade_type>" + TRADETYPE + "</trade_type>" +
					"<sign>" + mysign + "</sign>"
					+ "</xml>";
			System.out.println("调试模式_统一下单接口 请求XML数据:" + xml);

			// 调用统一下单接口,并接受返回的结果
			String result = PayUtil.httpRequest(pay_url, "POST", xml);

			System.out.println("调试模式_统一下单接口 返回XML数据:" + result);

			// 将解析结果存储在HashMap中
			Map maps = PayUtil.doXMLParse(result);
			String return_code = (String) maps.get("return_code");
			Map<String, Object> response = new HashMap<String, Object>();
			if ("SUCCESS".equals(return_code)) {
				// 业务结果
				String prepay_id = (String) maps.get("prepay_id");
				response.put("nonceStr", nonce_str);
				response.put("pg", "prepay_id=" + prepay_id);
				Long timeStamp = System.currentTimeMillis() / 1000;
				response.put("timeStamp", timeStamp + "");
				String stringSignTemp = "appId=" + appid  + "&nonceStr=" + nonce_str + "&package=prepay_id="
						+ prepay_id + "&signType=" + SIGNTYPE + "&timeStamp=" + timeStamp;
				// 再次签名,这个签名用于小程序端调用wx.requesetPayment方法
				String paySign = PayUtil.sign(stringSignTemp, key, "utf-8").toUpperCase();
				System.out.println("第二次签名:" + paySign + "========");
				response.put("paySign", paySign);

				// 更新订单信息
				
				// 业务逻辑代码

				//业务代码结束
			}
			response.put("appid", appid);

			json.setSuccess(true);
			json.setData(response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			json.setSuccess(false);
			json.setMsg("发起失败");
		}
		return json;
	}


    /**
	 * 支付成功回调
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/wxNotify")
	public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		br.close();
		// sb为微信返回的xml
		String notityXml = sb.toString();
		String resXml = "";
		System.out.println("接收到的报文:" + notityXml);

		Map map = PayUtil.doXMLParse(notityXml);

		String returnCode = (String) map.get("return_code");
		if ("SUCCESS".equals(returnCode)) {
			// 验证签名是否正确
			Map<String, String> validParams = PayUtil.paraFilter(map); // 回调验签时需要去除sign和空值参数
			String validStr = PayUtil.createLinkString(validParams);// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
			String sign = PayUtil.sign(validStr, key, "utf-8").toUpperCase();// 拼装生成服务器端验证的签名
			// 验证签名是否正确
			if (sign.equals(map.get("sign"))) {
				System.out.println(map);
				/** 此处添加自己的业务逻辑代码start **/
				
				/**例: 返回模板消息给用户(这一部分代码只是模拟公司业务的例子,不保证正确) **/
		
                String openid = (String) map.get("openid");
                User user =userservice.selectByid(openid);
				if (user) {
					Template tem = new Template();
					tem.setTemplateId("DDzhyZNR6vuyuCsdxgXligHkjkZIOuI4G4YTTeFXfJw");
					tem.setUrl("https://www.baidu.com/");
					tem.setTopColor("#ffab17");
					List<TemplateParam> paras = new ArrayList<TemplateParam>();
					paras.add(new TemplateParam("first", "您已成功支付快递费", "#ffab17"));
					paras.add(new TemplateParam("keyword1", user.getUsername(), "#ffab17"));
					paras.add(new TemplateParam("keyword2", user.getPhoto(), "#ffab17"));
					paras.add(new TemplateParam("keyword3", "5元", "#ffab17"));
					paras.add(new TemplateParam("remark", "明天早上发货", "#ffab17"));
					tem.setTemplateParamList(paras);
					tem.setToUser(openid);// 用户openid
					Noticeutil.sendMpMessage(tem);
				}
		
				/** 此处添加自己的业务逻辑代码end **/
				
				// 通知微信服务器已经支付成功
				resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
			}
		} else {
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
		}
		System.out.println(resXml);
		System.out.println("微信支付回调数据结束");

		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		out.write(resXml.getBytes());
		out.flush();
		out.close();
	}

}

实体类


public class Json {
	private boolean success;
	private String msg;
	private Object data;

   //get.set略...
}

/**
 * 模板参数
 */
public class TemplateParam {

	private String name;
	private String value;
	private String color;
	
	//get.set略...
}

/**
 * 消息模板
 */
public class Template {

	// 消息接收方
	private String toUser;
	// 模板id
	private String templateId;
	// 模板消息详情链接
	private String url;
	// 消息顶部的颜色
	private String topColor;
	// 参数列表
	private List<TemplateParam> templateParamList;

	// 按微信接口要求格式化模板
	public String toJSON() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("{");
		buffer.append(String.format("\"touser\":\"%s\"", this.toUser)).append(",");
		buffer.append(String.format("\"template_id\":\"%s\"", this.templateId)).append(",");
		buffer.append(String.format("\"url\":\"%s\"", this.url)).append(",");
		buffer.append(String.format("\"topcolor\":\"%s\"", this.topColor)).append(",");
		buffer.append("\"data\":{");
		TemplateParam param = null;
		for (int i = 0; i < this.templateParamList.size(); i++) {
			param = templateParamList.get(i);
			// 判断是否追加逗号
			if (i < this.templateParamList.size() - 1) {

				buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"},", param.getName(),
						param.getValue(), param.getColor()));
			} else {
				buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"}", param.getName(),
						param.getValue(), param.getColor()));
			}

		}
		buffer.append("}");
		buffer.append("}");
		return buffer.toString();
	}


	// 省略getter、setter方法

}

工具类

public class PayUtil {
	/**
	 * 签名字符串
	 * 
	 * @param text需要签名的字符串
	 * @param key               密钥
	 * @param input_charset编码格式
	 * @return 签名结果
	 */
	public static String sign(String text, String key, String input_charset) {
		text = text + "&key=" + key;
		return DigestUtils.md5Hex(getContentBytes(text, input_charset));
	}

	/**
	 * 签名字符串
	 * 
	 * @param text需要签名的字符串
	 * @param sign          签名结果
	 * @param key密钥
	 * @param input_charset 编码格式
	 * @return 签名结果
	 */
	public static boolean verify(String text, String sign, String key, String input_charset) {
		text = text + key;
		String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
		if (mysign.equals(sign)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @param content
	 * @param charset
	 * @return
	 * @throws SignatureException
	 * @throws UnsupportedEncodingException
	 */
	public static byte[] getContentBytes(String content, String charset) {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
		}
	}

	private static boolean isValidChar(char ch) {
		if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
			return true;
		if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
			return true;// 简体中文汉字编码
		return false;
	}

	/**
	 * 除去数组中的空值和签名参数
	 * 
	 * @param sArray 签名参数组
	 * @return 去掉空值与签名参数后的新签名参数组
	 */
	public static Map<String, String> paraFilter(Map<String, String> sArray) {
		Map<String, String> result = new HashMap<String, String>();
		if (sArray == null || sArray.size() <= 0) {
			return result;
		}
		for (String key : sArray.keySet()) {
			String value = sArray.get(key);
			if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
					|| key.equalsIgnoreCase("sign_type")) {
				continue;
			}
			result.put(key, value);
		}
		return result;
	}

	/**
	 * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
	 * 
	 * @param params 需要排序并参与字符拼接的参数组
	 * @return 拼接后字符串
	 */
	public static String createLinkString(Map<String, String> params) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		String prestr = "";
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);
			if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
				prestr = prestr + key + "=" + value;
			} else {
				prestr = prestr + key + "=" + value + "&";
			}
		}
		return prestr;
	}

	/**
	 * 
	 * @param requestUrl请求地址
	 * @param requestMethod请求方法
	 * @param outputStr参数
	 */
	public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
		// 创建SSLContext
		StringBuffer buffer = null;
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(requestMethod);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();
			// 往服务器端写内容
			if (null != outputStr) {
				OutputStream os = conn.getOutputStream();
				os.write(outputStr.getBytes("utf-8"));
				os.close();
			}
			// 读取服务器端返回的内容
			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			buffer = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				buffer.append(line);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */

	public static Map doXMLParse(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) {
			return null;
		}
		/* ============= !!!!注意,修复了微信官方反馈的漏洞,更新于2018-10-16 =========== */
		try {
			Map<String, String> data = new HashMap<String, String>();
			// TODO 在这里更换
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
			documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
			documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
			documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
			documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
			documentBuilderFactory.setXIncludeAware(false);
			documentBuilderFactory.setExpandEntityReferences(false);

			InputStream stream = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
			org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().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;
		}
	}

	/**
	 * 获取子结点的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(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

	public static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}
}

public class Noticeutil {
	/**
	 * 统一服务消息 公众号模板消息,发送公众号通知
	 * 
	 * @param token       小程序ACCESS_TOKEN
	 * @param touser      用户openid,可以是小程序的openid,也可以是公众号的openid
	 * @param appid       公众号appid
	 * @param template_id 公众号模板消息模板id
	 * @param url         公众号模板消息所要跳转的url
	 * @param weappid     公众号模板消息所要跳转的小程序appid,小程序的必须与公众号具有绑定关系
	 * @param pagepath    公众号模板消息所要跳转的小程序页面
	 * @param data        公众号模板消息的数据
	 * @return
	 * @author HGL
	 */
	public static JSONObject sendMpMessage(Template template) {
		JSONObject result = new JSONObject();
		try {
			String path = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
					+ Getaccess_token.postToken(填写自己的公众号appid , 填写自己的公众号APPSECRET);
			String r = HttpUtil.sendPost(path, template.toJSON());
			result = JSONObject.fromObject(r);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
public class StringUtils extends org.apache.commons.lang.StringUtils {
	/**
	 * StringUtils工具类方法 获取一定长度的随机字符串,范围0-9,a-z
	 * 
	 * @param length:指定字符串长度
	 * @return 一定长度的随机字符串
	 */
	public static String getRandomStringByLength(int length) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
}

感谢社区的大佬们
详细参数讲解可参考: https://blog.csdn.net/javaYouCome/article/details/79473743

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值