获取扫码二维码 public String getWxCode() { // 直接请求微信地址就行,%s相当于占位符 String url = "https://open.weixin.qq.com/connect/qrconnect" + "?appid=%s" + "&redirect_uri=%s" + "&response_type=code" + "&scope=snsapi_login" + "&state=%s" + "#wechat_redirect"; // 对redirecturl编码 String redirect_url = ConstantConfig.WX_OPEN_REDIRECT_URL; try { redirect_url = URLEncoder.encode(redirect_url, "utf-8"); } catch (Exception e) { e.printStackTrace(); } String baseUrl = String.format(url, ConstantConfig.WX_OPEN_APP_ID, redirect_url, "sunset"); return "redirect:" + baseUrl; }
扫码成功后回调
public Object callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
String code = request.getParameter("code");
String state = request.getParameter("state");
//2、拿着code请求微信固定的地址,得到两个值access_token 和 openid
String accessTokenUrl =
"https://api.weixin.qq.com/sns/oauth2/access_token" +
"?appid=" + ConstantConfig.WX_OPEN_APP_ID +
"&secret=" + ConstantConfig.WX_OPEN_APP_SECRET +
"&code=" + code +
"&grant_type=authorization_code";
JSONObject wechatAccessToken = HttpClientUtils.httpGet(accessTokenUrl);
if (wechatAccessToken.get("errcode") != null) {
return R.error("获取accessToken失败");
}
String accessToken = (String) wechatAccessToken.get("access_token");
logger.info("accessToken==============="+accessToken);
String openid = (String) wechatAccessToken.get("openid");
String unionid = (String) wechatAccessToken.get("unionid");
if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(unionid)) {
return R.error("获取accessToken失败");
}
CMember wxMember = cMemberService.getMemberByWechatOpenId(unionid);
if (wxMember == null) {
//3 拿着acess_token和openid再去请求微信固定地址,得到扫描人信息
String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
"?access_token=" +accessToken+
"&openid="+openid;
JSONObject wechatBaseUserInfo = HttpClientUtils.httpGet(baseUserInfoUrl);
logger.info("微信用户信息=================="+wechatBaseUserInfo);
logger.info("微信用户信息=================="+wechatBaseUserInfo.get("sex"));
wxMember = new CMember();
wxMember.setId(UUID.get());
wxMember.setWxUnionId(unionid);
// wxMember.setWxOpenId(openid);
// wxMember.setSex(Integer.parseInt(wechatBaseUserInfo.get("sex").toString()));
wxMember.setSex(0);//2男 1女 0默认
wxMember.setNickName(wechatBaseUserInfo.getString("nickname"));
wxMember.setAvatar(wechatBaseUserInfo.getString("headimgurl"));
wxMember.setCreateTime(DateUtils.getCurrentTime());
cMemberService.save(wxMember);
}
String token = commonService.genCrmToken(wxMember); //生成token并存redis
//Step6------------重定向
response.sendRedirect(Constants.LOCALHOST+"/index.html?name=SY&token="+token);
return R.success("登录成功");
}
连接微信接口
package com.chenyue.cm.utils; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * HttpClient4.3工具类 * @author */ public class HttpClientUtils { private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录 private static RequestConfig requestConfig = null; final static int TIMEOUT = 1000; final static int TIMEOUT_MSEC = 5 * 1000; static { // 设置请求和传输超时时间 requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); } /** * post请求传输json参数 * @param url url地址 * @param * @return */ public static JSONObject httpPost(String url, JSONObject jsonParam) { // post请求返回结果 CloseableHttpClient httpClient = HttpClients.createDefault(); JSONObject jsonResult = null; HttpPost httpPost = new HttpPost(url); // 设置请求和传输超时时间 httpPost.setConfig(requestConfig); try { if (null != jsonParam) { // 解决中文乱码问题 StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); } CloseableHttpResponse result = httpClient.execute(httpPost); // 请求发送成功,并得到响应 if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String str = ""; try { // 读取服务器返回过来的json字符串数据 str = EntityUtils.toString(result.getEntity(), "utf-8"); // 把json字符串转换成json对象 jsonResult = JSONObject.parseObject(str); } catch (Exception e) { logger.error("post请求提交失败:" + url, e); } } } catch (IOException e) { logger.error("post请求提交失败:" + url, e); } finally { httpPost.releaseConnection(); } return jsonResult; } /** * post请求传输String参数 例如:name=Jack&sex=1&type=2 * Content-type:application/x-www-form-urlencoded * @param url url地址 * @param strParam 参数 * @return */ public static JSONObject httpPost(String url, String strParam) { // post请求返回结果 CloseableHttpClient httpClient = HttpClients.createDefault(); JSONObject jsonResult = null; HttpPost httpPost = new HttpPost(url); httpPost.setConfig(requestConfig); try { if (null != strParam) { // 解决中文乱码问题 StringEntity entity = new StringEntity(strParam, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(entity); } CloseableHttpResponse result = httpClient.execute(httpPost); // 请求发送成功,并得到响应 if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String str = ""; try { // 读取服务器返回过来的json字符串数据 str = EntityUtils.toString(result.getEntity(), "utf-8"); // 把json字符串转换成json对象 jsonResult = JSONObject.parseObject(str); } catch (Exception e) { logger.error("post请求提交失败:" + url, e); } } } catch (IOException e) { logger.error("post请求提交失败:" + url, e); } finally { httpPost.releaseConnection(); } return jsonResult; } public static String doPost(String url, Map<String, String> paramMap) throws IOException { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (paramMap != null) { List<NameValuePair> paramList = new ArrayList<>(); for (Map.Entry<String, String> param : paramMap.entrySet()) { paramList.add(new BasicNameValuePair(param.getKey(), param.getValue())); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } httpPost.setConfig(builderRequestConfig()); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (Exception e) { throw e; } finally { try { response.close(); } catch (IOException e) { throw e; } } return resultString; } private static RequestConfig builderRequestConfig() { return RequestConfig.custom() .setConnectTimeout(TIMEOUT_MSEC) .setConnectionRequestTimeout(TIMEOUT_MSEC) .setSocketTimeout(TIMEOUT_MSEC).build(); } /** * 发送get请求 * @param url 路径 * @return */ public static JSONObject httpGet(String url) { // get请求返回结果 JSONObject jsonResult = null; CloseableHttpClient client = HttpClients.createDefault(); // 发送get请求 HttpGet request = new HttpGet(url); request.setConfig(requestConfig); try { CloseableHttpResponse response = client.execute(request); // 请求发送成功,并得到响应 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 读取服务器返回过来的json字符串数据 HttpEntity entity = response.getEntity(); String strResult = EntityUtils.toString(entity, "utf-8"); // 把json字符串转换成json对象 jsonResult = JSONObject.parseObject(strResult); } else { logger.error("get请求提交失败:" + url); } } catch (IOException e) { logger.error("get请求提交失败:" + url, e); } finally { request.releaseConnection(); } return jsonResult; } }