酷代码 AI
菜单

Springboot+vue微信扫码登录

# SpringBoot + Vue 实现微信扫码登录 微信扫码登录是一种常见的第三方登录方式,下面我将详细介绍如何实现SpringBoot后端和Vue前端的微信扫码登录功能。 ## 一、准备工作 1. 注册微信开放平台账号(https://open.weixin.qq.com) 2. 创建网站应用,获取AppID和AppSecret 3. 设置授权回调域(需要备案的域名) ## 二、后端实现(SpringBoot) 1. 添加依赖 ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency> ``` 2. 创建微信登录工具类 ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class WeChatAuthUtil { private static final String APP_ID = "你的AppID"; private static final String APP_SECRET = "你的AppSecret"; // 获取微信登录二维码URL public static String getQrCodeUrl(String redirectUri, String state) { return "https://open.weixin.qq.com/connect/qrconnect?appid=" + APP_ID + "&redirect_uri=" + redirectUri + "&response_type=code&scope=snsapi_login&state=" + state + "#wechat_redirect"; } // 通过code获取access_token public static String getAccessToken(String code) throws IOException { String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET + "&code=" + code + "&grant_type=authorization_code"; return doGet(url); } // 获取用户信息 public static String getUserInfo(String accessToken, String openid) throws IOException { String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid; return doGet(url); } // 发送GET请求 private static String doGet(String url) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); response.close(); httpClient.close(); return result; } } ``` 3. 创建控制器 ```java import com.alibaba.fastjson.JSONObject; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @RestController @RequestMapping("/api/auth") public class AuthController { @GetMapping("/wechat/qrCode") public String getWeChatQrCode(@RequestParam String redirectUri, @RequestParam String state) { return WeChatAuthUtil.getQrCodeUrl(redirectUri, state); } @GetMapping("/wechat/callback") public JSONObject wechatCallback(@RequestParam String code) throws IOException { // 1. 获取access_token String accessTokenResult = WeChatAuthUtil.getAccessToken(code); JSONObject accessTokenObj = JSONObject.parseObject(accessTokenResult); // 2. 获取用户信息 String userInfo = WeChatAuthUtil.getUserInfo( accessTokenObj.getString("access_token"), accessTokenObj.getString("openid") ); // 3. 处理用户信息(如保存到数据库等) JSONObject userInfoObj = JSONObject.parseObject(userInfo); // 4. 返回用户信息给前端 return userInfoObj; } } ``` ## 三、前端实现(Vue) 1. 安装依赖 ```bash npm install qrcode.vue --save ``` 2. 创建微信登录组件 ```vue <template> <div> <qrcode-vue v-if="qrCodeUrl" :value="qrCodeUrl" :size="200" level="H" /> <div v-else>加载中...</div> </div> </template> <script> import QrcodeVue from 'qrcode.vue' import axios from 'axios' export default { components: { QrcodeVue }, data() { return { qrCodeUrl: '', timer: null } }, mounted() { this.initWeChatLogin() }, beforeDestroy() { clearInterval(this.timer) }, methods: { async initWeChatLogin() { // 生成随机state防止CSRF攻击 const state = Math.random().toString(36).substring(2) // 获取微信登录二维码URL const res = await axios.get('/api/auth/wechat/qrCode', { params: { redirectUri: encodeURIComponent(window.location.origin + '/wechatCallback'), state } }) this.qrCodeUrl = res.data // 轮询检查登录状态 this.timer = setInterval(() => { this.checkLoginStatus(state) }, 2000) }, async checkLoginStatus(state) { try { const res = await axios.get('/api/auth/wechat/callback', { params: { state } }) if (res.data && res.data.openid) { clearInterval(this.timer) // 登录成功,处理用户信息 this.$emit('login-success', res.data) } } catch (error) { console.error('检查登录状态出错:', error) } } } } </script> ``` 3. 使用组件 ```vue <template> <div> <h1>微信扫码登录</h1> <wechat-login @login-success="handleLoginSuccess" /> </div> </template> <script> import WechatLogin from '@/components/WechatLogin.vue' export default { components: { WechatLogin }, methods: { handleLoginSuccess(userInfo) { // 存储用户信息 localStorage.setItem('userInfo', JSON.stringify(userInfo)) // 跳转到首页或其他页面 this.$router.push('/home') } } } </script> ``` ## 四、注意事项 1. 微信开放平台要求回调域名必须备案且与申请时填写的一致 2. 生产环境需要使用HTTPS协议 3. state参数用于防止CSRF攻击,应该随机生成并验证 4. 用户扫码后,微信会重定向到回调地址并带上code和state参数 5. 前端轮询检查登录状态的方式可以改为WebSocket实现更高效 ## 五、额外逻辑点 1. 微信返回的access_token有效期较短(7200秒),如需长期存储用户信息应考虑使用自己的token机制 2. 用户信息中的unionid是同一用户在多个微信应用中的唯一标识,建议存储 3. 微信扫码登录涉及敏感信息传输,务必使用HTTPS确保通信安全 [2025-06-03 11:51:27 | AI写代码神器 | 1660点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多