目录
1.微信支付流程图
2.微信接口查询官网
https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
3.根据订单生成微信二维码
controller层
@CrossOrigin//解决跨域问题
@RestController
@RequestMapping("/order")
public class OrderController {
@Resource
private OrderService orderService;
@RequestMapping("/createNavite/{orderNo}")
public CommonResult createNavite(@PathVariable String orderNo){
return orderService.createNative(orderNo);
}
}
配置文件
server.port=8807
spring.datasource.druid.url=jdbc:mysql://localhost:3306/project?serverTimezone=Asia/Shanghai
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
# 微信的appid 商家id 密钥---申请你无法申请因为需要营业执照--这里一个老师的
weixin.appid=wx8087d8149331d27c
weixin.mch_id=1532192611
weixin.api_key=Cc158380629071583806290715838062
service层
@Service
public class OrderService {
@Resource
private OrderMapper orderMapper;
//配置文件中有
@Value("${weixin.appid}")
private String appId;
@Value("${weixin.mch_id}")
private String mchId;
@Value("${weixin.api_key}")
private String apiKey;
public CommonResult createNative(String orderNo) {
//1.根据订单号查询订单信息
QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("order_no",orderNo);
//0代表未支付
queryWrapper.eq("status",0);
Order order = orderMapper.selectOne(queryWrapper);
if(order!=null){
try{
Map<String,String> params=new HashMap<>();//请求参数
params.put("appid",appId);
params.put("mch_id",mchId);
params.put("nonce_str", WXPayUtil.generateNonceStr());
params.put("body",order.getCourseTitle());
params.put("out_trade_no",orderNo);
//这是真实数据
//params.put("total_fee",new BigDecimal(order.getTotalFee()).multiply(new BigDecimal(100)).longValue()+"");
//测试金额数据,现在是1分
params.put("total_fee",new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
params.put("spbill_create_ip","127.0.0.1");//未来写成项目部署的ID
params.put("notify_url","http://localhost:8080/pay/back");
params.put("trade_type","NATIVE");
//创建httpClient对象 作为远程调用
HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
//支持https协议
client.setHttps(true);
//设置请求的参数---格式为xml
client.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
//发送请求
client.post();
//获取请求响应结果
String content = client.getContent();
System.out.println(content);
Map<String,String> map=WXPayUtil.xmlToMap(content);
if(map.get("result_code").equals("SUCCESS")){
Map<String,Object> result=new HashMap<>();
result.put("codeUrl",map.get("code_url"));
result.put("price",order.getTotalFee());
result.put("orderNo",orderNo);
return new CommonResult(2000,"生成二维码成功",result);
}
}catch (Exception e){
e.printStackTrace();
}
}
return new CommonResult(5000,"订单失效",null);
}
}
4.前端二维码及查询订单的展示
注意下载vue-qr
npm install vue-qr
<template>
<div id="app">
<el-button type="primary" @click="pay">支付</el-button>
<!--二维码的弹出层-->
<el-dialog
title="收银台"
:visible.sync="dislogVisible"
width="30%">
<div style="text-align: center">
<p>微信支付{
{payResult.price}}元</p >
<div style="border: 1px solid #f3f3f3; width: 220px;padding: 0px;margin: 0px auto">
<!--使用vue-qr-->
<vue-qr
:text="payResult.codeUrl"
:margin="0"
colorDark="green"
:logo="require('@/assets/logo.png')"
colorLight="#fff"
:size="200">
</vue-qr>
</div>
</div>
<el-divider></el-divider>
<div style="font-size: 13px;">
提示:<br>
二维码两小时内有效,请及时扫码支付<br>
</div>
</el-dialog>
</div>
</template>
<script>
import vueQr from 'vue-qr'
export default {
name: 'app',
components:{
vueQr
},
data(){
return{
orderNo:"222111111",
payResult:{
price:0,
//借助vue-qr 可以把二维码地址转换为二维码图片
codeUrl:'',
},
dislogVisible:false,
timer1:""
}
},
methods:{
//根据订单号查询支付状态
queryPayStatus(orderNo){
this.$http.post("/order/queryPayStatus/"+orderNo).then(result=>{
if(result.data.code===2000){
//消除定时器
clearInterval(this.timer1)
this.timer1=null;
this.$message.success("支付成功");
this.dislogVisible=false;
}
})
},
pay(){
this.dislogVisible=true;
this.$http.post("/order/createNavite/"+this.orderNo).then(result=>{
if(result.data.code===2000){
this.payResult=result.data.data;
// //设置一个定时任务,每隔3秒调用一次
this.timer1=setInterval(()=>{
this.queryPayStatus(this.payResult.out_trade_no)
},3000);
}
})
}
}
}
</script>
<style>
</style>
5.后台查询订单状态
controller层
@RequestMapping("/queryPayStatus/{orderNo}")
public CommonResult queryPayStatus(@PathVariable String orderNo){
return orderService.queryPayStatus(orderNo);
}
service层
public CommonResult queryPayStatus(String orderNo) {
try{
//1.根据订单状态查询微信的支付情况
HttpClient client=new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
Map<String,String> params=new HashMap<>();
params.put("appid",appId);
params.put("mch_id",mchId);
params.put("out_trade_no",orderNo);
params.put("nonce_str",WXPayUtil.generateNonceStr());
client.setHttps(true);
client.setXmlParam(WXPayUtil.generateSignedXml(params,apiKey));
client.post();
String content = client.getContent();
System.out.println(content);
Map<String,String> map=new HashMap<>();
map = WXPayUtil.xmlToMap(content);
if(map.get("trade_state").equals("SUCCESS")){
//1.修改订单状态
Order order=new Order();
order.setStatus(1);
order.setGmtModified(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
queryWrapper.eq("order_no",orderNo);
queryWrapper.eq("status",0);
orderMapper.update(order,queryWrapper);
return new CommonResult(2000,"支付成功",null);
}
}catch (Exception e){
}
return new CommonResult(5000,"支付失败",null);
}
6.展示实体类及依赖
order类
@Data
@TableName(value = "t_order")
public class Order {
@TableId(type = IdType.ASSIGN_ID)
private String id;
private String orderNo;
private String courseId;
private String courseTitle;
private String teacherName;
private String memberId;
private String nickname;
private String mobile;
private Double totalFee;
private Integer payType;
private Integer status;
private Integer isDeleted;
private String gmtCreate;
private String gmtModified;
}
依赖
dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!--微信需要的依赖-->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>0.0.3</version>
</dependency>
<!--Java端发送请求:在Java端模拟浏览器远程访问微信接口-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
</dependencies>