在去年这个时候,根据视频完成了微信网页授权的案例,但是那时候使用原生的方式进行完成。本次案例是基于微信开发框架来编写。
首先需要准备一些工具,工具在 https://blog.csdn.net/weixin_41622183/article/details/80267734 旧文中有提到。
工具准备好后,我们来开始写代码
application.yml 文件:
weChat:
mpAppId: "微信 appId"
mpAppSecret: "微信秘钥"
修改该文件中 mpAppId 和 mpAppSecret ,将其换成我们自己的配置。
接下来我们需要准备两个配置文件
WeChatAccountConfig 配置文件:
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author Gentle
* @description: 微信账号配置文件
*/
@Data
@Component
@ConfigurationProperties(prefix = "weChat")
public class WeChatAccountConfig {
private String mpAppId;
private String mpAppSecret;
}
WeChatMpConfig 配置文件:
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @author Gentle
* @description: 微信服务配置
* @date 2019/04/18
*/
@Component
public class WeChatMpConfig {
@Autowired
private WeChatAccountConfig wechatAccountConfig;
@Bean
public WxMpService wxMpService(){
WxMpService wxMpService=new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
return wxMpService;
}
@Bean
public WxMpConfigStorage wxMpConfigStorage(){
WxMpInMemoryConfigStorage wxMpConfigStorage=new WxMpInMemoryConfigStorage();
wxMpConfigStorage.setAppId(wechatAccountConfig.getMpAppId());
wxMpConfigStorage.setSecret(wechatAccountConfig.getMpAppSecret());
return wxMpConfigStorage;
}
}
最后我们开始写微信授权接口的 Controller 类:
@Controller
@RequestMapping(value = "/api/client/")
public class WeChatLoginController {
@Autowired
private WxMpService wxMpService;
/**
* 微信授权入口,请求该接口
* @return
*/
@GetMapping(value = "weChatLogin")
public String weChatRedirect() {
String url = "http://修改成自己的域名/api/client/apiTest";
String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_USER_INFO, null);
return "redirect:" + redirectURL;
}
/**
* 微信重定向回来,并携带 code 参数
* @param code 微信返回的 code
* @return
*/
@GetMapping(value = "apiTest")
public String redirectToIndexPage(@RequestParam("code") String code) {
//请求微信,拿到微信信息
try {
//根据 code 换取 accessToken
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
/**
* 这里处理内部业务,如判断数据库中是否已经有该用户了
*/
//换取用户信息
WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
/**
* 消息入库等等之类的代码
*/
System.out.println("得到授权的个人信息 :" + wxMpUser);
} catch (WxErrorException e) {
e.printStackTrace();
}
//这里可以做重定向到某个页面,懒得做页面就算了。
return "请求成功!";
}
}
上面代码可以做适当修改,修改自己的域名以及 url 地址即可!
微信授权这里就做完啦,代码很简单,我们关注业务就可以写完,大多数代码已经由框架内部完成了!
本次案例源代码已经提交到 github 和码云,可自行下载:
GitHub:
https://github.com/LuckyToMeet-Dian-N/WeChat-Demo/tree/master/wechat-login-demo
码云:
https://gitee.com/reway_wen/WeChat-Demo/tree/master/wechat-login-demo