12.18 微信扫码获取openid与登陆
官方文档: https://open.weixin.qq.com/
1.先获取code
1-1 配置项目配置文件
wechat: mpAppId: wxd898fcb01713c658 mpAppSecret: 47ccc303338cee6e62894fxxxxxxxxxxx openAppId: wx6ad144e54af67d87///////// openAppSecret: 91a2ff6d38a2bbccfb7e9f9079108e2e/////////配置密钥
1-2 配置相应的配置文件
Data @Component @ConfigurationProperties(prefix = "wechat") public class WechatAccountConfig { /** * 公众平台id */ private String mpAppId; /** * 公众平台密钥 */ private String mpAppSecret; /** * 开放平台id */ private String openAppId; /** * 开放平台密钥 */ private String openAppSecret; /** * 商户号 */ private String mchId; /** * 商户密钥 */ private String mchKey; /** * 商户证书路径 */ private String keyPath; /** * 微信支付异步通知地址 */ private String notifyUrl; /** * 微信模版id */ private Map<String, String> templateId; }
1-3开放平台文件配置
@Component 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 wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage(); wxMpInMemoryConfigStorage.setAppId(accountConfig.getOpenAppId()); wxMpInMemoryConfigStorage.setSecret(accountConfig.getOpenAppSecret()); return wxMpInMemoryConfigStorage; } }
1-4 controller,并配置同意的Url配置文件
url配置文件
@Data @ConfigurationProperties(prefix = "projectUrl") @Component public class ProjectUrlConfig { /** * 微信公众平台授权url */ public String wechatMpAuthorize; /** * 微信开放平台授权url */ public String wechatOpenAuthorize; /** * 点餐系统 */ public String sell; }
项目配置文件
projectUrl: wechatMpAuthorize: http://sell.natapp4.cc wechatOpenAuthorize: http://sell.natapp4.cc sell: http://sell.natapp4.cc
@Controller @RequestMapping("/wechat") @Slf4j public class WechatController { @Autowired private WxMpService wxMpService; @Autowired private WxMpService wxOpenService; @Autowired private ProjectUrlConfig projectUrlConfig; @GetMapping("/qrAuthorize") public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) { String url = projectUrlConfig.getWechatOpenAuthorize() + "/sell/wechat/qrUserInfo"; String redirectUrl = wxOpenService.buildQrConnectUrl(url, WxConsts.QRCONNECT_SCOPE_SNSAPI_LOGIN, URLEncoder.encode(returnUrl)); return "redirect:" + redirectUrl; } @GetMapping("/qrUserInfo") public String qrUserInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl) { WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken(); try { wxMpOAuth2AccessToken = wxOpenService.oauth2getAccessToken(code); } catch (WxErrorException e) { log.error("【微信网页授权】{}", e); throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(), e.getError().getErrorMsg()); } log.info("wxMpOAuth2AccessToken={}", wxMpOAuth2AccessToken); String openId = wxMpOAuth2AccessToken.getOpenId(); return "redirect:" + returnUrl + "?openid=" + openId; } }
2.登陆
2-1controller创建登陆方法
步骤://1. openid去和数据库里的数据匹配
2. 设置token至redis:[
使用redis步骤:
1.引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.在controller里面引入
@Autowired private StringRedisTemplate redisTemplate;
3.在方法里
redisTepla.opsForValue().set("abc","1111111");//告诉redic调用并set key-value
]
/3. 设置token至cookie
controller层
注意:uuid过期时间类
/** * redis常量 * Created by 廖师兄 * 2017-07-30 16:22 */ public interface RedisConstant { String TOKEN_PREFIX = "token_%s"; Integer EXPIRE = 7200; //2小时 }
cookie常量类
public interface CookieConstant { String TOKEN = "token"; Integer EXPIRE = 7200; }
所需
public class CookieUtil { /** * 设置 * @param response * @param name * @param value * @param maxAge */ public static void set(HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setMaxAge(maxAge); response.addCookie(cookie); }
@Controller @RequestMapping("/seller") public class SellerUserController { @Autowired private SellerService sellerService; @Autowired private StringRedisTemplate redisTemplate; @Autowired private 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至redis String token = UUID.randomUUID().toString();//uuid通用唯一识别码 Integer expire = RedisConstant.EXPIRE;//uuid过期时间 redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS); //3. 设置token至cookie CookieUtil.set(response, CookieConstant.TOKEN, token, expire); return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list"); } }
3.退出登陆
思路:清楚redis存值和cookie 步骤:1)从cookie里面查询 2).清除redis 3).清除cookie
查询cookie
public class CookieUtil { /** * 获取cookie * @param request * @param name * @return */ public static Cookie get(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = readCookieMap(request); if (cookieMap.containsKey(name)) { return cookieMap.get(name); }else { return null; } } /** * 将cookie封装成Map * @param request * @return */ private static Map<String, Cookie> readCookieMap(HttpServletRequest request) { Map<String, Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie: cookies) { cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } }
controller层方法
@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. 清除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); }