微信扫码登录很难吗?5步帮你搞定( 二 )


# 开放平台wechat.open-app-id=wx6ad144e54af67d87wechat.open-app-secret=91a2ff6d38a2bbccfb7e9f9079108e2e@Data@Component@ConfigurationProperties(prefix = "wechat")public class WechatAccountConfig {//公众号appidprivate String mpAppId;//公众号appSecretprivate String mpAppSecret;//商户号private String mchId;//商户秘钥private String mchKey;//商户证书路径private String keyPath;//微信支付异步通知private String notifyUrl;//开放平台idprivate String openAppId;//开放平台秘钥private String openAppSecret;}@Configurationpublic class WechatOpenConfig {@Autowiredprivate WechatAccountConfig accountConfig;@Beanpublic WxMpService wxOpenService() {WxMpService wxOpenService = new WxMpServiceImpl();wxOpenService.setWxMpConfigStorage(wxOpenConfigStorage());return wxOpenService;}@Beanpublic WxMpConfigStorage wxOpenConfigStorage() {WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();wxMpInMemoryConfigStorage.setAppId(accountConfig.getOpenAppId());wxMpInMemoryConfigStorage.setSecret(accountConfig.getOpenAppSecret());return wxMpInMemoryConfigStorage;}}@Controller@RequestMapping("/wechat")@Slf4jpublic class WeChatController {@Autowiredprivate WxMpService wxMpService;@Autowiredprivate WxMpService wxOpenService;@GetMapping("/qrAuthorize")public String qrAuthorize() {//returnUrl就是用户授权同意后回调的地址String returnUrl = "http://heng.nat300.top/sell/wechat/qrUserInfo";//引导用户访问这个链接 , 进行授权String url = wxOpenService.buildQrConnectUrl(returnUrl, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode(returnUrl));return "redirect:" + url;}//用户授权同意后回调的地址 , 从请求参数中获取code@GetMapping("/qrUserInfo")public String qrUserInfo(@RequestParam("code") String code) {WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();try {//通过code获取access_tokenwxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code);} catch (WxErrorException e) {log.error("【微信网页授权】{}", e);throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg());}//从token中获取openidString openId = wxMpOAuth2AccessToken.getOpenId();//这个地址可有可无 , 反正只是为了拿到openid , 但是如果没有会报404错误 , 为了好看随便返回一个百度的地址StringreturnUrl = "http://www.baidu.com";log.info("openid={}", openId);return "redirect:" + returnUrl + "?openid="+openId;}}请求路径:在浏览器打开

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
获取了openid:openid=
o9AREv7Xr22ZUk6BtVqw82bb6AFk
微信扫码登录很难吗?5步帮你搞定

文章插图
 
3. 用户登录和登出
@Controller@RequestMapping("/seller")public class SellerUserController {@Autowiredprivate SellerService sellerService;@Autowiredprivate StringredisTemplate redisTemplate;@Autowiredprivate ProjectUrlConfig projectUrlConfig;@GetMapping("/login")public ModelAndView login(@RequestParam("openid") String openid,HttpServletResponse response,Map<String, Object> map) {//1. openid去和数据库里的数据匹配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. 设置token至redisString token = UUID.randomUUID().toString();//设置token的过期时间Integer expire = RedisConstant.EXPIRE;redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);//3. 设置token至cookieCookieUtil.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里查询Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);if (cookie != null) {//2. 清除redisredisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));//3. 清除cookieCookieUtil.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);}}


推荐阅读