微信支付
https://pay.weixin.qq.com/wiki/doc/api/index.html
一、支付流程
商户后台系统先调用微信支付的统一下单接口,微信后台系统返回连接参数code_url,商户后台系统将code_url值生成唯二维码图片
二、统一下单接口
https://api.mch.weixin.qq.com/pay/unifiedorder
配置文件:
wx:
pay:
#微信支付id
app_id: wx74862e0dfcf69954
#商户号
mch_id: *********
#终端ip地址 服务所在ip地址
spbill_create_ip: 127.0.0.1
#支付之后回调
notify_url: *************
xml_key: ******************
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
11
controller层
//3.根据订单号生成二维码
@GetMapping("/createPayQcCode/{orderNo}")
public RetVal createPayQcCode(@PathVariable String orderNo){
Map<String,Object> retMap = orderService.createPayQcCode(orderNo);
return RetVal.success().data(retMap);
}
serviceImpl层
请求二维码代码:
@Value("${wx.pay.app_id}")
private String WX_PAY_APP_ID;
@Value("${wx.pay.mch_id}")
private String WX_PAY_MCH_ID;
@Value("${wx.pay.spbill_create_ip}")
private String WX_PAY_SPBILL_IP;
@Value("${wx.pay.notify_url}")
private String WX_PAY_NOTIFY_URL;
@Value("${wx.pay.xml_key}")
private String WX_PAY_XML_KEY;
public Map<String, Object> createPayQcCode(String orderNo) {
QueryWrapper<EduOrder> wrapper = new QueryWrapper<>();
wrapper.eq("order_no",orderNo);
EduOrder order = baseMapper.selectOne(wrapper);
//将参数封装成一个map接口用于转换成xml
Map<String, String> map = new HashMap<>();
//公众账号id
map.put("appid",WX_PAY_APP_ID);
//商户号
map.put("mch_id",WX_PAY_MCH_ID);
//随机字符串 工具类随机生成
map.put("nonce_str", WXPayUtil.generateNonceStr());
//商品描述(标题)
map.put("body",order.getCourseTitle());
//商户订单号
map.put("out_trade_no",orderNo);
//标价金额
String totalFee = order.getTotalFee().multiply(new BigDecimal(100)).longValue()+"";
map.put("total_fee",totalFee);
//终端IP 错误
map.put("spbill_create_ip",WX_PAY_SPBILL_IP);
//通知地址
map.put("notify_url",WX_PAY_NOTIFY_URL);
//交易类型
map.put("trade_type","NATIVE");
//生成带有标签的xml数据
try {
//WXPayUtil微信提供的工具类
String xmlParam = WXPayUtil.generateSignedXml(map, WX_PAY_XML_KEY);
//生成二维码接口
HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
//对请求接口参加参数
client.setXmlParam(xmlParam);
client.setHttps(true);
client.post();
//请求之后微信给的响应
String content = client.getContent();
//将xml格式转成map
Map<String, String> xmlToMap = WXPayUtil.xmlToMap(content);
//将从微信接受的数据,找到需要的提取出来存入新的map返会
Map<String, Object> retMap = new HashMap<>();
//二维码
retMap.put("codeUrl",xmlToMap.get("code_url"));
//订单ma
retMap.put("orderNo",orderNo);
//订单金额
retMap.put("totalFee",order.getTotalFee());
//订单课程id
retMap.put("courseId",order.getCourseId());
return retMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
查询支付状态:controller
//查看支付状态
@GetMapping("/queryOrderState/{orderNo}")
public RetVal queryOrderState(@PathVariable String orderNo){
Map<String,String> retMap = orderService.queryOrderState(orderNo);
if(retMap.get("trade_state").equals("SUCCESS")){
//说明他支付成功,那就修改订单状态并添加
orderService.updateOrderState(retMap);
return RetVal.success().message("支付成功");
}else {
return RetVal.error().message("支付失败");
}
}
serviceImpl:
//查询支付状态
@Override
public Map<String, String> queryOrderState(String orderNo) {
Map<String, String> map = new HashMap<>();
//公众账号ID
map.put("appid",WX_PAY_APP_ID);
//商户号
map.put("mch_id",WX_PAY_MCH_ID);
//商户订单号
map.put("out_trade_no",orderNo);
//随机字符串
map.put("nonce_str",WXPayUtil.generateNonceStr());
try {
String signedXml = WXPayUtil.generateSignedXml(map, WX_PAY_XML_KEY);
//发送请求
HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
//对请求接口添加参数
httpClient.setXmlParam(signedXml);
httpClient.setHttps(true);
httpClient.post();
//发送请求参数之后微信给回应
String content = httpClient.getContent();
Map<String, String> retMap = WXPayUtil.xmlToMap(content);
return retMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
HttpClient工具类:
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.SSLContextBuilder;
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.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* http请求客户端
*
* @author qy
*
*/
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);
}
/**
* set http post,put param
*/
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() {
// 信任所有
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;
}
}
自己需要所以写的没有太详细见谅