pom.xml
<!-- wewePay -->
<dependency>
<groupId>com.egzosn</groupId>
<artifactId>pay-java-common</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.egzosn</groupId>
<artifactId>pay-java-wx</artifactId>
<version>2.12.1</version>
</dependency>
application.yml
# 公众号支付配置 公众账号ID(appid) 商户号(mch_id) key为商户平台设置的密钥key
# key设置路径:微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置
# notify_url 回调地址
weixinpay:
appid : XX #正式
mch_id : XX #正式
key : 591f8cb5bf174ff9a178f7b9bd0aa9cf #正式
notify_url : https://XXX/notifyWeiXinPay # 回调 测试
Weixinpay.java
package com.navitek.maternal.apiweb.bean;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Author: syl
* @Date: 2019/2/26 0026 15:09
* @Description:
*/
@Data //lombok的
@Component
@ConfigurationProperties(prefix = "weixinpay")
public class Weixinpay {
private String appId ;
private String mch_id ;
private String key ;
private String notify_url ;
}
WayPayController
package com.hs.weixin_pay;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayOrder;
import com.egzosn.pay.wx.api.WxPayConfigStorage;
import com.egzosn.pay.wx.api.WxPayService;
import com.egzosn.pay.wx.bean.WxTransactionType;
import com.hs.weixin_pay.service.WeixinPayBean;
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 javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Map;
import java.util.UUID;
/**
* @Author: syl
* @Date: 2019/2/21 13:09
* @Description:
*/
@Controller
public class WayPayController {
@Autowired
private WeixinPayBean weixinPayBean;
private PayService service = null;
@PostConstruct
public void init() {
WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage();
wxPayConfigStorage.setMchId("XX");//
wxPayConfigStorage.setAppid("XX");//appId
wxPayConfigStorage.setKeyPublic("");
wxPayConfigStorage.setSecretKey("XX");//key
wxPayConfigStorage.setNotifyUrl("www");
wxPayConfigStorage.setReturnUrl("同步回调地址");
wxPayConfigStorage.setSignType("MD5");
wxPayConfigStorage.setInputCharset("utf-8");
service = new WxPayService(wxPayConfigStorage);
}
@RequestMapping(value = "tesss")
public String tesstss(){
return "wx/wxpay";
}
@RequestMapping(value = "testPay")
@ResponseBody
public Map testPay(){
PayOrder order = new PayOrder("订单title", "摘要", new BigDecimal(0.01) , UUID.randomUUID().toString().replace("-", ""));
//网页支付
order.setTransactionType(WxTransactionType.JSAPI);
order.setOpenid("okmyawMfVE-Yd0fEXPH2U0LbQFYw");//openId
//获取支付订单信息
Map orderInfo = service.orderInfo(order);
System.out.println("返回信息==="+orderInfo);
//组装成html表单信息
return orderInfo;
}
}
回调
@RequestMapping(value = "notifyWeiXinPay", produces = MediaType.APPLICATION_JSON_VALUE) // @RequestDescription("支付回调地址") @ResponseBody public String notifyWeiXinPay(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException { System.out.println("微信支付回调"); InputStream inStream = request.getInputStream(); ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } String resultxml = new String(outSteam.toByteArray(), "utf-8"); Map<String, String> params = PayCommonUtil.doXMLParse(resultxml); outSteam.close(); inStream.close(); System.out.println("支付通知返回"+String.valueOf(params)); Map<String,String> return_data = new HashMap<>(); if (!PayCommonUtil.isTenpaySign(params,weixinpay.getKey())) { // 支付失败 return_data.put("return_code", "FAIL"); return_data.put("return_msg", "return_code不正确"); return StringUtil.GetMapToXML(return_data); } else { System.out.println("===============付款成功= 处理业务开始============="); int i = payOrderService.notifyWeiXinPay(params); if(i>0){ System.out.println("====================订单操作成功================="); } return_data.put("return_code", "SUCCESS"); return_data.put("return_msg", "OK"); return StringUtil.GetMapToXML(return_data); } }
工具类方法也给你们
//xml解析 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(); 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 = getChildrenText(children); } m.put(k, v); } //关闭流 in.close(); return m; }
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>weixin pay</title>
<script src="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function onBridgeReady(appId,timeStamp,nonceStr,package,signType,paySign){
//var d = new Date()
//var time = parseInt(d.getTime()/1000);
var params = {
"appId":appId, //公众号名称,由商户传入
"timeStamp":timeStamp, //时间戳,自1970年以来的秒数
"nonceStr":nonceStr, //随机串
"package":package,
"signType":signType, //微信签名方式:
"paySign":paySign //微信签名
};
//alert(params);
WeixinJSBridge.invoke(
'getBrandWCPayRequest', params,
function(res){
//get_brand_wcpay_request:ok 支付成功
//get_brand_wcpay_request:cancel 支付过程中用户取消
//get_brand_wcpay_request:fail 支付失败
if(res.err_msg == "get_brand_wcpay_request:ok" ){
// 使用以上方式判断前端返回,微信团队郑重提示: res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
alert("支付成功");
}else if(res.err_msg == "get_brand_wcpay_request:cancel" ){
alert("取消支付");
}else if(res.err_msg == "get_brand_wcpay_request:fail" ){
alert("支付失败");
}
//alert(res.err_msg);
});
}
function prepay(){
//判断是否是微信浏览器
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
}
console.log(0);
//return;
}else{
console.log(1);
}
var d = new Date()
var time = parseInt(d.getTime()/1000);
var product_id = "KC002"+time;
var open_id = "okmyawHNYzWkEdVj2Gdj9jT7Q1XI";
$.ajax({
url:"testPay",
type:"post",
success:function(result){
alert("访问");
if(result.package){
alert(result.package);
var data = result;
var appId = data.appId ;
var timeStamp = data.timeStamp ;
var nonceStr = data.nonceStr ;
var package = data.package ;
var signType = data.signType ;
var paySign = data.sign ;
onBridgeReady(appId,timeStamp,nonceStr,package,signType,paySign);
}else{
}
}
});
}
function refresh_weixin() {
var random = Math.floor((Math.random() * 10000) + 1);
var url_random = "random="+random;
var url = decodeURI(window.location.href);
var i = url.indexOf('?');
var j = url.indexOf('random=');
if (i>-1) {
if(j>-1){
url = url.substr(0,j-1) + "&" + url_random;
}else{
url = url + "&" + url_random;
}
} else {
url = url + "?" + url_random;
}
window.location.href = url;
}
</script>
</head>
<body>
This is my weixin pay page. <br>
<input type="button" value="支付" onclick="prepay()">
<input type="button" value="刷新" onclick="refresh_weixin()">
</body>
</html>
注意:微信支付账号的回调地址一定要配置上html所在项目的服务器的地址,否则会报url不在支付配置地址中,造成支付失败。
参考资料较多,记录一下以后直接用。