直接使用 cloud 集成微信扫码登录系统
pom.xml文件新增坐标
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
在配置文件中配置appid 等信息
wx:
open:
#微信开放平台appId
appId: xxxxxx
#微信开放平台appSecret
appSecret: xxxxxx
#微信开放平台-重定向url
redirectUri: http://xxxxx/api/ucenter/wx/callback
```javascript
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
编写微信登录controller
@RestController
@RequestMapping("ucenter/wx")
@Slf4j
public class ApiWxController {
@Resource
private RemoteLogService remoteLogService;
@Resource
private UcenterProperties ucenterProperties;
@Resource
private WxMemberMapper wxMemberMapper;
@Resource
private ISysUserService sysUserService;
@Autowired
private TokenService tokenService;
@Resource
private RemoteUserService remoteUserService;
@PostMapping("/login")
public R<String> genQrConnect(HttpSession session,@RequestParam("id") String id) {
if(StringUtils.isEmpty(id)){
R.fail("用户id为空,请重新登录");
}
String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
"?appid=%s" +
"&redirect_uri=%s" +
"&response_type=code" +
"&scope=snsapi_login" +
"&state=%s" +
"#wechat_redirect";
String redirecturi = "";
try {
redirecturi = URLEncoder.encode(ucenterProperties.getRedirectUri(), "UTF-8");
} catch (UnsupportedEncodingException e) {
log.error(ExceptionUtils.getMessage(e));
}
String state = id;
log.info("生成 state = " + state);
String qrcodeUrl = String.format(
baseUrl,
ucenterProperties.getAppId(),
redirecturi,
state
);
System.out.println(qrcodeUrl);
return R.ok(qrcodeUrl);
}
@GetMapping("/callback")
public R<?> callback(String code, String state, HttpSession session) {
log.info("callback被调用");
log.info("code = " + code);
log.info("state = " + state);
if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state)) {
log.error("非法回调请求");
return R.fail("非法回调请求");
}
String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
Map<String, String> accessTokenParam = new HashMap();
accessTokenParam.put("appid", ucenterProperties.getAppId());
accessTokenParam.put("secret", ucenterProperties.getAppSecret());
accessTokenParam.put("code", code);
accessTokenParam.put("grant_type", "authorization_code");
HttpClientUtils client = new HttpClientUtils(accessTokenUrl, accessTokenParam);
String result = "";
try {
client.get();
result = client.getContent();
} catch (Exception e) {
log.error("获取access_token失败");
return R.fail("获取用户信息失败");
}
Gson gson = new Gson();
HashMap<String, Object> resultMap = gson.fromJson(result, HashMap.class);
Object errcodeObj = resultMap.get("errcode");
if (errcodeObj != null) {
String errmsg = (String) resultMap.get("errmsg");
Double errcode = (Double) errcodeObj;
log.error("获取access_token失败 - " + "message: " + errmsg + ", errcode: " + errcode);
return R.fail("获取accessToken失败");
}
String accessToken = (String) resultMap.get("access_token");
String openid = (String) resultMap.get("openid");
log.info("accessToken = " + accessToken);
log.info("openid = " + openid);
WxMember member = wxMemberMapper.getByOpenid(openid);
WxMember member_user = null;
if(null == member){
member_user = wxMemberMapper.getByUserId(state);
}
if ( null == member && null==member_user) {
String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo";
Map<String, String> baseUserInfoParam = new HashMap();
baseUserInfoParam.put("access_token", accessToken);
baseUserInfoParam.put("openid", openid);
client = new HttpClientUtils(baseUserInfoUrl, baseUserInfoParam);
String resultUserInfo = null;
try {
client.get();
resultUserInfo = client.getContent();
} catch (Exception e) {
log.error(ExceptionUtils.getMessage(e));
return R.fail("获取用户信息失败");
}
HashMap<String, Object> resultUserInfoMap = gson.fromJson(resultUserInfo, HashMap.class);
if (resultUserInfoMap.get("errcode") != null) {
log.error("获取用户信息失败" + ",message:" + resultMap.get("errmsg"));
return R.fail("获取用户信息失败");
}
String nickname = (String) resultUserInfoMap.get("nickname");
String headimgurl = (String) resultUserInfoMap.get("headimgurl");
Double sex = (Double) resultUserInfoMap.get("sex");
member = new WxMember();
member.setOpenId(openid);
member.setNickName(nickname);
member.setAvatar(headimgurl);
member.setSex(sex.intValue());
member.setUserId(Integer.valueOf(state));
wxMemberMapper.save(member);
}else{
return R.fail("请使用绑定微信号登录");
}
String username = sysUserService.selectUserById(Long.valueOf(state)).getUserName();
R<LoginUser> userResult = remoteUserService.getUserInfo(username);
remoteLogService.saveLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
return R.ok(tokenService.createToken(userResult.getData()));
}
}
public class HttpClientUtils {
private String url;
private Map<String, String> param;
private int statusCode;
private String content;
private String xmlParam;
private boolean isHttps;
public boolean isHttps() {
return isHttps;
}
public void setHttps(boolean isHttps) {
this.isHttps = isHttps;
}
public String getXmlParam() {
return xmlParam;
}
public void setXmlParam(String xmlParam) {
this.xmlParam = xmlParam;
}
public HttpClientUtils(String url, Map<String, String> param) {
this.url = url;
this.param = param;
}
public HttpClientUtils(String url) {
this.url = url;
}
public void setParameter(Map<String, String> map) {
param = map;
}
public void addParameter(String key, String value) {
if (param == null)
param = new HashMap<String, String>();
param.put(key, value);
}
public void post() throws ClientProtocolException, IOException {
HttpPost http = new HttpPost(url);
setEntity(http);
execute(http);
}
public void put() throws ClientProtocolException, IOException {
HttpPut http = new HttpPut(url);
setEntity(http);
execute(http);
}
public void get() throws ClientProtocolException, IOException {
if (param != null) {
StringBuilder url = new StringBuilder(this.url);
boolean isFirst = true;
for (String key : param.keySet()) {
if (isFirst) {
url.append("?");
isFirst = false;
}else {
url.append("&");
}
url.append(key).append("=").append(param.get(key));
}
this.url = url.toString();
}
HttpGet http = new HttpGet(url);
execute(http);
}
private void setEntity(HttpEntityEnclosingRequestBase http) {
if (param != null) {
List<NameValuePair> nvps = new LinkedList<NameValuePair>();
for (String key : param.keySet())
nvps.add(new BasicNameValuePair(key, param.get(key)));
http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
}
if (xmlParam != null) {
http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
}
}
private void execute(HttpUriRequest http) throws ClientProtocolException,
IOException {
CloseableHttpClient httpClient = null;
try {
if (isHttps) {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain,
String authType)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
.build();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = httpClient.execute(http);
try {
if (response != null) {
if (response.getStatusLine() != null)
statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity, Consts.UTF_8);
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.close();
}
}
public int getStatusCode() {
return statusCode;
}
public String getContent() throws ParseException, IOException {
return content;
}
}