1. 首页
  2. 软件开发
  3. JAVA
  4. Spring Boot】实现微信扫码登录

Spring Boot】实现微信扫码登录

  • 发布于 2024-08-14
  • 0 次阅读

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

微信扫码登录的具体流程涉及多个步骤,从前期的配置到后端代码的实现,下面详细介绍每个步骤:

1. 注册和配置

  1. 注册微信账号:首先在微信注册一个账号。
  2. 获取应用的 AppID 和 AppSecret:在微信上创建应用后,你会得到 AppID 和 AppSecret,这两个值在后续步骤中会用到。
  3. 配置授权回调域:在微信设置中,配置授权回调域名。这个域名是微信在用户授权后回调的地址,例如 yourdomain.com。

2. 前端代码准备

在前端页面上添加一个按钮或链接,让用户点击后开始微信扫码登录流程。

<a href="/wechat/login">微信登录</a>

3. 后端代码实现

3.1 配置项目

首先,在 application.properties 文件中添加微信应用的配置:

wechat.app-id=YOUR_APP_ID
wechat.app-secret=YOUR_APP_SECRET
wechat.redirect-uri=http://yourdomain.com/wechat/callback
3.2 创建微信扫码登录控制器
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;

@Controller
public class WeChatLoginController {

    @Value("${wechat.app-id}")
    private String appId;

    @Value("${wechat.app-secret}")
    private String appSecret;

    @Value("${wechat.redirect-uri}")
    private String redirectUri;

    @GetMapping("/wechat/login")
    public String wechatLogin() {
        String state = UUID.randomUUID().toString();
        String wechatUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId
                + "&redirect_uri=" + redirectUri
                + "&response_type=code&scope=snsapi_login&state=" + state;
        return "redirect:" + wechatUrl;
    }

    @GetMapping("/wechat/callback")
    public String wechatCallback(String code, String state, Model model) {
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId
                + "&secret=" + appSecret
                + "&code=" + code
                + "&grant_type=authorization_code";

        RestTemplate restTemplate = new RestTemplate();
        WeChatAccessTokenResponse response = restTemplate.getForObject(tokenUrl, WeChatAccessTokenResponse.class);

        if (response != null) {
            String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + response.getAccessToken()
                    + "&openid=" + response.getOpenId();
            WeChatUserInfo userInfo = restTemplate.getForObject(userInfoUrl, WeChatUserInfo.class);
            model.addAttribute("user", userInfo);
            return "userProfile";
        }

        return "error";
    }

    static class WeChatAccessTokenResponse {
        private String accessToken;
        private String openId;

        // Getters and setters
    }

    static class WeChatUserInfo {
        private String openId;
        private String nickname;
        private String sex;
        private String province;
        private String city;
        private String country;
        private String headimgurl;

        // Getters and setters
    }
}
3.3 创建用户信息展示页面

在 src/main/resources/templates 目录下创建 userProfile.html 文件,用于显示用户信息:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>User Profile</title>
</head>
<body>
<h1>User Profile</h1>
<div>
    <img th:src="${user.headimgurl}" alt="User Avatar"/>
    <p>Nickname: <span th:text="${user.nickname}"></span></p>
    <p>Country: <span th:text="${user.country}"></span></p>
    <p>Province: <span th:text="${user.province}"></span></p>
    <p>City: <span th:text="${user.city}"></span></p>
</div>
</body>
</html>

4. 执行流程

  1. 用户点击微信登录链接:用户点击前端页面上的微信登录链接,浏览器会重定向到微信的授权页面。
  2. 用户扫码并授权:用户在微信授权页面扫码并授权,微信会将授权结果(包含授权码 code)回调到你配置的回调 URL。
  3. 后端处理回调请求:后端接收到微信的回调请求,通过授权码 code 获取访问令牌 access_token 和用户的 openid。
  4. 获取用户信息:使用 access_token 和 openid 调用微信 API 获取用户详细信息。
  5. 展示用户信息:将获取到的用户信息展示在页面上。

5. 处理异常和安全性

实际应用中,处理异常和安全性是非常重要的,包括但不限于:

  1. 防止 CSRF 攻击:使用 state 参数验证请求的合法性。
  2. 处理网络异常:网络请求可能会失败,需要处理超时和错误响应。
  3. 存储用户信息:将用户信息存储在数据库中,便于后续使用。

以上步骤基本上可以实现微信扫码登录功能。如果需要更详细的实现,可以参考微信开放平台的官方文档。