首页 > 其他分享 >微信登录

微信登录

时间:2022-09-24 01:00:06浏览次数:71  
标签:String 登录 微信 state userInfo import com

微信配置文件

# 微信开放平台 appid
wx.open.app-id=你的appid
# 微信开放平台 appsecret
wx.open.app-secret=你的secret
# 微信开放平台 重定向url
wx.open.redirect-uri=重定向url/api/user/wx/callback

配置类

package com.atguigu.yygh.user.utils;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:wx.properties")
@ConfigurationProperties(prefix = "wx.open")
@Data
public class ConstantProperties {

    private String appId;
    private String appSecret;
    private String redirectUri;

}

前端请求方法

 //切换微信登录
    weixinLogin() {
      this.dialogAtrr.showLoginType = 'weixin'

      user.getQRCodeParams().then((response) =>{
        new WxLogin({
          //true:手机单击确认后可以在iframe内跳转到redirecturl
        //false :手机单击确认登录后可以在top window 跳转到redirecturl
            self_redirect: false,
            id: 'weixinLogin', // 显示二维码的容器id
            appid: response.data.appid, 
            scope: response.data.scope, 
            redirect_uri: response.data.redirectUri,
            state: response.data.state, 
            style: 'black', // 提供"black"、"white"可选。二维码的样式
            href: '', // 外部css文件url,需要https

        }) 
      })
    },

前端api

 //获得微信登录二维码的相关参数
  getQRCodeParams(){
    return request({
      url : `/api/user/wx/getQRCodeParams`,
      method : `get`
    })
  },

生成二维码以及回调函数

api文档:网站应用微信登录开发指南

package com.atguigu.yygh.user.controller.api;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.result.ResultCode;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantProperties;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.google.gson.Gson;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.net.util.URLUtil;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.UUID;

@Api(tags = "微信扫码登录")
@Controller //注意这里没有配置@restcontroller
@RequestMapping("/api/user/wx")
@Slf4j
public class ApiWxController {

    @Autowired
    private ConstantProperties constantProperties;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 方法一: 在新的页面打开显示二维码
     */
    @GetMapping("/getQRCodeUrl")
    public String getQRCodeUrl(HttpSession session){

        try {
            //处理回调url
            String redirectUrl = URLEncoder.encode(constantProperties.getRedirectUri(), "UTF-8");

            //处理state :生成随机数,存入session
            String state = UUID.randomUUID().toString();
            log.info("生成的state = "+ state);
            session.setAttribute("wx_open_state",state);


            //要重定向的地址
            String qrcUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                    "?appid=" + constantProperties.getAppId() +
                    "&redirect_uri=" + redirectUrl +
                    "&response_type=code" +
                    "&scope=snsapi_login" +
                    "&state=" + state +
                    "#wechat_redirect";

            return "redirect:" + qrcUrl;
        } catch (UnsupportedEncodingException e) {
            throw new YyghException(ResultCode.ERROR,"生成二维码错误");
        }
    }

    /**
     * 在内嵌窗口打开
     * @param session
     * @return
     */
    @GetMapping("/getQRCodeParams")
    @ResponseBody
    public R getQRCodeParams(HttpSession session){
        try {
            String redirectUrl = URLEncoder.encode(constantProperties.getRedirectUri(), "UTF-8");

            String state = UUID.randomUUID().toString();
            log.info("生成的state : "+ state);
            session.setAttribute("wx_open_state",state);

            //组装好返回给前端的数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("appid",constantProperties.getAppId());
            map.put("redirectUri",redirectUrl);
            map.put("scope","snsapi_login");
            map.put("state",state);

            return R.ok().data(map);

        } catch (UnsupportedEncodingException e) {
            throw new YyghException(ResultCode.ERROR,"生成二维码错误");
        }

    }

    /**
     * 回调函数
     */
    @GetMapping("/callback")
    public String callback(String code, String state, HttpSession session)  {

        try {
            String sessionState = (String)session.getAttribute("wx_open_state");

            //判空操作
            if(StringUtils.isEmpty(code) || StringUtils.isEmpty(state) || !state.equals(sessionState)){
                throw new YyghException(ResultCode.ERROR,"回调参数错误");
            }

            //向微信发送请求,请求获得access_tokens
            String accessTokenUrl ="https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=" + constantProperties.getAppId() +
                    "&secret=" + constantProperties.getAppSecret() +
                    "&code=" + code +
                    "&grant_type=authorization_code";

            //使用httpclient发送请求
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //将json'转换成map 获取其中的errcode键值 ,来判断相应的成功与否
            Gson gson = new Gson();
            HashMap<String,Object> accessTokenInfoMap = gson.fromJson(accessTokenInfo, HashMap.class);

            //通过错误码是否存在来判断响应是否成功
            if(accessTokenInfoMap.get("errcode") !=null ){ //errcode只要存在就说明有错误
                throw new YyghException(ResultCode.ERROR,"获取access_token失败");
            }

            //微信获取access_token成功
            String openid = (String) accessTokenInfoMap.get("openid");
            String accessToken = (String) accessTokenInfoMap.get("access_token");

            //根据openid判断数据库中的数据是否存在
            UserInfo  userInfo= userInfoService.selectWxInfoByOpenId(openid);
            if(userInfo==null){
                //用户不存在则进行注册操作

                //向微信的资源服务器发送请求,获得当前用户的信息
                String userInfoUrl ="https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=" + accessToken +
                        "&openid=" + openid;

                String userInfResult = HttpClientUtils.get(userInfoUrl);
                HashMap<String,Object> userInfResultMap = gson.fromJson(userInfResult, HashMap.class);
                //判断响应是否失败,同上
                //通过错误码是否存在来判断响应是否成功
                if(accessTokenInfoMap.get("errcode") !=null ){ //errcode只要存在就说明有错误
                    throw new YyghException(ResultCode.ERROR,"获取用户信息失败");
                }

                //解析用户信息
                String nickname =(String) userInfResultMap.get("nickname");

                //用户注册(添加)
                 userInfo = new UserInfo();
                 userInfo.setName(nickname);
                 userInfo.setNickName(nickname);
                 userInfo.setOpenid(openid);
                 userInfoService.save(userInfo);
            }else {
                //用户存在则只需判断用户状态是否可用
                if(userInfo.getStatus() == 0){
                    throw new YyghException(ResultCode.ERROR,"用户已被锁定");
                }
            }

            //生成jwt字符串
            String token = JwtHelper.createToken(userInfo.getId(), userInfo.getName());

            //跳转到前端页面
            return "redirect:http://localhost:3000/" +
                    "?token=" + token +
                    "&name=" + URLEncoder.encode(userInfo.getName(), "utf-8") +
                    "&openid=" + openid +
                    "&phone=" + userInfo.getPhone() ;
        } catch (Exception e) {

            throw new YyghException(ResultCode.ERROR,"微信登录失败",e);
        }

    }

}

 

标签:String,登录,微信,state,userInfo,import,com
From: https://www.cnblogs.com/zhang-a-d/p/16724793.html

相关文章

  • 从《羊了个羊》看微信小游戏如何破圈以及其变现潜力和上线要求
    原文:《羊了个羊》赚得盆满钵满却暗藏风险 小游戏如何破圈“通关率不到0.1%。”因其“血压飙升”的通关设计,一款名为《羊了个羊》的微信小游戏最近走红社交网络。截......
  • WeSender不封号的微信群发工具(九)——重新设计,最新版本,更加专业
    介绍经过一年的学习,对产品和运营有了更专业的认知重新开发了WeSender,融入了产品和运营的理念界面重新设计,支持更多发送类型,新增数据分析比旧版本更安全,也更专业界面 ......
  • MySQL8 修改root用户登录密码
    在安装MySQL数据库的时候,默认不操作可能会是一个空密码。如果要设置登录密码,很多之前的旧方式,在mysql8中都不适用了,下面的这个是可以操作成功的修改mysql数据库中的user......
  • 远程登录到Linux
    首先我们下载一个xshell,下载地址:https://www.xshell.com/zh/下载安装打开xshell按快捷键alt+n进入新建窗口,输入自己的主机名,名称,说明等双击点击左边所有会话中创建......
  • windows服务器设置自动登录
    首先单击“开始运行”,在输入框中键入“regedit”打开注册表编辑器,然后在注册表编辑器左方控制台中依次单击展开“HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/WindowsNT/......
  • 【推荐】推荐一款云盘 不限速 【下载免登录】【下载不限速】【2T大存储】
    推荐一款非常好用的云盘:新用户注册即可有:2T 容量。分享:可以不用密码。可以永久使用。下载:不用登录 ,不用密码,可马上下载,且不限速。使用:分享:      ......
  • STS用Maven写一个登录页面 - 将MySQL和STS连接起来
     准备用户名数据库创建方法前面已介绍,不重复说明。创建方法:https://www.cnblogs.com/smart-zihan/p/15041013.html通过MySQLWorkbench添加。  连接MySQL与STS......
  • mac免密登录linux
    思路:在本地生成公钥和私钥,然后将公钥放到linux的root(也就是~)目录下的.ssh文件夹下(隐藏文件夹),如何没有则生成一个。在Mac客户端命令行生成公钥和私钥#cd~/.ssh......
  • 微信发送新闻每日汇报
    运行代码的时候要打开微信o#coding=utf8importpyautoguiimportpyperclipimporttimeimportrequestsfromlxmlimportetreedefget_requests():headers......
  • 安卓系统手机微信 MT管理器改羊了个羊全皮肤
    教程开始。1.打开微信,删除羊了个羊小程序。然后重新打开羊了个羊。进入之后不授权任何信息(不要登陆账号)。2.打开mt管理器/storage/emulated/0/Android/data/com.tencent.......