WeChat Open Platform QR Code Login Integration with Spring Boot

This article explains how to implement WeChat QR code login using OAuth2.0 in a Spring Boot backend, detailing the authorization flow, required configuration, code examples for obtaining access tokens, user authentication, Spring AOP login verification, and exception handling to securely integrate WeChat login into a Java application.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
WeChat Open Platform QR Code Login Integration with Spring Boot

WeChat Open Platform provides a QR code login feature based on OAuth2.0, allowing users to authenticate with their WeChat credentials and grant access to third‑party applications.

1. Authorization Process Overview

When a user authorizes a third‑party app, WeChat redirects to the app with a temporary code parameter. The app exchanges this code together with its AppID and AppSecret for an access_token, which can then be used to call WeChat APIs and retrieve basic user information.

Step 1: Request CODE

Open the following URL (replace APPID, REDIRECT_URI, SCOPE, and STATE as needed):

https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

After the user authorizes, WeChat redirects to redirect_uri with code and state. If the user denies, only state is returned.

Step 2: Exchange CODE for access_token

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

Successful response example:

{
  "access_token":"ACCESS_TOKEN",
  "expires_in":7200,
  "refresh_token":"REFRESH_TOKEN",
  "openid":"OPENID",
  "scope":"SCOPE",
  "unionid":"o6_bmasdasdsad6_2sgVt7hMZOPfL"
}

Typical error response:

{"errcode":40029,"errmsg":"invalid code"}

Step 3: Use access_token to call APIs

Ensure the access_token is valid and the user has granted the required scope before invoking any protected API.

2. Configuration Code

Define properties for the Open Platform credentials:

# Open Platform
wechat.open-app-id=wx6ad144e54af67d87
wechat.open-app-secret=91a2ff6d38a2bbccfb7e9f9079108e2e

Spring beans for WeChat SDK:

@Configuration
public class WechatOpenConfig {
    @Autowired
    private WechatAccountConfig accountConfig;

    @Bean
    public WxMpService wxOpenService() {
        WxMpService wxOpenService = new WxMpServiceImpl();
        wxOpenService.setWxMpConfigStorage(wxOpenConfigStorage());
        return wxOpenService;
    }

    @Bean
    public WxMpConfigStorage wxOpenConfigStorage() {
        WxMpInMemoryConfigStorage storage = new WxMpInMemoryConfigStorage();
        storage.setAppId(accountConfig.getOpenAppId());
        storage.setSecret(accountConfig.getOpenAppSecret());
        return storage;
    }
}

Controller handling QR authorization and callback:

@Controller
@RequestMapping("/wechat")
@Slf4j
public class WeChatController {
    @Autowired
    private WxMpService wxOpenService;

    @GetMapping("/qrAuthorize")
    public String qrAuthorize() {
        String returnUrl = "http://example.com/qrUserInfo";
        String url = wxOpenService.buildQrConnectUrl(returnUrl, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode(returnUrl));
        return "redirect:" + url;
    }

    @GetMapping("/qrUserInfo")
    public String qrUserInfo(@RequestParam("code") String code) {
        WxMpOAuth2AccessToken token = wxOpenService.oauth2getAccessToken(code);
        String openId = token.getOpenId();
        return "redirect:http://example.com/login?openid=" + openId;
    }
}

3. User Login and Logout Logic

Login controller stores a generated token in Redis and sets it as a cookie; logout clears both Redis and the cookie.

4. Spring AOP Login Verification

@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("execution(public * com.hh.controller.Seller*.*(..)) && !execution(public * com.hh.controller.SellerUserController.*(..))")
    public void verify() {}

    @Before("verify()")
    public void doVerify() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie == null) throw new SellerAuthorizeException();
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)) throw new SellerAuthorizeException();
    }
}

5. Exception Handling for Unauthorized Access

@ControllerAdvice
public class SellExceptionHandler {
    @ExceptionHandler(SellerAuthorizeException.class)
    public ModelAndView handlerAuthorizeException() {
        return new ModelAndView("redirect:" +
            "https://open.weixin.qq.com/connect/qrconnect?appid=wx6ad144e54af67d87&redirect_uri=http%3A%2F%2Fsell.springboot.cn%2Fsell%2Fqr%2F" +
            "oTgZpwenC6lwO2eTDDf_-UYyFtqI&response_type=code&scope=snsapi_login&state=http%3a%2f%2fheng.nat300.top%2fsell%2fwechat%2fqrUserInfo");
    }
    @ExceptionHandler(SellException.class)
    @ResponseBody
    public ResultVO handlerSellerException(SellException e) {
        return ResultVOUtil.error(e.getCode(), e.getMessage());
    }
}

The article also includes screenshots of the login flow and promotional links, but the core technical content focuses on integrating WeChat QR login into a Java Spring backend.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Spring BootSecurityOAuth2WeChatQR login
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.