In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian introduces in detail "how to achieve Wechat code scan login function by Spring Boot" with detailed content, clear steps and proper handling of details. I hope that this article "how to achieve Wechat code scan login function with Spring Boot" can help you solve your doubts.
1. Authorization process description
Wechat OAuth4.0 authorization login allows Wechat users to use Wechat identity to securely log in to third-party applications or websites. After Wechat users are authorized to log in to third-party applications that have been connected to Wechat OAuth4.0, the third party can obtain the user's API call credential (access_token), and the Wechat open platform authorization relationship API can be called through access_token. Thus, it is possible to obtain the basic open information of Wechat users and help users to achieve basic open functions.
Wechat OAuth4.0 authorization login currently supports authorization_code mode, which is suitable for applications with server authorization. The overall process of the model is:
After the ① third party initiates the Wechat authorization login request, and after the Wechat user allows the authorization of the third party application, Wechat will pull the application or redirect to the third party website with the authorization temporary ticket code parameter
② uses code parameters plus AppID and AppSecret to exchange for access_token through API.
③ makes interface calls through access_token to obtain users' basic data resources or help users to achieve basic operations.
Step 1: request CODE
Before a third party logs in with the website application authorization, please note that you have obtained the corresponding web page authorization scope (scope=snsapi_login), you can open the following link on the PC side: https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
Return description
Once authorization is allowed, the user will be redirected to the URL of redirect_uri with code and state parameters
Redirect_uri?code=CODE&state=STATE
If authorization is prohibited by the user, the code parameter will not be taken with the redirect, only the state parameter will be taken.
Redirect_uri?state=STATE
For example, after logging in to the No.1 store website and opening the application https://passport.yhd.com/wechat/login.do, the No.1 store will generate a state parameter and jump to 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 Wechat users to scan the QR code using Wechat and confirm login. The PC side will jump to https://passport.yhd.com/wechat/callback.do?code=CODE&state=3d6be0a4035d839573b04816624a415e
Step 2: get access_token through code
Obtain access_token through code
Https://api.weixin.qq.com/sns/oauth4/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
Return description
Correct return:
{"access_token": "ACCESS_TOKEN", "expires_in": 7200, "refresh_token": "REFRESH_TOKEN", "openid": "OPENID", "scope": "SCOPE", "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"}
Sample error return:
{"errcode": 40029, "errmsg": "invalid code"}
Appsecret is the key used by the application interface, which may lead to high-risk consequences such as application data disclosure, application user data leakage and so on. When stored in the client, it is very likely to be maliciously stolen (such as decompilation to obtain Appsecret)
Access_token authorizes the credentials of the third-party application to initiate API calls (equivalent to the user's login state), which are stored on the client. There may be behaviors such as user data leakage caused by malicious acquisition of access_token, malicious initiation of user Wechat-related interface functions, etc.
Refresh_token is a long-term credential for users to authorize third-party applications. It is only used to refresh access_token, but the leakage is equivalent to access_token leakage. The risk is the same as above.
It is recommended to put secret and user data (such as access_token) on the App cloud server, where the request is called by the cloud transfer API.
Step 3: call the interface through access_token
After the access_token is obtained, the API is called with the following prerequisites:
Access_token is valid and does not time out
Wechat users have been authorized to the corresponding interface scope (scope) of the third-party application account.
For interface scope (scope), the following interfaces can be called:
two。 Authorization process code
Because the AppiD and APPSecret of Wechat open platform and the AppiD and AppSecret of Wechat public platform are different, you need to configure:
# Open platform wechat.open-app-id=wx6ad144e54af67d87wechat.open-app-secret=91a2ff6d38a2bbccfb7e9f9079108e2e@Data@Component@ConfigurationProperties (prefix = "wechat") public class WechatAccountConfig {/ / official appid private String mpAppId; / / official appSecret private String mpAppSecret; / / merchant private String mchId; / / merchant secret key private String mchKey; / / merchant certificate path private String keyPath; / / WeChat Pay asynchronously notifies private String notifyUrl / / Open platform id private String openAppId; / / Open platform key private String openAppSecret;} @ Configurationpublic 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") @ Slf4jpublic class WeChatController {private WxMpService wxMpService; private WxMpService wxOpenService; @ GetMapping ("/ qrAuthorize") public String qrAuthorize () {/ / returnUrl is the callback address String returnUrl = "http://heng.nat300.top/sell/wechat/qrUserInfo";" after the user's authorization is agreed. / / lead the user to this link, authorize String url = wxOpenService.buildQrConnectUrl (returnUrl, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode (returnUrl)); return "redirect:" + url; / / the address of the callback after the user's authorization is agreed, and obtain code @ GetMapping ("/ qrUserInfo") public String qrUserInfo (@ RequestParam ("code") String code) {WxMpOAuth4AccessToken wxMpOAuth4AccessToken = new WxMpOAuth4AccessToken () from the request parameters. Try {/ / get access_token wxMpOAuth4AccessToken = wxOpenService.oauth4getAccessToken (code) through code;} catch (WxErrorException e) {log.error ("[Wechat webpage authorization] {}", e); throw new SellException (ResultEnum.WECHAT_MP_ERROR.getCode (), e.getError () .getErrorMsg ()) } / / get openid String openId = wxMpOAuth4AccessToken.getOpenId () from token; / / this address is optional, anyway, just to get openid, but if not, you will report a 404 error. In order to look good, you can return a Baidu address String returnUrl = "http://www.baidu.com"; log.info (" openid= {} ", openId). Return "redirect:" + returnUrl + "? openid=" + openId
Request path: open in browser
Https://open.weixin.qq.com/connect/qrconnect?appid=wx6ad144e54af67d87&redirect_uri=http%3A%2F%2Fsell.springboot.cn%2Fsell%2Fqr%2FoTgZpwenC6lwO2eTDDf_-UYyFtqI&response_type=code&scope=snsapi_login&state=http%3A%2F%2Fheng.nat300.top%2Fsell%2Fwechat%2FqrUserInfo
Got openid:openid=o9AREv7Xr22ZUk6BtVqw82bb6AFk
3. User logs in and logs out @ 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 map) {/ / 1. Openid to match the data in the database 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. Set token to redis String token = UUID.randomUUID (). ToString (); / / set the expiration time of token Integer expire = RedisConstant.EXPIRE; redisTemplate.opsForValue (). Set (String.format (RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS); / / 3. Set token to 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 map) {/ / 1. Query Cookie cookie = CookieUtil.get (request, CookieConstant.TOKEN) from cookie; if (cookie! = null) {/ / 2. Clear redis redisTemplate.opsForValue (). GetOperations (). Delete (String.format (RedisConstant.TOKEN_PREFIX, cookie.getValue (); / / 3. Clear 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);}
① stores the openid obtained in the previous step in the database
② changes the address redirected after authorization to the login address.
/ / get code @ GetMapping ("/ qrUserInfo") public String qrUserInfo (@ RequestParam ("code") String code) {WxMpOAuth4AccessToken wxMpOAuth4AccessToken = new WxMpOAuth4AccessToken () from the request parameters; try {/ / get access_token wxMpOAuth4AccessToken = wxOpenService.oauth4getAccessToken (code) through code } catch (WxErrorException e) {log.error ("[Wechat Web license] {}", e); throw new SellException (ResultEnum.WECHAT_MP_ERROR.getCode (), e.getError (). GetErrorMsg ());} / / get openid String openId = wxMpOAuth4AccessToken.getOpenId () from token / / after successful authorization, jump to the login address of the seller's system String returnUrl = "http://heng.nat300.top/sell/seller/login"; log.info (" openid= {} ", openId); return" redirect: "+ returnUrl +"? openid= "+ openId;}
③ requests this link in the browser:
Https://open.weixin.qq.com/connect/qrconnect?appid=wx6ad144e54af67d87&redirect_uri=http%3A%2F%2Fsell.springboot.cn%2Fsell%2Fqr%2FoTgZpwenC6lwO2eTDDf_-UYyFtqI&response_type=code&scope=snsapi_login&state=http%3a%2f%2fheng.nat300.top%2fsell%2fwechat%2fqrUserInfo
The third application requests to log in using Wechat scan code instead of using the password of this website:
After the user agrees to the authorization, log in to the background management system of the third-party application:
4. Spring AOP verifies whether the user has logged in to @ Aspect@Component@Slf4jpublic 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 (); / / query cookie Cookie cookie = CookieUtil.get (request, CookieConstant.TOKEN) / / if there is no token in cookie that indicates that if has been logged out or has not logged in at all (cookie = = null) {log.warn ("[login verification] token is not found in Cookie"); / / if the verification fails, throw an exception throw new SellerAuthorizeException () } / / query String tokenValue = redisTemplate.opsForValue (). Get (String.format (RedisConstant.TOKEN_PREFIX, cookie.getValue () in redis; / / if there is no corresponding openid in redis, it also means that you are logged out or have not logged in to if (StringUtils.isEmpty (tokenValue)) {log.warn ("[login verification] token not found in Redis");}} 5. Intercept exceptions that the login check fails to throw
Block and log in failed exceptions and let them jump to the login page and scan the code to log in.
@ ControllerAdvicepublic class SellExceptionHandler {/ / intercept login exception @ ExceptionHandler (value = SellerAuthorizeException.class) public ModelAndView handlerAuthorizeException () {/ / after blocking exception Jump to the login interface 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 () {}} read here, this article "how to achieve Wechat scan login function with Spring Boot" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it. If you want to know more about the article, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.