Wx生成微信支付二维码
1.配置jar依赖
<dependencies>
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
</dependencies>
2.controller–>PayLogController Wx生成微信支付二维码
@RestController
@RequestMapping("/orderservice/paylog")
public class PayLogController {
@Autowired
private PayLogService payLogService;
@Autowired
private OrderService orderService;
@GetMapping("createNative/{orderNo}")
public R createNative(@PathVariable("orderNo")String orderNo){
Map<String,Object> map= null;
try {
map = payLogService.createNative(orderNo);
return R.ok().data("map",map);
} catch (Exception e) {
e.printStackTrace();
return R.error().message("支付二维码生成失败");
}
}
@GetMapping("getPayStatus/{orderNo}")
public R getPayStatus(@PathVariable("orderNo")String orderNo){
Map<String, String> payStatus = this.payLogService.getPayStatus(orderNo);
if(payStatus==null){
return R.error();
}
if(payStatus.get("trade_state").equals("SUCCESS")){
this.payLogService.updateStatusSaveLog(payStatus);
return R.ok().message("支付成功");
}
return R.ok().code(25000).message("支付中");
}
}
3.entity–>PayLog
package com.lee.orderservice.entity;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.*;
import java.util.Date;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("t_pay_log")
@ApiModel(value="PayLog对象", description="支付日志表")
public class PayLog implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@ApiModelProperty(value = "订单号")
private String orderNo;
@ApiModelProperty(value = "支付完成时间")
private Date payTime;
@ApiModelProperty(value = "支付金额(分)")
private BigDecimal totalFee;
@ApiModelProperty(value = "交易流水号")
private String transactionId;
@ApiModelProperty(value = "交易状态")
private String tradeState;
@ApiModelProperty(value = "支付类型(1:微信 2:支付宝)")
private Integer payType;
@ApiModelProperty(value = "其他属性")
private String attr;
@ApiModelProperty(value = "逻辑删除 1(true)已删除, 0(false)未删除")
@TableLogic
private Boolean isDeleted;
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
}
4.service–>PayLogService
public interface PayLogService extends IService<PayLog> {
Map<String, Object> createNative(String orderNo) throws Exception;
public Map<String,String> getPayStatus(String orderNo);
void updateStatusSaveLog(Map<String, String> map);
}
5.service–>impl–>PayLogServiceImpl
package com.lee.orderservice.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.lee.exception.AAAException;
import com.lee.orderservice.entity.Order;
import com.lee.orderservice.entity.PayLog;
import com.lee.orderservice.mapper.PayLogMapper;
import com.lee.orderservice.service.OrderService;
import com.lee.orderservice.service.PayLogService;
import com.lee.orderservice.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
@Transactional
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {
@Autowired
private OrderService orderService;
@Override
public Map<String, Object> createNative(String orderNo) throws Exception {
Order order = orderService.getOne(new QueryWrapper<Order>().eq("order_no", orderNo));
Map<String,String> m=new HashMap<>();
m.put("appid", "wx74862e0dfcf69954");
m.put("mch_id", "1558950191");
m.put("nonce_str", WXPayUtil.generateNonceStr());
m.put("body", order.getCourseTitle());
m.put("out_trade_no", orderNo);
m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
m.put("spbill_create_ip", "127.0.0.1");
m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
m.put("trade_type", "NATIVE");
HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
client.setHttps(true);
client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
client.post();
String content = client.getContent();
Map<String, String> result = WXPayUtil.xmlToMap(content);
Map<String,Object> finalResult=new HashMap<>();
finalResult.put("out_trade_no", orderNo);
finalResult.put("course_id", order.getCourseId());
finalResult.put("total_fee", order.getTotalFee());
finalResult.put("result_code", result.get("result_code"));
finalResult.put("code_url", result.get("code_url"));
return finalResult;
}
@Override
public Map<String,String> getPayStatus(String orderNo){
try {
Map<String, String> m = new HashMap<>();
m.put("appid", "wx74862e0dfcf69954");
m.put("mch_id", "1558950191");
m.put("out_trade_no", orderNo);
m.put("nonce_str", WXPayUtil.generateNonceStr());
HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
client.setHttps(true);
client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
client.post();
String content = client.getContent();
Map<String, String> result = WXPayUtil.xmlToMap(content);
return result;
}catch (Exception e){
throw new AAAException(20001,"获取支付状态失败");
}
}
@Override
public void updateStatusSaveLog(Map<String, String> map) {
String orderNo = map.get("out_trade_no");
Order order = this.orderService.getOne(new QueryWrapper<Order>().eq("order_no", orderNo));
if(order==null||order.getStatus()==1){
return;
}
order.setStatus(1);
this.orderService.updateById(order);
PayLog payLog=new PayLog();
payLog.setOrderNo(orderNo);
payLog.setPayTime(new Date());
payLog.setPayType(1);
payLog.setTotalFee(order.getTotalFee());
payLog.setTradeState(map.get("trade_state"));
payLog.setTransactionId(map.get("transaction_id"));
this.save(payLog);
}
}
6.utils–>HttpClient
package com.lee.orderservice.utils;
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;
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;
}
}