1.生成支付二维码
2.查询支付状态
3.订单状态的修改、删除
4.支付状态的回查->微信支付返回的状态
5.MQ.kafka,redis,mqtt处理支付回调状态
6.RabbitMQ,kafka,redis,mqtt实现超时订单的回滚(用户就是不支付)
其实微信支付处理起来是非常简单的,今天就用springboot来做个微信支付的操作,没操作数据库思路写在了里面(一定要看文档)
这是最终的效果图视频连接就1分多钟
https://v.qq.com/x/page/w3201nsgfrk.html)
整体结构如下
通过订单号生成支付二维码
自己写个html将里面的连接换成请求到的url就像这样
<html>
<head>
<title>微信支付title>
head>
<body>
<img id="qrious">
<script src="https://cdn.bootcdn.net/ajax/libs/qrious/4.0.2/qrious.js">script>
<script>
var qr = new QRious({
element:document.getElementById('qrious'),
size:250,
level:'H',
value:'weixin://wxpay/bizpayurl?pr=I9XWGQG00'
});
script>
body>
html>
完了之就可以在本地打开二维码扫码付款了
支付成功之后就可以通过调用接口查看支付状态和处理回调逻辑了(后面有代码)就像这样
代码如下(开发中只需要换掉微信配置即可)
1 添加pom依赖
<!-- 微信支付 -->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
<!--httpclient支持-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.51</version>
</dependency>
2 重新封装httpclient 原生的超难用
package com.demo.wxpay.utis;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class HttpClient {
private String url;
private Map<String, String> param;
private int statusCode;
private String content;
private String xmlParam;
private boolean isHttps;
public boolean isHttps() {
return isHttps;
}
public void setHttps(boolean isHttps) {
this.isHttps = isHttps;
}
public String getXmlParam() {
return xmlParam;
}
public void setXmlParam(String xmlParam) {
this.xmlParam = xmlParam;
}
public HttpClient(String url, Map<String, String> param) {
this.url = url;
this.param = param;
}
public HttpClient(String url) {
this.url = url;
}
public void setParameter(Map<String, String> map) {
param = map;
}
public void addParameter(String key, String value) {
if (param == null)
param = new HashMap<String, String>();
param.put(key, value);
}
public void post() throws ClientProtocolException, IOException {
HttpPost http = new HttpPost(url);
setEntity(http);
execute(http);
}
public void put() throws ClientProtocolException, IOException {
HttpPut http = new HttpPut(url);
setEntity(http);
execute(http);
}
public void get() throws ClientProtocolException, IOException {
if (param != null) {
StringBuilder url = new StringBuilder(this.url);
boolean isFirst = true;
for (String key : param.keySet()) {
if (isFirst) {
url.append("?");
}else {
url.append("&");
}
url.append(key).append("=").append(param.get(key));
}
this.url = url.toString();
}
HttpGet http = new HttpGet(url);
execute(http);
}
private void setEntity(HttpEntityEnclosingRequestBase http) {
if (param != null) {
List<NameValuePair> nvps = new LinkedList<NameValuePair>();
for (String key : param.keySet()) {
nvps.add(new BasicNameValuePair(key, param.get(key)));
}
http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
}
if (xmlParam != null) {
http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
}
}
private void execute(HttpUriRequest http) throws ClientProtocolException,
IOException {
CloseableHttpClient httpClient = null;
try {
if (isHttps) {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain,
String authType)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
.build();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = httpClient.execute(http);
try {
if (response != null) {
if (response.getStatusLine() != null) {
statusCode = response.getStatusLine().getStatusCode();
}
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity, Consts.UTF_8);
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.close();
}
}
public int getStatusCode() {
return statusCode;
}
public String getContent() throws ParseException, IOException {
return content;
}
}
3 controller service
controller
package com.demo.wxpay.controller;
import com.demo.wxpay.service.wxPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
@RequestMapping(value = "/wxpay")
@RestController
public class wxPayController {
@Autowired
private wxPayService wxPayService;
@GetMapping("/index")
public Object create(@RequestParam String orderid){
Map<String, String> param = new HashMap<>();
param.put("orderid", orderid);
Map map = wxPayService.nativeCreateCode(param);
return map;
}
@GetMapping("/query")
public Object query(@RequestParam String orderid){
Map map = wxPayService.queryOrder(orderid);
return map;
}
@RequestMapping("/notify/url")
public String notifyurl(HttpServletRequest request) throws Exception{
ServletInputStream inputStream = request.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int leng = 0;
while ((leng = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, leng);
}
byte[] bytes = byteArrayOutputStream.toByteArray();
String xmlStr = new String(bytes, "UTF-8");
Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("列名:" + entry.getKey() + "值是:" + entry.getValue());
}
String str = "" +
"" +
"";
return str;
}
}
接口和实现类
接口
package com.demo.wxpay.service;
import java.util.Map;
public interface wxPayService {
Map nativeCreateCode(Map<String, String> mapParam);
Map queryOrder(String orderid);
}
实现类
package com.demo.wxpay.service.impl;
import com.demo.wxpay.service.wxPayService;
import com.demo.wxpay.utis.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class wxPayServiceImpl implements wxPayService {
@Value("${weixin.appid}")
private String appid;
@Value("${weixin.partner}")
private String partner;
@Value("${weixin.partnerkey}")
private String partnerkey;
@Value("${weixin.notifyurl}")
private String notifyurl;
@Override
public Map nativeCreateCode(Map<String, String> mapParam){
Map<String, String> map = new HashMap<>();
try {
map.put("appid", appid);
map.put("mch_id", partner);
map.put("nonce_str", WXPayUtil.generateNonceStr());
map.put("body", "你最帅");
map.put("out_trade_no", mapParam.get("orderid"));
map.put("total_fee", "1");
map.put("spbill_create_ip", "127.0.0.1");
map.put("notify_url", notifyurl);
map.put("trade_type", "NATIVE");
String xml = WXPayUtil.generateSignedXml(map, partnerkey);
String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
HttpClient httpClient = new HttpClient(url);
httpClient.setHttps(true);
httpClient.setXmlParam(xml);
httpClient.post();
String content = httpClient.getContent();
Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
return resultMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public Map queryOrder(String orderid) {
Map<String, String> map = new HashMap<>();
try {
map.put("appid", appid);
map.put("mch_id", partner);
map.put("nonce_str", WXPayUtil.generateNonceStr());
map.put("out_trade_no", orderid);
String xml = WXPayUtil.generateSignedXml(map, partnerkey);
String url = "https://api.mch.weixin.qq.com/pay/orderquery";
HttpClient httpClient = new HttpClient(url);
httpClient.setHttps(true);
httpClient.setXmlParam(xml);
httpClient.post();
String content = httpClient.getContent();
Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
return resultMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
4 application.yml 配置文件
server:
port: 10086
# 微信支付信息
weixin:
# 应用ID
appid: wx8397f8696b538317
# 商户ID
partner: 1473426802
# 秘钥
partnerkey: T6m9iK73b0kn9g5v426MKfHQH7X8rKwb
# 回调地址
notifyurl: http://2r9ztiog0a.52http.tech/wxpay/notify/url
5 工具
各位大佬都知道在本地开发的时候回调是不通的,原因很简单,所有的支付商家不可能访问的到你电脑的环境,所以我们要借助第三方工具内网穿透,有ecs的可以使用自己现有的域名和ip没有的就只能借助第三方了,花生壳Windows可以mac不行,由于我是mac环境 推荐大家使用如下图的工具,关键是免费,哲西云 直接配置就可以了稍微注意点是你当前电脑的ip地址,不是127.0.0.1就可以了,创建之后会给你生成一个域名,将域名映射到你本地的项目的端口就可以了就像这样