1.引入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.3.12.RELEASE</version>
</dependency>
2.添加websocket服务节点配置(java配置方式)
WebSocketConfig :
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter getServerEndpointExporter(){
return new ServerEndpointExporter();
}
}
3.创建websocket服务器
WebSocketServer :
@Component
@ServerEndpoint("/webSocket/{oid}")
public class WebSocketServer {
private static ConcurrentHashMap<String,Session> sessionMap = new ConcurrentHashMap<>();
//前端发送请求建立webSocket连接,就会执行OnOpen方法
@OnOpen
public void open(@PathParam("oid") String orderId, Session session){
sessionMap.put(orderId,session);
}
//前端关闭页面或者主动关闭webSocket连接都会执行close
@OnClose
public void close(@PathParam("oid") String orderId){
sessionMap.remove(orderId);
}
public static void sendMsg(String orderId,String msg){
try {
Session session = sessionMap.get(orderId);
session.getBasicRemote().sendText(msg);
}catch (Exception e){
e.printStackTrace();
}
}
}
PayController:
@RestController
@RequestMapping("/pay")
public class PayController {
@Autowired
private OrderService orderService;
//回调接口:当用户支付成功之后,微信支付平台就会请求这个接口,将支付状态的数据传递过来
//1.接收微信支付平台传递的数据(传递的数据格式为request的输入流)
@RequestMapping("/callback")
public String success(HttpServletRequest request) throws Exception {
System.out.println("------------callback");
ServletInputStream is = request.getInputStream();
byte[] bs = new byte[1024];
int len = -1;
StringBuilder builder = new StringBuilder();
while ( (len = is.read(bs)) != -1){
builder.append(new String(bs,0,len));
}
String s = builder.toString();
//使用帮助类将xml接口的字符串转换成map
Map<String, String> map = WXPayUtil.xmlToMap(s);
if (map != null && "success".equalsIgnoreCase( map.get("result_code")) ){
//支付成功
//2.修改订单状态为“待发货/已支付”
String orderId = map.get("out_trade_no");
int i = orderService.updateOrderStatus(orderId, "2");
System.out.println("----orderId:"+orderId);
//3.通过websocket连接向前端推送消息
// Session session = WebSocketServer.sessionMap.get(orderId);
// session.getBasicRemote().sendText("1");
WebSocketServer.sendMsg(orderId,"1");
//4.响应微信支付平台
if (i>0){
HashMap<String,String> resp = new HashMap<>();
resp.put("return_code","success");
resp.put("return_msg","OK");
resp.put("app_id",map.get("appid"));
resp.put("result_code","success");
String s1 = WXPayUtil.mapToXml(resp);
return s1;
}else {
return null;
}
}else {
//支付失败
return null;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/128087.html