当前位置:网站首页>Millet College wechat scanning code login process record and bug resolution

Millet College wechat scanning code login process record and bug resolution

2022-07-01 03:45:00 My little brother

It is the wechat login of cereal college , There seems to be something wrong with the information he provided on the wechat open platform , There is no way to operate normally , The following changes are made here :
The original configuration file information :

wx.open.app_id=wxed9954c01bb89b47
wx.open.app_secret=a7482517235173ddb4083788de60b90e
wx.open.redirect_url=http://guli.shop/api/ucenter/wx/callback

Now change to :

wx.open.app_id=wxed9954c01bb89b47
wx.open.app_secret=a7482517235173ddb4083788de60b90e
wx.open.redirect_url=http://localhost:8160/api/ucenter/wx/callback

Also modify the project startup port to 8160.

ConstantWxUtil Get the information of the configuration file :

@Component
public class ConstantWxUtil  implements InitializingBean {
    

    @Value("${wx.open.app_id}")
    private String appId;

    @Value("${wx.open.app_secret}")
    private String appSecret;

    @Value("${wx.open.redirect_url}")
    private String redirectUrl;

    public static String WX_OPEN_APP_ID;
    public static String WX_OPEN_APP_SECRET;
    public static String WX_OPEN_REDIRECT_URL;

    @Override
    public void afterPropertiesSet() throws Exception {
    
        WX_OPEN_APP_ID = appId;
        WX_OPEN_APP_SECRET = appSecret;
        WX_OPEN_REDIRECT_URL = redirectUrl;
    }
}

Generation of two-dimensional code method :

 @GetMapping("login")
    public String genQrConnect(HttpSession session) {
    

        //  Wechat open platform authorization baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //  token url 
        String redirectUrl = ConstantWxUtil.WX_OPEN_REDIRECT_URL;
        try {
    
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url code 
        } catch (UnsupportedEncodingException e) {
    
            throw new GuliException(20001, e.getMessage());
        }
        String state = "imhelen";
        System.out.println("state = " + state);


        // Generate qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantWxUtil.WX_OPEN_APP_ID,
                redirectUrl,
                state);

        return "redirect:" + qrcodeUrl;
    }

Code scanning login method :

@Autowired
    private UcenterMemberService memberService;

    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {
    
        // Get code
        // Hold code Request wechat fixed address , obtain access_token and openid
        // Authorized temporary notes code
        System.out.println("code = " + code);
        System.out.println("state = " + state);

        try{
    
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtil.WX_OPEN_APP_ID,
                    ConstantWxUtil.WX_OPEN_APP_SECRET,
                    code);

            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            // obtain accessToken and openid

            String result = null;

            Gson gson=new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");



            // Add the scanner information to the database 
            // Judge whether there is duplicate wechat information in the database 
            UcenterMember member=memberService.getOpenIdMember(openid);
            if (member==null){
    

                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";

                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                String userInfo = HttpClientUtils.get(userInfoUrl);
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");
                String headimgurl = (String) userInfoMap.get("headimgurl");


                // add to 
                member=new UcenterMember();
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                member.setOpenid(openid);
                memberService.save(member);

            }
            // Use jwt according to member Object to generate token character string 
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;

        }catch (Exception e){
    
            throw new GuliException(20001," Login failed ");
        }

    }

Front page method : significance : When the page is initialized , Determine whether there is in the path token Parameters , If there is , call wxLogin Method , hold token Put it in cookie in , Then call the method to get user information , according to token Get user information display .

 created() {
    

    // Get... In the path token Value 
    this.token=this.$route.query.token
    if(this.token){
    
      this.wxLogin()
    }

  },

  methods: {
    
    // Wechat login 
    wxLogin(){
    
      cookie.set("guli_token",this.token,{
    domain: 'localhost'})
       cookie.set('guli_ucenter','', {
     domain: 'localhost' })
       loginApi.getLoginInfo()
        .then(response=>{
    
          this.loginInfo= response.data.data.userInfo
           cookie.set('guli_ucenter', this.loginInfo, {
     domain: 'localhost' })
        })
    }
    }

The diagram is as follows :
 Insert picture description here

 Insert picture description here
In a nutshell : Take it first app_id,app_secret,redirect_url Go to request an interface of wechat , Wechat will return a QR code , After the user scans the code to confirm login , perform callback The callback method , Two values will be passed , One state, One code,, Then take code Request an interface provided by wechat , Get two values , One access_token For access credentials , One openid It is the unique identification of each wechat , Take these two values and request an interface of wechat , You can get the wechat avatar, nickname and other information of the code scanner .

Personal understanding is , Open a door with the key of wechat application , Get a map , Scan the map to get the key , Open a door with a key , Get another key , Open another door , To get useful information .

原网站

版权声明
本文为[My little brother]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010320511860.html