记录一下微信扫码支付。该思路是自己想的,如果错了,别喷,看一下即可
<!-- 微信sdk支付 -->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
yml文件配置直接用传智播客提供的
ly:
pay:
wx:
appID: wx8397f8696b538317 #公众号id
mchID: 1473426802 #商户号id
key: T6m9iK73b0kn9g5v426MKfHQH7X8rKwb # 秘钥
notifyurl: http://a31ef7db.ngrok.io/WeChatPay/WeChatPayNotify #回调地址
写个配置类,一会方便调用
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "ly.pay.wx")
public class PayProperties {
private String appID;
private String mchID;
private String key;
private String notifyurl;
public String getAppID() {
return appID;
}
public void setAppID(String appID) {
this.appID = appID;
}
public String getMchID() {
return mchID;
}
public void setMchID(String mchID) {
this.mchID = mchID;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getNotifyurl() {
return notifyurl;
}
public void setNotifyurl(String notifyurl) {
this.notifyurl = notifyurl;
}
配置一下请求调用编码
@Bean
public RestTemplate getRestTemplate(){
RestTemplate restTemplate = new RestTemplate(); //将默认的编码格式指定成utf-8
StringHttpMessageConverter converter = new StringHttpMessageConverter();
converter.setDefaultCharset(Charset.forName("utf-8"));//处理乱码
restTemplate.getMessageConverters().set(1,converter);
return restTemplate;
}
生成code_url,用来转化成二维码
@RequestMapping("/weChatPay")
public String createPayUrl(HttpServletRequest request) {
String orderId=UUID.randomUUID().toString().replace("-", "");
try {
Map<String,String> paramMap = new HashMap<>();
paramMap.put("appid",payProperties.getAppID());
paramMap.put("mch_id",payProperties.getMchID());
paramMap.put("nonce_str", WXPayUtil.generateNonceStr());//随机数
paramMap.put("body","网课商城");
paramMap.put("out_trade_no",orderId); //交易号
paramMap.put("total_fee","1"); // 测试时 使用1分钱
paramMap.put("spbill_create_ip","127.0.0.1");
paramMap.put("notify_url",payProperties.getNotifyurl());
paramMap.put("trade_type","NATIVE"); //将参数转xml
String paramXml = WXPayUtil.generateSignedXml(paramMap, payProperties.getKey()); //2、基于httpclient工具类,调用微信支付平台,完成支付操作
String resultString = restTemplate.postForObject("https://api.mch.weixin.qq.com/pay/unifiedorder", paramXml, String.class);
Map<String, String> stringStringMap = WXPayUtil.xmlToMap(resultString);
String code_url = stringStringMap.get("code_url");
request.setAttribute("code_url", code_url);
request.setAttribute("orderId", orderId);
return "protal/memeber/wepay";
}
catch (Exception e) {
e.printStackTrace();
System.out.println("支付流程失败");
}
return "redirect:www.baidu.com";
}
/**
* 查询该订单状态
* @param orderId
* @return
*/
@RequestMapping("/pay/state/{orderId}")
@ResponseBody
public int queryPayState(@PathVariable("orderId") String orderId) {
try {
// 1、组装微信查询支付状态所需要的必填参数
Map<String,String> paramMap = new HashMap<>();
paramMap.put("appid",payProperties.getAppID());
paramMap.put("mch_id",payProperties.getMchID());
paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
paramMap.put("out_trade_no",orderId.toString()); //将参数转xml
String paramXml = WXPayUtil.generateSignedXml(paramMap, payProperties.getKey()); //2、基于restTemplate工具类,调用微信支付平台,完成支付状态操作操作
String resultString = restTemplate.postForObject("https://api.mch.weixin.qq.com/pay/orderquery", paramXml, String.class); //3、处理响应结果
Map<String, String> resultMap = WXPayUtil.xmlToMap(resultString); //支付成功,返回状态1
String status = resultMap.get("trade_state");
if(status.equals("NOTPAY")){
return 0;
}else if(status.equals("SUCCESS")){
return 1;
}else{
return 2;
}
} catch (Exception e) {
e.printStackTrace();
return 2;
}
}
获取刚才的code_url,使用js生成二维码
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>扫码支付</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-1.8.3.min.js"></script>
<script src="${pageContext.request.contextPath }/static/js/jquery.qrcode.min.js" type="text/javascript" ></script>
<script type="text/javascript">
var code = '${code_url}';
</script>
</head>
<body>
<div id="qrImage">
</div>
<div>
<p>请用微信扫码支付</p>
</div>
</body>
<script type="text/javascript">
var code = '${code_url}';
$("#qrImage").qrcode({
width:100,
height:100,
text:code,
})
</script>
<script type="text/javascript">
var x= '${sessionScope.loginUser.id}';
//alert(x);
//订单查询状态
var orderId='${orderId}';
setTimeout("queryPayState()",1000);
function queryPayState(){
$.ajax({
url:"${pageContext.request.contextPath }/pay/state/"+orderId,
data:{},
type:"GET",
success:function(data){
if(data==0){
setTimeout("queryPayState()",1000);
}else if(data==1){//支付成功,并刷新父窗口
//window.close();
//window.opener.location.href = window.opener.location.href;
makeorder();
}else{
alert("服务器忙");
}
},
error:function(){
alert("服务器忙");
},
dataType:"json"
});
}
</script>
</html>
我在该页面写一个setTimeout方法,一秒执行一次,查询该订单是否被支付,支付成功后提示信息。大致就这样,就不来图了