1、映射配置文件
@Data @Component @ConfigurationProperties(prefix = "wx.mp") public class WxMpProperties { /** * 设置微信公众号的appid */ private String appId; /** * 设置微信公众号的app secret */ private String secret; /** * 设置微信公众号的token */ private String token; /** * 设置微信公众号的EncodingAESKey */ private String aesKey; }
2、微信配置信息
@Configuration @Slf4j public class WxConfig { @Autowired private WxMpProperties wxMpProperties; @Autowired private RedisTemplate redisTemplate; @Bean public WxMpService wxMpService() { RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); WxRedisOps redisOps = new RedisTemplateWxRedisOps(new StringRedisTemplate(factory)); WxMpRedisConfigImpl configStorage = new WxMpRedisConfigImpl(redisOps, Redis.getProjectName()); configStorage.setAppId(wxMpProperties.getAppId()); configStorage.setSecret(wxMpProperties.getSecret()); configStorage.setToken(wxMpProperties.getToken()); configStorage.setAesKey(wxMpProperties.getAesKey()); WxMpService service = new WxMpServiceImpl(); service.setWxMpConfigStorage(configStorage); log.info("微信公众号初始化完成..."); return service; } }
3、授权获取code
let flag = confirm("该功能需要获取您的头像、昵称信息、openId"); if (flag) { let href = window.location.href; let redirect = href.indexOf("?") ? href.split("?")[0] : href; let appid = "**************"; let api = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(redirect) + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; window.location.href = api;
}
$(function () { let code = getQueryString('code'); })
//获取url中的参数 function getQueryString(name) { let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); let r = window.location.search.substr(1).match(reg); return r == null ? '' : unescape(r[2]) }
4、通过code获取用户基本信息
WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code); WxOAuth2UserInfo userInfo = wxMpService.getOAuth2Service().getUserInfo(accessToken, "zh_CN");
通过userInfo可以获取用户openid、图像等基本信息
userInfo.getOpenid();//获取oopenid
Base64.getEncoder().encodeToString(userInfo.getNickname().getBytes());//获取昵称
userInfo.getHeadImgUrl();//获取图像
标签:code,configStorage,微信,private,获取,href,let,授权 From: https://www.cnblogs.com/person008/p/17089680.html