SpringBoot 實(shí)現(xiàn)微信掃碼登錄的示例代碼
以下是支持 微信掃碼登錄 的服務(wù)端核心代碼實(shí)現(xiàn)(基于 Java+Spring Boot 框架,附帶詳細(xì)注釋):
一、準(zhǔn)備工作
注冊(cè)微信開放平臺(tái)
- 申請(qǐng)網(wǎng)站應(yīng)用,獲取
AppID和AppSecret(需 ICP 備案域名) - 設(shè)置授權(quán)回調(diào)域名(如
www.yourdomain.com)
- 申請(qǐng)網(wǎng)站應(yīng)用,獲取
添加 Maven 依賴
<!-- HTTP請(qǐng)求工具 --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.3</version> </dependency> <!-- JSON解析 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency>
二、核心代碼實(shí)現(xiàn)
1. 生成微信登錄二維碼(Controller 層)
@RestController
@RequestMapping("/auth/wechat")
public class WechatAuthController {
// 從配置文件讀?。╝pplication.yml)
@Value("${wechat.appid}")
private String appId;
@Value("${wechat.callback}")
private String callbackUrl;
/**
* 生成微信登錄二維碼的URL
*/
@GetMapping("/qrcode-url")
public String getQrCodeUrl() {
// 微信開放平臺(tái)生成二維碼的固定URL格式
String url = "https://open.weixin.qq.com/connect/qrconnect" +
"?appid=%s" +
"&redirect_uri=%s" +
"&response_type=code" +
"&scope=snsapi_login" + // 固定值
"&state=YOUR_STATE"; // 防CSRF攻擊隨機(jī)字符串(需存儲(chǔ)校驗(yàn))
return String.format(url, appId, URLEncoder.encode(callbackUrl, StandardCharsets.UTF_8));
}
}
2. 處理微信回調(diào)(獲取用戶信息)
/**
* 微信回調(diào)接口(需與開放平臺(tái)配置的回調(diào)地址一致)
*/
@GetMapping("/callback")
public ResponseEntity<?> callback(@RequestParam String code, @RequestParam String state) {
// 1. 校驗(yàn)state參數(shù)(防止CSRF攻擊)
if (!validateState(state)) {
return ResponseEntity.badRequest().body("非法請(qǐng)求");
}
// 2. 用code換取access_token
String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
"?appid=%s" +
"&secret=%s" +
"&code=%s" +
"&grant_type=authorization_code";
String response = OkHttpUtil.get(String.format(tokenUrl, appId, appSecret, code));
JsonNode tokenJson = JsonUtil.parse(response);
// 3. 獲取用戶信息
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
"?access_token=%s" +
"&openid=%s";
String userResponse = OkHttpUtil.get(
String.format(userInfoUrl, tokenJson.get("access_token").asText(),
tokenJson.get("openid").asText()));
JsonNode userInfo = JsonUtil.parse(userResponse);
// 4. 處理用戶登錄(示例:創(chuàng)建本地用戶或綁定已有賬號(hào))
User user = userService.createOrUpdateWechatUser(userInfo);
// 5. 生成JWT或Session(此處以JWT為例)
String jwtToken = JwtUtil.generateToken(user.getId());
return ResponseEntity.ok().header("Authorization", jwtToken).build();
}
3. 工具類封裝
public class OkHttpUtil {
/**
* 發(fā)送GET請(qǐng)求
*/
public static String get(String url) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
public class JsonUtil {
private static final ObjectMapper mapper = new ObjectMapper();
/**
* JSON字符串轉(zhuǎn)對(duì)象
*/
public static JsonNode parse(String json) throws JsonProcessingException {
return mapper.readTree(json);
}
}
三、關(guān)鍵安全措施
State 參數(shù)校驗(yàn)
生成隨機(jī) state 字符串并存儲(chǔ)(如 Redis),回調(diào)時(shí)驗(yàn)證是否匹配。敏感信息保護(hù)
AppSecret必須存儲(chǔ)在服務(wù)端,不可暴露給前端- 用戶 openid 等敏感信息需加密存儲(chǔ)
錯(cuò)誤處理
// 在回調(diào)接口中添加異常處理 try { // ... 業(yè)務(wù)邏輯 } catch (WechatApiException e) { // 處理微信接口錯(cuò)誤(如code過期) return ResponseEntity.status(500).body("微信登錄失?。? + e.getMessage()); }
四、配置示例(application.yml)
wechat: appid: wx1234567890abcdef # 微信應(yīng)用ID app-secret: your_app_secret_here # 微信應(yīng)用密鑰 callback: https://www.yourdomain.com/auth/wechat/callback # 授權(quán)回調(diào)地址
五、前端對(duì)接建議
- 前端通過
/auth/wechat/qrcode-url獲取二維碼 URL,使用微信官方 JS 庫渲染 - 掃碼成功后,前端通過輪詢或 WebSocket 檢查登錄狀態(tài)
到此這篇關(guān)于SpringBoot 實(shí)現(xiàn)微信掃碼登錄的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot 微信掃碼登錄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實(shí)現(xiàn)表格tr拖動(dòng)的實(shí)例(分享)
下面小編就為大家分享一篇java實(shí)現(xiàn)表格tr拖動(dòng)的實(shí)例。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12
spring?boot項(xiàng)目實(shí)戰(zhàn)之實(shí)現(xiàn)與數(shù)據(jù)庫的連接
在我們?nèi)粘5拈_發(fā)過程中,肯定不可避免的會(huì)使用到數(shù)據(jù)庫以及SQL?語句,下面這篇文章主要給大家介紹了關(guān)于spring?boot項(xiàng)目實(shí)戰(zhàn)之實(shí)現(xiàn)與數(shù)據(jù)庫連接的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
詳解spring cloud整合Swagger2構(gòu)建RESTful服務(wù)的APIs
這篇文章主要介紹了詳解spring cloud整合Swagger2構(gòu)建RESTful服務(wù)的APIs,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-01-01
一文教會(huì)你如何搭建vue+springboot項(xiàng)目
最近在搗鼓?SpringBoot?與?Vue?整合的項(xiàng)目,所以下面這篇文章主要給大家介紹了關(guān)于如何通過一篇文章教會(huì)你搭建vue+springboot項(xiàng)目,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
如何使用RequestHeaders添加自定義參數(shù)
這篇文章主要介紹了使用RequestHeaders添加自定義參數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2022-02-02

