栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java通过webSocket实现微信扫码后通过微信小程序授权登录Web端

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java通过webSocket实现微信扫码后通过微信小程序授权登录Web端

 

1.web端向服务器发送请求获取二维码,服务器同时返回webSocket id

参考:JAVA获取小程码_qq_43019699的博客-CSDN博客

注意:本次返回返回的二维码,同时将webSocke ID一同给前端。

    
    public Map getQRCode() {
        Map map = new HashMap();
        String webSocketId = String.valueOf(System.currentTimeMillis());
        String accessToken = getCustomerAccessToken();
        String postUrl ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scene", webSocketId);     //将webSocketId 作为参数传给扫码跳转后页面
        jsonObject.put("page", "pages/weChat_login/weChat_login"); //扫码后跳转页面
        jsonObject.put("check_path", false); //是否检查跳转页面存不存在
        jsonObject.put("env_version", "develop"); //版本
        byte[] string = null;
        try {
            string = sendPostJsonImge(postUrl, jsonObject.toJSONString());
        } catch (IOException e) {
            logger.info(String.valueOf("获取二维码时出现异常"));
        }
        String base64Str = Base64.getEncoder().encodeToString(string);
        map.put("base64Str",base64Str);
        map.put("webSocketId",webSocketId);
        return map;
    }
2.前端接收到WebSocket ID时,开启WebSocket

 web端代码

// 获取二维码
    getSignQRCode() {
      ApiService.get(
        guaranteeLoginApi.getSignQRCode.url,
        {},
        ApiService.createBasicHeaders()
      ).then(response => {
        console.log(response);
        if (response.code === ResponseType.SUCCESS.code) {
          // const buffer = Buffer.from(response.data.base64Str, "base64");
          this.dataBuffer = "data:image/png;base64," + response.data.base64Str;
          this.webSocketId = response.data.webSocketId;
          this.initWebSocket();
        } else {
          this.$message.error(response.msg);
        }
      });
    },
    initWebSocket() {
      const wsurl = process.env.VUE_APP_WEBSOCKET_URL + this.webSocketId;
      this.websock = new WebSocket(wsurl);
      console.log(this.websock);
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() {
      console.log("推送服务连接成功");
      // this.websocketsend('连接进行中', 'INITIAL');
    },
    websocketonerror() {
      // 错误
      // info(this, '推送服务连接失败');
      console.log("推送服务连接失败");
    },
    websocketonmessage(evt) {
      // 数据接收
      console.log(evt);
      const msg = eval("(" + evt.data + ")");
      console.log(msg);
      const params = {
        username: msg.unionid,
        password: msg.unionid,
        loginType: "web",
        authType: "4"
      };
      this.Login(params);
    },
3.手机端扫码跳转页面,并且获取到WebSocket ID

微信小程序页面代码






 4.点击【授权登录】之后调用后台,获取用户信息,再通过webSocket将用户信息发送到web端
 
    @Override
    public ResponseEntity getWxUserInfo(String code, String id) {
        WxAuthorizeResponse wxWebAuthorizeResponse = null;
        BeanCopyUtils beanCopyUtils = SpringUtil.getBean(BeanCopyUtils.class);
        try {
            //通过 code,appid,appSecret获取 openid 和 unionid
            wxWebAuthorizeResponse = callApiForDecrypt(code,appid,appSecret);
        }catch (Exception e){
            log.error("微信登录凭证校验异常!appId:{},code:{}", clientAppid, code, e);
            SysExceptionUtil.insert(e);
            throw new SystemServiceException(SystemStatus.CHECK_ERROR_EXCEPTION).reason("存在问题");
        }
        // 根据openid获取数据库中的用户信息
        CustomerUsers customerUsers = customerUsersMapper.findByApOpenId(wxWebAuthorizeResponse.getOpenid());
        if(customerUsers == null){
            throw new SystemServiceException(SystemStatusCode.PARAM_ERROR_EXCEPTION).reason("您尚未绑定微信账号。");
        }
        CustomerUsersRespVo customerUsersRespVo = beanCopyUtils.convertTo(customerUsers, CustomerUsersRespVo.class);
        //向webSocket发送用户信息
        try {
            WebSocketServer webSocketServer = SpringUtil.getBean("webSocketServer", WebSocketServer.class);
            webSocketServer.sendMessage(id, customerUsersRespVo);
        } catch (Exception e) {
            log.error("WebSocket消息提醒异常,消息内容为:{}", customerUsersRespVo, e);
            return ResponseEntity.Failure(BaseStatus.SERVICE_FAILURE, "未拿到webSocket中的uuid");
        }
        return ResponseEntity.Success(null).OK();
    }
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;



@Slf4j
//@ConditionalOnClass(value = WebSocketConfig.class)
@ServerEndpoint("/ws/{id}")
@Component
public class WebSocketServer {

    
    private String id = "";

    
    private Session session;

    
    private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();


    
    @OnOpen
    public void onOpen(@PathParam(value = "id") String id, Session session) {
        this.session = session;
        // 接收到发送消息的客户端编号
        this.id = id;
        // 加入map中
        webSocketMap.put(id, this);
        log.info("用户连接:{}", this.id);

    }

    
    @OnClose
    public void onClose() {
        // 从map中删除
        webSocketMap.remove(this);
        log.info("用户退出:{}", this.id);
    }

    
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:{},报文:{}", this.id, message);
        String[] messages = message.split("[|]");
        try {
            if (messages.length > 1) {
                sendToUser(messages[0], messages[1]);
            } else {
                sendToAll(messages[0]);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:{},原因:{}", this.id, error.getMessage());
        error.printStackTrace();
    }

    
    public void sendToUser(String message, String id) throws IOException {
        if (StringUtils.isBlank(message)) {
            log.error("发送报文为空!id:{}", id);
            return;
        }
        log.info("发送消息到:{},报文:{}", id, message);
        if (StringUtils.isNotBlank(id) && webSocketMap.containsKey(id)) {
            webSocketMap.get(id).sendMessage(message);
        } else {
            log.error("用户{}不在线!", id);
        }
    }

    
    public void sendToAll(String message) throws IOException {
        if (StringUtils.isBlank(message)) {
            log.error("群发报文为空!");
            return;
        }
        log.info("群发消息到所有客户端,消息:{}", message);
        for (String key : webSocketMap.keySet()) {
            webSocketMap.get(key).sendMessage(message);
        }
    }

    
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    
    public void sendMessage(String id, Object msgObj) {
        String message = null;
        if (msgObj instanceof String) {
            message = String.valueOf(msgObj);
        } else {
            message = JSON.toJSONString(msgObj);
        }
        try {
            this.sendToUser(message, id);
        } catch (IOException e) {
            log.error("websocket发送消息失败!id:{},message:{}", id, message, e);
        }
    }


}
5.最后web前端根据返回的用户信息登录。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/979463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号