Spring?Boot實(shí)現(xiàn)微信掃碼登錄功能流程分析
微信開(kāi)放平臺(tái):微信掃碼登錄功能
官方文檔:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
1. 授權(quán)流程說(shuō)明
微信OAuth3.0授權(quán)登錄讓微信用戶(hù)使用微信身份安全登錄第三方應(yīng)用或網(wǎng)站,在微信用戶(hù)授權(quán)登錄已接入微信OAuth3.0的第三方應(yīng)用后,第三方可以獲取到用戶(hù)的接口調(diào)用憑證(access_token),通過(guò)access_token可以進(jìn)行微信開(kāi)放平臺(tái)授權(quán)關(guān)系接口調(diào)用,從而可實(shí)現(xiàn)獲取微信用戶(hù)基本開(kāi)放信息和幫助用戶(hù)實(shí)現(xiàn)基礎(chǔ)開(kāi)放功能等。
微信OAuth3.0授權(quán)登錄目前支持authorization_code模式,適用于擁有server端的應(yīng)用授權(quán)。該模式整體流程為:
① 第三方發(fā)起微信授權(quán)登錄請(qǐng)求,微信用戶(hù)允許授權(quán)第三方應(yīng)用后,微信會(huì)拉起應(yīng)用或重定向到第三方網(wǎng)站,并且?guī)鲜跈?quán)臨時(shí)票據(jù)code參數(shù);
② 通過(guò)code參數(shù)加上AppID和AppSecret等,通過(guò)API換取access_token;
③ 通過(guò)access_token進(jìn)行接口調(diào)用,獲取用戶(hù)基本數(shù)據(jù)資源或幫助用戶(hù)實(shí)現(xiàn)基本操作。

第一步:請(qǐng)求CODE
第三方使用網(wǎng)站應(yīng)用授權(quán)登錄前請(qǐng)注意已獲取相應(yīng)網(wǎng)頁(yè)授權(quán)作用域(scope=snsapi_login),則可以通過(guò)在PC端打開(kāi)以下鏈接:https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
返回說(shuō)明
用戶(hù)允許授權(quán)后,將會(huì)重定向到redirect_uri的網(wǎng)址上,并且?guī)蟘ode和state參數(shù)
redirect_uri?code=CODE&state=STATE
若用戶(hù)禁止授權(quán),則重定向后不會(huì)帶上code參數(shù),僅會(huì)帶上state參數(shù)
redirect_uri?state=STATE
例如:登錄一號(hào)店網(wǎng)站應(yīng)用 https://passport.yhd.com/wechat/login.do 打開(kāi)后,一號(hào)店會(huì)生成state參數(shù),跳轉(zhuǎn)到 https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect 微信用戶(hù)使用微信掃描二維碼并且確認(rèn)登錄后,PC端會(huì)跳轉(zhuǎn)到 https://passport.yhd.com/wechat/callback.do?code=CODE&state=3d6be0a4035d839573b04816624a415e
第二步:通過(guò)code獲取access_token
通過(guò)code獲取access_token
返回說(shuō)明
正確的返回:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE",
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}錯(cuò)誤返回樣例:
{"errcode":40029,"errmsg":"invalid code"}- Appsecret 是應(yīng)用接口使用密鑰,泄漏后將可能導(dǎo)致應(yīng)用數(shù)據(jù)泄漏、應(yīng)用的用戶(hù)數(shù)據(jù)泄漏等高風(fēng)險(xiǎn)后果;存儲(chǔ)在客戶(hù)端,極有可能被惡意竊取(如反編譯獲取Appsecret);
- access_token 為用戶(hù)授權(quán)第三方應(yīng)用發(fā)起接口調(diào)用的憑證(相當(dāng)于用戶(hù)登錄態(tài)),存儲(chǔ)在客戶(hù)端,可能出現(xiàn)惡意獲取access_token 后導(dǎo)致的用戶(hù)數(shù)據(jù)泄漏、用戶(hù)微信相關(guān)接口功能被惡意發(fā)起等行為;
- refresh_token 為用戶(hù)授權(quán)第三方應(yīng)用的長(zhǎng)效憑證,僅用于刷新access_token,但泄漏后相當(dāng)于access_token 泄漏,風(fēng)險(xiǎn)同上。
建議將secret、用戶(hù)數(shù)據(jù)(如access_token)放在App云端服務(wù)器,由云端中轉(zhuǎn)接口調(diào)用請(qǐng)求。
第三步:通過(guò)access_token調(diào)用接口
獲取access_token后,進(jìn)行接口調(diào)用,有以下前提:
- access_token有效且未超時(shí);
- 微信用戶(hù)已授權(quán)給第三方應(yīng)用帳號(hào)相應(yīng)接口作用域(scope)。
對(duì)于接口作用域(scope),能調(diào)用的接口有以下:

2. 授權(quán)流程代碼
因?yàn)槲⑿砰_(kāi)放平臺(tái)的AppiD和APPSecret和微信公眾平臺(tái)的AppiD和AppSecret都是不同的,因此需要配置一下:
# 開(kāi)放平臺(tái)
wechat.open-app-id=wx6ad144e54af67d87
wechat.open-app-secret=91a2ff6d38a2bbccfb7e9f9079108e2e
@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {
//公眾號(hào)appid
private String mpAppId;
//公眾號(hào)appSecret
private String mpAppSecret;
//商戶(hù)號(hào)
private String mchId;
//商戶(hù)秘鑰
private String mchKey;
//商戶(hù)證書(shū)路徑
private String keyPath;
//微信支付異步通知
private String notifyUrl;
//開(kāi)放平臺(tái)id
private String openAppId;
//開(kāi)放平臺(tái)秘鑰
private String openAppSecret;
}
@Configuration
public class WechatOpenConfig {
@Autowired
private WechatAccountConfig accountConfig;
@Bean
public WxMpService wxOpenService() {
WxMpService wxOpenService = new WxMpServiceImpl();
wxOpenService.setWxMpConfigStorage(wxOpenConfigStorage());
return wxOpenService;
}
public WxMpConfigStorage wxOpenConfigStorage() {
WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();
wxMpInMemoryConfigStorage.setAppId(accountConfig.getOpenAppId());
wxMpInMemoryConfigStorage.setSecret(accountConfig.getOpenAppSecret());
return wxMpInMemoryConfigStorage;
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WeChatController {
private WxMpService wxMpService;
private WxMpService wxOpenService;
@GetMapping("/qrAuthorize")
public String qrAuthorize() {
//returnUrl就是用戶(hù)授權(quán)同意后回調(diào)的地址
String returnUrl = "http://heng.nat300.top/sell/wechat/qrUserInfo";
//引導(dǎo)用戶(hù)訪(fǎng)問(wèn)這個(gè)鏈接,進(jìn)行授權(quán)
String url = wxOpenService.buildQrConnectUrl(returnUrl, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode(returnUrl));
return "redirect:" + url;
//用戶(hù)授權(quán)同意后回調(diào)的地址,從請(qǐng)求參數(shù)中獲取code
@GetMapping("/qrUserInfo")
public String qrUserInfo(@RequestParam("code") String code) {
WxMpOAuth3AccessToken wxMpOAuth3AccessToken = new WxMpOAuth3AccessToken();
try {
//通過(guò)code獲取access_token
wxMpOAuth3AccessToken = wxOpenService.oauth3getAccessToken(code);
} catch (WxErrorException e) {
log.error("【微信網(wǎng)頁(yè)授權(quán)】{}", e);
throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
}
//從token中獲取openid
String openId = wxMpOAuth3AccessToken.getOpenId();
//這個(gè)地址可有可無(wú),反正只是為了拿到openid,但是如果沒(méi)有會(huì)報(bào)404錯(cuò)誤,為了好看隨便返回一個(gè)百度的地址
String returnUrl = "http://www.baidu.com";
log.info("openid={}", openId);
return "redirect:" + returnUrl + "?openid="+openId;請(qǐng)求路徑:在瀏覽器打開(kāi)
獲取了openid:openid=o9AREv7Xr22ZUk6BtVqw82bb6AFk

3. 用戶(hù)登錄和登出
@Controller
@RequestMapping("/seller")
public class SellerUserController {
@Autowired
private SellerService sellerService;
private StringRedisTemplate redisTemplate;
private ProjectUrlConfig projectUrlConfig;
@GetMapping("/login")
public ModelAndView login(@RequestParam("openid") String openid, HttpServletResponse response, Map<String, Object> map) {
//1. openid去和數(shù)據(jù)庫(kù)里的數(shù)據(jù)匹配
SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
if (sellerInfo == null) {
map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
map.put("url", "/sell/seller/order/list");
return new ModelAndView("common/error");
}
//2. 設(shè)置token至redis
String token = UUID.randomUUID().toString();
//設(shè)置token的過(guò)期時(shí)間
Integer expire = RedisConstant.EXPIRE;
redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);
//3. 設(shè)置token至cookie
CookieUtil.set(response, CookieConstant.TOKEN, token, expire);
return new ModelAndView("redirect:" + "http://heng.nat300.top/sell/seller/order/list");
}
@GetMapping("/logout")
public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) {
//1. 從cookie里查詢(xún)
Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
if (cookie != null) {
//2. 清除redis
redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
//3. 清除cookie
CookieUtil.set(response, CookieConstant.TOKEN, null, 0);
map.put("msg", ResultEnum.LOGOUT_SUCCESS.getMessage());
map.put("url", "/sell/seller/order/list");
return new ModelAndView("common/success", map);
}① 將上一步獲取到的openid存入數(shù)據(jù)庫(kù)

② 將授權(quán)后跳轉(zhuǎn)的地址改為登錄地址
//用戶(hù)授權(quán)同意后回調(diào)的地址,從請(qǐng)求參數(shù)中獲取code
@GetMapping("/qrUserInfo")
public String qrUserInfo(@RequestParam("code") String code) {
WxMpOAuth3AccessToken wxMpOAuth3AccessToken = new WxMpOAuth3AccessToken();
try {
//通過(guò)code獲取access_token
wxMpOAuth3AccessToken = wxOpenService.oauth3getAccessToken(code);
} catch (WxErrorException e) {
log.error("【微信網(wǎng)頁(yè)授權(quán)】{}", e);
throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());
}
//從token中獲取openid
String openId = wxMpOAuth3AccessToken.getOpenId();
//授權(quán)成功后跳轉(zhuǎn)到賣(mài)家系統(tǒng)的登錄地址
String returnUrl = "http://heng.nat300.top/sell/seller/login";
log.info("openid={}", openId);
return "redirect:" + returnUrl + "?openid="+openId;
}③ 在瀏覽器請(qǐng)求這個(gè)鏈接:
第三應(yīng)用請(qǐng)求使用微信掃碼登錄,而不是使用本網(wǎng)站的密碼:

用戶(hù)同意授權(quán)后登入第三方應(yīng)用的后臺(tái)管理系統(tǒng):

4. Spring AOP校驗(yàn)用戶(hù)有沒(méi)有登錄
@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() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//查詢(xún)cookie
Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
//如果cookie中沒(méi)有token說(shuō)明已經(jīng)登出或者根本沒(méi)有登錄
if (cookie == null) {
log.warn("【登錄校驗(yàn)】Cookie中查不到token");
//校驗(yàn)不通過(guò),拋出異常
throw new SellerAuthorizeException();
}
//去redis里查詢(xún)
String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
//如果redis中沒(méi)有對(duì)應(yīng)的openid,同樣表示登出或者根本沒(méi)有登錄
if (StringUtils.isEmpty(tokenValue)) {
log.warn("【登錄校驗(yàn)】Redis中查不到token");
}
}5. 攔截登錄校驗(yàn)不通過(guò)拋出的異常
攔截及登錄校驗(yàn)不通過(guò)的異常,讓其跳轉(zhuǎn)到登錄頁(yè)面,掃碼登錄
@ControllerAdvice
public class SellExceptionHandler {
//攔截登錄異常
@ExceptionHandler(value = SellerAuthorizeException.class) public ModelAndView handlerAuthorizeException() {
//攔截異常后,跳轉(zhuǎn)到登錄界面
return new ModelAndView("redirect:".concat("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(value = SellException.class) @ResponseBody public ResultVO handlerSellerException(SellException e) {
return ResultVOUtil.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(value = ResponseBankException.class) @ResponseStatus(HttpStatus.FORBIDDEN) public void handleResponseBankException() {
}
}到此這篇關(guān)于Spring Boot 實(shí)現(xiàn)微信掃碼登錄的文章就介紹到這了,更多相關(guān)Spring Boot微信掃碼登錄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatis返回map結(jié)果集@MapKey使用的場(chǎng)景分析
這篇文章主要介紹了mybatis返回map結(jié)果集@MapKey使用的場(chǎng)景分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
SpringBoot mybatis 實(shí)現(xiàn)多級(jí)樹(shù)形菜單的示例代碼
這篇文章主要介紹了SpringBoot mybatis 實(shí)現(xiàn)多級(jí)樹(shù)形菜單的示例代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05
SpringBoot原理之自動(dòng)配置機(jī)制詳解
Springboot遵循“約定優(yōu)于配置”的原則,使用注解對(duì)一些常規(guī)的配置項(xiàng)做默認(rèn)配置,減少或不使用xml配置,讓你的項(xiàng)目快速運(yùn)行起來(lái),下面這篇文章主要給大家介紹了關(guān)于SpringBoot原理之自動(dòng)配置機(jī)制的相關(guān)資料,需要的朋友可以參考下2021-11-11
SpringBoot文件上傳大小設(shè)置方式(yml中配置)
這篇文章主要介紹了SpringBoot文件上傳大小設(shè)置方式(yml中配置),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
使用Spring Initializr方式如何快速構(gòu)建Spring Boot項(xiàng)目
Spring lnitializr是一個(gè)Web應(yīng)用,它提供了一個(gè)基本的項(xiàng)目結(jié)構(gòu),能夠幫助我們快速構(gòu)建一個(gè)基礎(chǔ)的Spring Boot項(xiàng)目,本文分步驟講解如何使用Spring Initializr方式構(gòu)建Spring Boot項(xiàng)目,感興趣的朋友跟隨小編一起看看吧2023-08-08
jcrop 網(wǎng)頁(yè)截圖工具(插件)開(kāi)發(fā)
今天給大家介紹一下一個(gè)web 中經(jīng)常會(huì)用到的截圖(如:頭像等)工具,需要的朋友可以了解下2012-11-11

