记得访问的是 微信-开放平台
整个流程和微信授权几乎一样,但是要注意的是,AppId与AppSecret是不一样的。
首先先配置微信开放平台的账号
在WeChatAccountConfig.java中增加相应的配置(因为之前已经完成过授权的开发了)。
同授权一样,将配置好微信开放平台WechatOpenConfig.java
@Component
public class WechatOpenConfig {
@Autowired
private WechatAccountConfig wechatAccountConfig;
@Bean
public WxMpService wxOpenService(){
WxMpService wxOpenService = new WxMpServiceImpl();
wxOpenService.setWxMpConfigStorage(wxOpenConfigStorage());
return wxOpenService;
}
@Bean
public WxMpConfigStorage wxOpenConfigStorage(){
WxMpInMemoryConfigStorage wxMpInMemoryConfigStorage = new WxMpInMemoryConfigStorage();
wxMpInMemoryConfigStorage.setAppId(wechatAccountConfig.getOpenAppId());
wxMpInMemoryConfigStorage.setSecret(wechatAccountConfig.getOpenAppSecret());
return wxMpInMemoryConfigStorage;
}
}
WxMpService是配置了看Github上的SDK:https://github.com/Wechat-Group/WxJava。在公众号开发-支付的文章中有说明,不再赘述。
再去WechatController中调用wxOpenService
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {
@Autowired
private WxMpService wxOpenService;
@GetMapping("/qrAuthorize")
public String qrAuthorize(@RequestParam("returnUrl") String returnUrl) {
String url = "http://sell35.natapp1.cc/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;
}
}
当访问
"/wechat/qrAuthorize"
这个链接时,则会跳转进入微信扫码界面。
网友评论