How to Build a WeChat QR Code Login with Spring Boot: Step‑by‑Step Guide
This article walks through the complete process of implementing WeChat QR code login using a Java Spring Boot backend, covering prerequisite configuration, Maven dependencies, configuration classes, QR code generation, callback handling, session storage in Redis, and frontend integration.
Overview
This guide shows how to implement WeChat public‑account QR‑code login with a Spring Boot backend. The flow consists of generating a QR‑code URL, handling the OAuth callback, retrieving user information, storing a session in Redis, and returning a session identifier to the frontend.
Prerequisites
AppID and AppSecret – obtain from the WeChat public‑account settings.
Authorized callback domain – configure in the WeChat Open Platform and set the redirect URI that the backend will expose.
Maven Dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>Configuration
@Configuration
public class WeChatConfig {
@Value("${wechat.appId}")
private String appId;
@Value("${wechat.appSecret}")
private String appSecret;
@Value("${wechat.redirectUri}")
private String redirectUri;
public String getAppId() { return appId; }
public String getAppSecret() { return appSecret; }
public String getRedirectUri() { return redirectUri; }
}QR Code Generation Endpoint
@RestController
@RequestMapping("/api/wechat")
public class WeChatLoginController {
@Autowired
private WeChatConfig weChatConfig;
@GetMapping("/login/qrcode")
public ResponseEntity<String> getQRCode() {
String url = "https://open.weixin.qq.com/connect/qrconnect" +
"?appid=" + weChatConfig.getAppId() +
"&redirect_uri=" + URLEncoder.encode(weChatConfig.getRedirectUri(), StandardCharsets.UTF_8) +
"&response_type=code" +
"&scope=snsapi_login" +
"&state=STATE#wechat_redirect";
return ResponseEntity.ok(url);
}Callback Handling Endpoint
@GetMapping("/callback")
public ResponseEntity<String> weChatCallback(@RequestParam("code") String code) {
// Exchange code for access token
String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
weChatConfig.getAppId() +
"&secret=" + weChatConfig.getAppSecret() +
"&code=" + code +
"&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
String tokenResponse = restTemplate.getForObject(accessTokenUrl, String.class);
JSONObject tokenJson = new JSONObject(tokenResponse);
String accessToken = tokenJson.getString("access_token");
String openId = tokenJson.getString("openid");
// Retrieve user info
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" +
accessToken + "&openid=" + openId;
String userInfo = restTemplate.getForObject(userInfoUrl, String.class);
return ResponseEntity.ok(userInfo);
}Session Management
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@PostMapping("/saveSession")
public ResponseEntity<String> saveSession(@RequestBody Map<String, String> userInfo) {
String sessionId = UUID.randomUUID().toString();
redisTemplate.opsForValue().set(sessionId, userInfo);
return ResponseEntity.ok(sessionId);
}
}Frontend Integration
The client calls /api/wechat/login/qrcode to obtain the QR‑code URL, displays the image, and after the user scans and authorises, the backend returns a session ID via /saveSession. The frontend stores this ID as the login credential.
Full Flow Summary
Frontend requests /api/wechat/login/qrcode and receives a URL that points to the WeChat QR‑code page.
User scans the QR code with the WeChat app and authorises the login.
WeChat redirects the user to the configured /callback endpoint with a code query parameter.
The backend exchanges the code for an access_token and openid, then calls the user‑info API to obtain profile data.
User data is stored in Redis and a UUID session identifier is generated.
The session identifier is returned to the frontend, which uses it to maintain the authenticated session.
Java Architecture Stack
Dedicated to original, practical tech insights—from skill advancement to architecture, front‑end to back‑end, the full‑stack path, with Wei Ge guiding you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
