加粗样式
另外,在正式公众号下,还有一个非常重要的关键点,就是一定要配置白名单,且白名单须是IP地址
设置方式如下:
A、
B、
C、附上我在开发过程中配置的白名单
说到这里关于微信授权的相关配置就没有了,接下来就是代码如何实现的问题!!!
/**
* 用户初始化登录获取微信请求地址
*
* @return
* @throws Exception
*/
@RequestMapping("loginInit")
@ApiOperation(value = "用户扫码后调用进行授权", notes = "接口不需要传参数")
public void loginInit(HttpServletResponse response) throws Exception {
//回调地址,要跟下面的地址能调通(getWechatGZAccessToken.do)
// 从配置文件中读取回调地址
String backUrl = wxGrantProperties.getWxBackUrl();
//注:首尾不能有多的空格(因为直接复制往往会多出空格),其次就是参数的顺序不能变动
// AuthUtil.APPID微信公众号的appId
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxGrantProperties.getAppId() +
"&redirect_uri=" + URLEncoder.encode(backUrl, "UTF-8") +
"&response_type=code" +
"&scope=snsapi_userinfo" +
"&state=" + UUID.randomUUID() + "#wechat_redirect";
// 方法重定向
response.sendRedirect(url);
}
/**
* loginInit方法重定向到此获取微信用户基本信息,基本进行入库操作
*
* @param request
* @return
* @throws Exception
*/
@RequestMapping("getWechatGZAccessToken")
@ResponseBody
public ResponseVO getWechatGZAccessToken(HttpServletRequest request) {
try {
Map map = userWxService.getWechatGZAccessToken(request);
if (map.get("statusCode").equals(ResponseVO.REQUEST_PARAM_ERROR)) {
return ResponseVO.requestParamsError();
} else if (map.get("statusCode").equals(ResponseVO.DEFAULT_ERROR_CODE)) {
return ResponseVO.serviceFail("请求失败");
}
return ResponseVO.success(map, "微信授权成功");
} catch (Exception e) {
log.error("微信授权异常");
e.printStackTrace();
return ResponseVO.serviceFail("微信授权异常");
}
}
/**
* 用户授权登录
*
* @param request
* @return
*/
@Override
@Transactional
public Map getWechatGZAccessToken(HttpServletRequest request) throws Exception {
Map map = new HashMap();
//微信公众号的APPID和APPSECRET
String code = request.getParameter("code");
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxGrantProperties.getAppId() +
"&secret=" + wxGrantProperties.getAppSecret() +
"&code=" + code +
"&grant_type=authorization_code";
String result = HttpClientManager.getUrlData(url);
// 请求参数有误
if (result.contains("errcode")) {
map.put("statusCode",ResponseVO.REQUEST_PARAM_ERROR);
return map;
}
Map data = JSONObject.parseObject(result);
String openid = data.get("openid").toString();
String token = data.get("access_token").toString();
//获取信息
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token +
"&openid=" + openid +
"&lang=zh_CN";
String infoResult = HttpClientManager.getUrlData(infoUrl);
Map wxUser = JSONObject.parseObject(infoResult);
// 截止到次数已经获取到了微信授权用户的所有能拿到的信息
// 以下根据个人业务需要进行修改
if (ToolUtil.isEmpty(wxUser.get("openid"))) {
map.put("statusCode",ResponseVO.REQUEST_PARAM_ERROR);
return map;
}
String nickName = filterEmoji(wxUser.get("nickname").toString());
EntityWrapper entityWrapper = new EntityWrapper<>();
entityWrapper.eq("openid",openid);
Integer integer = this.baseMapper.selectCount(entityWrapper);
if (integer == 0){
UserWx u = new UserWx();
u.setAddTime(DateUtil.getTime());
u.setHeadimg(wxUser.get("headimgurl").toString());
u.setName(nickName);
u.setCountry(wxUser.get("country").toString());
u.setCity(wxUser.get("city").toString());
u.setOpenid(openid);
u.setProvince(wxUser.get("province").toString());
// 1:男 2:女 0:未知
u.setUserSex(Integer.parseInt(wxUser.get("sex").toString()));
Integer insert = this.baseMapper.insert(u);
if (insert > 0) {
map.put("openId",wxUser.get("openid"));
map.put("statusCode",ResponseVO.DEFAULT_SUCCESS_CODE);
return map;
} else {
map.put("statusCode",ResponseVO.DEFAULT_ERROR_CODE);
return map;
}
}else{
map.put("openId",wxUser.get("openid"));
map.put("statusCode",ResponseVO.DEFAULT_SUCCESS_CODE);
return map;
}
}
///////////////////////////////////////////////////需要使用到的Util工具类,由于不能上传文件,我就附上代码段了
package cn.stylefeng.guns.core.util.wx;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class HttpClientManager {
/**
* 执行url请求数据
*
* @param urlStr
* @return
* @throws Exception
* @throws IOException
*/
public static String getUrlData(String urlStr) throws Exception {
URL url = new URL(urlStr);
URLConnection connection = url.openConnection();
// 一旦发送成功,用以下方法就可以得到服务器的回应:
String sCurrentLine = "";
StringBuffer sTotalString = new StringBuffer();
InputStream l_urlStream = connection.getInputStream();
// 传说中的三层包装阿!
BufferedReader l_reader = new BufferedReader(new InputStreamReader(
l_urlStream, "UTF-8"));
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString.append(sCurrentLine);
}
return sTotalString.toString();
}
/**
* 执行url请求数据
*
* @param urlStr
* @return
* @throws Exception
* @throws IOException
*/
public static String postUrlData(String urlStr, String data)
throws Exception {
URL url = new URL(urlStr);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒28
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒29
// 30
OutputStream os = http.getOutputStream();
os.write(data.getBytes("UTF-8"));// 传入参数
os.flush();
os.close();
// 一旦发送成功,用以下方法就可以得到服务器的回应:
String sCurrentLine = "";
String sTotalString = "";
InputStream l_urlStream = http.getInputStream();
// 传说中的三层包装阿!
BufferedReader l_reader = new BufferedReader(new InputStreamReader(
l_urlStream, "UTF-8"));
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine;
}
return sTotalString;
}
}