引入jar包
<!-- 微信授权登录-->
<!-- https://mvnrepository.com/artifact/com.github.binarywang/weixin-java-mp -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.4.0</version>
</dependency>
后台代码:
import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/wx")
public class WXLoginController {
private static final Logger logger = Logger.getLogger(WXLoginController.class);
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
private String login_url="http://**/wx/login";//回调接口
private String success_login_url=""; // 登录成功后返回的网页
/**
* 提示用户点击同意,授权登录
* @return
*/
@GetMapping("/welcome")
public String welcome() {
// 1.根据appid和appsecret和回调地址配置微信授权
WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
wxMpConfigStorage.setAppId("APPID");//你的公众号id
wxMpConfigStorage.setSecret("APPSECRET");//你的公众号密匙
wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
// 完成配置后进行跳转
String oauth2buildAuthorizationUrl = wxMpService.oauth2buildAuthorizationUrl(login_url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
System.out.println(oauth2buildAuthorizationUrl);
return "redirect:" + oauth2buildAuthorizationUrl;
}
/**
* 通过code拿到数据openid
* @param code
* @param returnUrl
* @return 进行网站跳转
*/
@GetMapping("/login")
public String login(@RequestParam("code") String code,
@RequestParam("state") String returnUrl,HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
System.out.println("code=="+code);
// 2.根据code换取AccessToken
WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
try {
wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
} catch (WxErrorException e) {
e.printStackTrace();
}
// 3.进一步获取用户信息
String openId = wxMpOAuth2AccessToken.getOpenId();
System.out.println("openid="+openId);
// 拿到用户的基本信息
WxMpUser wxMpUser=null;
try {
wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
} catch (WxErrorException e) {
e.printStackTrace();
}
// 后面的内容根据需要编写,微信授权到此已经结束了。
// 判断这个用户是否已经注册
return "redirect:" + success_login_url+"?openid="+openId;
}
}