1,vue前端登录页面
<script>
export default {
name: "login",
data() {
return {
path: "ws://www.david10.com/studyassistant/websocket/",
socket: "",
date: Date.parse(new Date()),
mywin: '',
}
},
mounted() {
this._jq();
this.init();
},
methods: {
roters() {
this.$router.push({path: '/serviceText', query: {}});
},
init: function () {
if (typeof (WebSocket) === "undefined") {
alert("您的浏览器不支持socket")
} else {
this.socket = new WebSocket(this.path + this.date)
this.socket.onopen = this.open
this.socket.onerror = this.error
this.socket.onmessage = this.getMessage
}
},
open: function () {
console.log("socket连接成功")
},
error: function () {
console.log("连接错误")
},
getMessage: function (msg) {
this.mywin.close();
let data = JSON.parse(msg.data);
if (data.code == 0) {
this.$notify({
title: '成功',
message: '登录成功',
type: 'success'
});
this.$store.commit('tokenAdd', data.msg);
this.$store.commit('yesLogin');
window.sessionStorage.setItem("isLogin", true);
window.sessionStorage.setItem("token", data.msg);
this.$router.push({path: '/index', query: {wx:data.msg}});
this.$http.defaults.headers.common['Authorization'] = data.msg;
}
if (data.code == 1) {
this.$notify.error({
title: '错误',
message: data.msg
});
}
},
send: function () {
this.socket.send(params)
},
close: function () {
console.log("socket已经关闭")
},
wxChange() {
this.mywin = window.open("https://open.weixin.qq.com/connect/qrconnect?appid=&redirect_uri=&response_type=code&scope=snsapi_login&state=" + this.date + "#wechat_redirect", "", "width=500px,height=500px");
_jq() {
$('.login').height($(window).height())
},
},
destroyed() {
this.socket.onclose = this.close
}
}
</script>
2,websocket配置
(1)maven依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>
(2)ChatInterceptor.java
public class ChatInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
String s = request.getURI().toString();
String name = s.substring(s.lastIndexOf("/" )+ 1);
attributes.put("name", name);
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
super.afterHandshake(request, response, wsHandler, ex);
}
}
(3)ChatMessageHandler.java
public class ChatMessageHandler extends TextWebSocketHandler {
private static Map<String, WebSocketSession> allClient = new ConcurrentHashMap<>();
public static Map<String, WebSocketSession> getAllClient() {
return allClient;
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
Map<String, Object> attributes = session.getAttributes();
allClient.put((String) attributes.get("name"), session);
super.afterConnectionEstablished(session);
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
}
}
(4)WebSocketConfig.java
@Configuration
@EnableWebSocket
public class WebSockertConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
webSocketHandlerRegistry.addHandler(new ChatMessageHandler(),"/websocket/*").addInterceptors(new ChatInterceptor()).setAllowedOrigins("*");
}
}
3,微信登录回调后台接口
@RequestMapping("/callback")
public void callback(String code,String state){
Jedis jedis =null;
logger.info("进入授权回调,code:{},state:{}",code,state);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
url = url.replace("APPID","你的id").replace("SECRET","你的secret").replace("CODE",code);
String tokenInfoStr = HttpUtil.postData(url,"");
logger.info("tokenInfoStr =========>"+tokenInfoStr);
JSONObject tokenInfoObject = JSON.parseObject(tokenInfoStr);
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN",tokenInfoObject.getString("access_token")).replace("OPENID",tokenInfoObject.getString("openid"));
String userInfoStr = HttpUtil.postData(userInfoUrl,"");
logger.info("userInfoObject:{}",userInfoStr);
JSONObject jsStr = JSON.parseObject(userInfoStr);
String nickname = jsStr.getString("nickname");
String headimgurl = jsStr.getString("headimgurl");
String unionid = jsStr.getString("unionid");
try {
WebSocketSession session = ChatMessageHandler.getAllClient().get(state);
if (session != null && session.isOpen()) {
ResultBean resultBean = ResultBean.setError(0, unionid);
String resultjson = JSON.toJSONString(resultBean);
session.sendMessage(new TextMessage(resultjson));
}else {
ResultBean resultBean = ResultBean.setError(1, "请检查你的网络");
String resultjson = JSON.toJSONString(resultBean);
session.sendMessage(new TextMessage(resultjson));
logger.error("会话连接出错");
}
}catch (Exception e){
e.printStackTrace();
logger.error("微信登录失败");
}
}