申请测试账号:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
https://open.weixin.qq.com/connect/oauth2/authorize?appid=***&redirect_uri=http://186***4.iask.in/sell/weixin/auth&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
@Slf4j @RestController @RequestMapping("weixin") public class WeixinController { @GetMapping("auth") public void auth(@RequestParam("code") String code) { log.info("进入验证"); log.info("code={}", code); String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx111f1b7437e708dd&secret=e12860f0ce3d177f39e2160a0c8286c1&code=" + code + "&grant_type=authorization_code"; RestTemplate restTemplate = new RestTemplate(); String response=restTemplate.getForObject(url,String.class); log.info("response={}",response); }
<dependency>
<groupId>com.github.binarywanggroupId>
<artifactId>weixin-java-mpartifactId>
<version>2.9.0version>
dependency>
wechat: appId: wx***dd appSecret: e1286***86c1
@Component @ConfigurationProperties(prefix = "wechat") public class WeChatAccountConfig { //省略set get,(导入application配置) private String appId; private String appSecret; }
@Component public class WeChatMpConfig { @Autowired private WeChatAccountConfig accountConfig; @Bean public WxMpService wxMpService(){ WxMpService wxMpService=new WxMpServiceImpl(); wxMpService.setWxMpConfigStorage(wxMpConfigStorage()); return wxMpService; } @Bean public WxMpConfigStorage wxMpConfigStorage(){ WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage=new WxMpInMemoryConfigStorage(); wxMpInMemoryConfigStorage.setAppId(accountConfig.getAppId()); wxMpInMemoryConfigStorage.setSecret(accountConfig.getAppSecret()); return wxMpInMemoryConfigStorage; } }
@Slf4j @RequestMapping("wechat") @Controller public class WeChatController { @Autowired private WxMpService wxMpService; @GetMapping("authorize") public String authorize(){ //1.配置 //2.调用方法 String url="http://186***3bi4.iask.in/sell/wechat/userInfo"; String redirectUrl=wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_BASE,null); log.info("【微信网页授权】获取code,result={}",redirectUrl); return "redirect:"+redirectUrl; } @GetMapping("userInfo") public void userInfo(@RequestParam("code")String code){ WxMpOAuth2AccessToken wxMpOAuth2AccessToken; try { wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code); }catch (WxErrorException e){ log.error("【微信网页授权】{}",e); throw new SellException(ErrorEnum.WX_MP_ERROR.getCode(),e.getError().getErrorMsg()); } String openid=wxMpOAuth2AccessToken.getOpenId(); log.info("openid={}",openid); } }