一、方式一:手動實現微信授權
1、若沒有微信公衆號,可以用測試號來進行測試號
(1)官方鏈接:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
其中Token可以隨便寫,可能一開始配置的URL無法配置成功,彆着急,按照我下面的步驟操作
(2)在“網頁授權獲取用戶基本信息”那一欄,點擊修改
在此處設置自己的域名,可以是通過花生殼或者natapp[鏈接:https://natapp.cn/ ]獲取來的,均可!!
[不要包含http://或https://]
2、SpringBoot後臺
例如我配置的上述URL就是doWxLogin這個方法的地址:http://域名/sell/weixin/wx/wxLogin
訪問上述地址,調用doWxLogin方法請求微信,微信登陸後重定向到http://域名/sell/weixin/auth 這個方法,獲取到返回的信息
(1)Controller層
@RestController
@RequestMapping("/weixin")
@Slf4j
public class WeixinController {
@Autowired
private LoginService loginService;
@GetMapping("/auth")
public void auth(@RequestParam("code") String code) {
log.info("進入auth方法。。。");
log.info("code={}", code);
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=XXXXXXXXXXX&secret=XXXXXXXXXXXXXXXXXX&code=" + code + "&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
log.info("response={}", response);
}
@GetMapping("/wx/wxLogin")
public void doWxLogin (HttpServletRequest request, HttpServletResponse response) {
try {
loginService.doWxLogin(request, response);
System.out.println("==================================>");
} catch (Exception e) {
e.printStackTrace();
//相應的處理
}
}
}
(2)Service層
@Service
public class LoginServiceImpl implements LoginService {
@Override
public void doWxLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
String authUrl = WxConstants.AUTH_BASE_URL + "appid=" + WxConstants.APPID
+ "&redirect_uri=" + URLEncoder.encode(WxConstants.REDIRECT_URL)
+ "&response_type=code"
+ "&scope=" + WxConstants.SCOPE
+ "&state=STATE#wechat_redirect";
String signature = request.getParameter("signature");/// 微信加密簽名
String timestamp = request.getParameter("timestamp");/// 時間戳
String nonce = request.getParameter("nonce"); /// 隨機數
String echostr = request.getParameter("echostr"); // 隨機字符串
PrintWriter out = response.getWriter();
if (signature != null && timestamp != null && nonce != null && echostr != null) {
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
out.close();
} else {
response.sendRedirect(authUrl);
}
}
}
(3)WxConstants類
public final class WxConstants {
public static final String APPID = "XXXXXXXXXXXXXXXXX";
public static final String APPSECRET = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
//授權
public static final String AUTH_BASE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?";
//獲取token
public static final String ACCESS_TOKEN_BASE_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?";
//獲取用戶信息
public static final String INFO_BASE_URL = "https://api.weixin.qq.com/sns/userinfo?";
//回調
public static final String REDIRECT_URL = "http://域名/sell/weixin/auth";
//允許的範圍
public static final String SCOPE = "snsapi_userinfo";
//token
public static final String TOKEN = "與上面設置的token一致";
private WxConstants(){}
}
3、結果
微信訪問即可獲得授權:http://域名/sell/weixin/wx/wxLogin
二、方式二:利用第三方SDK實現微信授權
1、參考鏈接:https://github.com/Wechat-Group/WxJava
在pom.xml中加入:
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId> weixin-java-mp </artifactId>
<version>3.3.0</version>
</dependency>
2、SpringBoot後臺
參考文檔:https://github.com/wechat-group/WxJava/wiki
(1)Controller層
@Controller
@RequestMapping("/wechat")
@Slf4j
public class WechatController {
@Autowired
private WxMpService wxMpService;
@GetMapping("/authorize")
public String authorize(@RequestParam("returnUrl") String returnUrl){
//訪問:http://t238997p11.qicp.vip/sell/wechat/authorize?returnUrl=http://www.imooc.com
//訪問:http://127.0.0.1:8080/sell/wechat/authorize?returnUrl=http://www.imooc.com
//若用註解@RestController(會自動解析成json)
//返回:redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx085c556cb1d22b1f&redirect_uri=http%3A%2F%2Ft238997p11.qicp.vip%2Fsell%2Fwechat%2FuserInfo&response_type=code&scope=snsapi_userinfo&state=http%3A%2F%2Fwww.imooc.com&connect_redirect=1#wechat_redirect
//若用註解@Controller
//返回:直接重定向,請在微信打開,訪問http://t238997p11.qicp.vip/sell/wechat/authorize?returnUrl=http://www.imooc.com,在微信打開後會跳轉到returnUrl,即http://www.imooc.com
//配置(配置已經完成)
//回調方法
String url = "http://t238997p11.qicp.vip/sell/wechat/userInfo";
//構造網頁授權url
//可使用WxConsts.OAuth2Scope.SNSAPI_USERINFO模式,也可使用WxConsts.OAuth2Scope.SNSAPI_BASE模式,SNSAPI_BASE模式用戶是無感知的
String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
log.info("微信網頁授權獲取code,redirectUrl={}",redirectUrl);
return "redirect:" + redirectUrl;
}
@GetMapping("/userInfo")
public String userInfo(@RequestParam("code") String code,@RequestParam("state") String returnUrl){
//獲得access token
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
try {
wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
} catch (WxErrorException e) {
log.info("[微信網頁授權] {}",e);
throw new SellException(ResultEnum.WECHAT_MP_ERROR.getCode(),e.getError().getErrorMsg());
}
//獲取openid
String openId = wxMpOAuth2AccessToken.getOpenId();
return "redirect:" + returnUrl+"?openid=" + openId;
}
}
(2)相關配置
A: application.yml
wechat:
myAppId: XXXXXXXXXXXXXXXXXX
myAppSecret: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
B: WechatAccountConfig.java
@Data
@Component
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {
private String myAppId;
private String myAppSecret;
}
C: WechatMpConfig.java
@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 wxMpConfigStorage = new WxMpInMemoryConfigStorage();
wxMpConfigStorage.setAppId(accountConfig.getMyAppId());
wxMpConfigStorage.setSecret(accountConfig.getMyAppSecret());
return wxMpConfigStorage;
}
}
3、結果
微信訪問即可獲得授權: http://域名/sell/wechat/authorize?returnUrl=http://www.imooc.com
頁面會跳轉到http://www.imooc.com,並且地址欄路徑中會返回openid