微信公眾號掃碼登錄功能實(shí)現(xiàn):Java后端集成指南

2024-11-29 11:36 更新

大家好,我是 V哥。掃碼登錄是個(gè)很普遍的功能,通過與公眾號聯(lián)動(dòng)實(shí)現(xiàn)掃碼登錄功能,要怎么做呢,V 哥整理了以下步驟和代碼,供你參考。這里假設(shè)你已經(jīng)有一個(gè)Java后端應(yīng)用,并且微信開發(fā)者平臺(tái)的配置也已經(jīng)完成。(相信你可以根據(jù)微信開放平臺(tái)的操作進(jìn)行)整個(gè)流程包括二維碼生成、掃碼后獲取微信用戶信息、并將用戶登錄狀態(tài)返回到你的應(yīng)用中。

1. 微信公眾號掃碼登錄流程

  1. 申請掃碼登錄權(quán)限:在微信開放平臺(tái)申請掃碼登錄權(quán)限。
  2. 生成二維碼:使用微信提供的接口生成一個(gè)包含應(yīng)用授權(quán)信息的二維碼。
  3. 用戶掃碼授權(quán):用戶掃描二維碼,授權(quán)登錄。
  4. 獲取授權(quán)碼:用戶授權(quán)后,微信會(huì)回調(diào)給開發(fā)者一個(gè)授權(quán)碼。
  5. 獲取用戶信息:使用授權(quán)碼獲取用戶的基本信息(如昵稱、頭像等)。
  6. 建立會(huì)話:將用戶信息與系統(tǒng)的會(huì)話綁定,完成登錄流程。

2. 前置準(zhǔn)備

確保你在微信開放平臺(tái)上配置了以下信息:

  • AppID 和 AppSecret:在“公眾號設(shè)置”頁面可以找到。
  • 授權(quán)回調(diào)域名:在開放平臺(tái)進(jìn)行授權(quán)配置。

3. Java 實(shí)現(xiàn)掃碼登錄

使用Spring Boot實(shí)現(xiàn)一個(gè)簡單的微信掃碼登錄后端接口:

導(dǎo)入依賴

pom.xml 中添加必要的依賴項(xiàng):

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-data-redis</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>com.fasterxml.jackson.core</groupId>
  11. <artifactId>jackson-databind</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-security</artifactId>
  16. </dependency>

代碼實(shí)現(xiàn)

  1. 配置微信相關(guān)信息

  1. @Configuration
  2. public class WeChatConfig {
  3. @Value("${wechat.appId}")
  4. private String appId;
  5. @Value("${wechat.appSecret}")
  6. private String appSecret;
  7. @Value("${wechat.redirectUri}")
  8. private String redirectUri;
  9. public String getAppId() {
  10. return appId;
  11. }
  12. public String getAppSecret() {
  13. return appSecret;
  14. }
  15. public String getRedirectUri() {
  16. return redirectUri;
  17. }
  18. }

  1. 生成二維碼

創(chuàng)建一個(gè)控制器來生成微信掃碼二維碼URL。

  1. @RestController
  2. @RequestMapping("/api/wechat")
  3. public class WeChatLoginController {
  4. @Autowired
  5. private WeChatConfig weChatConfig;
  6. @GetMapping("/login/qrcode")
  7. public ResponseEntity<String> getQRCode() {
  8. String url = "https://open.weixin.qq.com/connect/qrconnect" +
  9. "?appid=" + weChatConfig.getAppId() +
  10. "&redirect_uri=" + URLEncoder.encode(weChatConfig.getRedirectUri(), StandardCharsets.UTF_8) +
  11. "&response_type=code" +
  12. "&scope=snsapi_login" +
  13. "&state=STATE#wechat_redirect";
  14. return ResponseEntity.ok(url);
  15. }
  16. }

通過此接口可以生成微信掃碼登錄的二維碼URL。

  1. 回調(diào)接口

微信掃碼后會(huì)將用戶重定向到配置的回調(diào)URL,在回調(diào)中處理授權(quán)碼并獲取用戶信息。

  1. @GetMapping("/callback")
  2. public ResponseEntity<String> weChatCallback(@RequestParam("code") String code) {
  3. String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + weChatConfig.getAppId() +
  4. "&secret=" + weChatConfig.getAppSecret() +
  5. "&code=" + code +
  6. "&grant_type=authorization_code";
  7. RestTemplate restTemplate = new RestTemplate();
  8. String response = restTemplate.getForObject(accessTokenUrl, String.class);
  9. JSONObject json = new JSONObject(response);
  10. String accessToken = json.getString("access_token");
  11. String openId = json.getString("openid");
  12. // 獲取用戶信息
  13. String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId;
  14. String userInfoResponse = restTemplate.getForObject(userInfoUrl, String.class);
  15. // 返回或保存用戶信息
  16. return ResponseEntity.ok(userInfoResponse);
  17. }

  1. 會(huì)話管理與重定向

在獲取到用戶信息后,可以將用戶數(shù)據(jù)存入Redis(或數(shù)據(jù)庫),并生成一個(gè)登錄態(tài)。

  1. @Autowired
  2. private RedisTemplate<String, Object> redisTemplate;
  3. @PostMapping("/saveSession")
  4. public ResponseEntity<String> saveSession(@RequestBody Map<String, String> userInfo) {
  5. String sessionId = UUID.randomUUID().toString();
  6. redisTemplate.opsForValue().set(sessionId, userInfo);
  7. // 返回Session ID作為登錄憑證
  8. return ResponseEntity.ok(sessionId);
  9. }

4. 前端處理

在前端頁面中調(diào)用 /api/wechat/login/qrcode 接口,將二維碼顯示給用戶。當(dāng)用戶掃碼并完成授權(quán)后,前端可以獲取后端傳回的Session ID,表示登錄成功。

完整流程小結(jié)

  1. 訪問后端接口生成二維碼鏈接。
  2. 前端顯示二維碼,用戶掃碼后進(jìn)入微信授權(quán)頁面。
  3. 授權(quán)成功后,微信重定向至后端的 /callback
  4. 后端使用 code 獲取用戶信息,并保存會(huì)話信息(如Redis)。
  5. 返回前端Session ID作為登錄憑證。

使用以上代碼和步驟可以實(shí)現(xiàn)完整的微信公眾號掃碼登錄流程,前端就可以使用得到的Session ID來維護(hù)用戶登錄狀態(tài)啦。

由于演示案例涉及自己的賬號信息和微信開放平臺(tái)的私密信息,請根據(jù)自己的情況使用代碼案例,下課。微信掃碼登錄, Java后端實(shí)現(xiàn), Spring Boot, 微信公眾號, 微信開放平臺(tái), 二維碼生成, 用戶授權(quán), 會(huì)話管理

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號