锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. JAVA
  4. Spring Boot】实现微信扫码登录

Spring Boot】实现微信扫码登录

0
  • JAVA
  • 发布于 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. 存储用户信息:将用户信息存储在数据库中,便于后续使用。

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

标签: #软件开发 1171 #JAVA 991
相关文章

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

SpringBoot整合异步任务执行 2024-10-08 11:24

同步任务: 同步任务是在单线程中按顺序执行,每次只有一个任务在执行,不会引发线程安全和数据一致性等 并发问题 同步任务需要等待任务执行完成后才能执行下一个任务,无法同时处理多个任务,响应慢,影响用 户体验 异步任务: 异步任务是在多线程中同时执行,多个任务可以并发执行,同时处理多个请求,响应快,资源

springboot kafka多数据源,通过配置动态加载发送者和消费者 2024-10-08 11:24

前言 最近做项目,需要支持kafka多数据源,实际上我们也可以通过代码固定写死多套kafka集群逻辑,但是如果需要不修改代码扩展呢,因为kafka本身不处理额外逻辑,只是起到削峰,和数据的传递,那么就需要对架构做一定的设计了。 准备test kafka本身非常容易上手,如果我们需要单元测试,引入ja

SpringBoot 集成 Redis 2024-10-08 11:24

一:SpringBoot 集成 Redis ①Redis是一个 NoSQL(not only)数据库, 常作用缓存 Cache 使用。 ②Redis是一个中间件、是一个独立的服务器;常用的数据类型: string , hash ,set ,zset , list ③通过Redis客户端可以使用多种语

SpringBoot整合QQ邮箱 2024-10-08 11:24

SpringBoot可以通过导入依赖的方式集成多种技术,这当然少不了我们常用的邮箱,现在本章演示SpringBoot整合QQ邮箱发送邮件…. 下面按步骤进行: 1.获取QQ邮箱授权码 1.1 登录QQ邮箱 1.2 开启SMTP服务 找到下图中的SMTP服务区域,如果当前账号未开启的话自己手动开启。

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.