一、创建网站应用
1. 在微信开发平台上面创建以个网站应用
2. 微信开发平台地址 https://open.weixin.qq.com/https://open.weixin.qq.com/
二、配置基本信息
1. 把公用的信息放在application.yml中
#微信开放平台创建的网站应用的appid
AppID: *********
#微信开放平台创建的网站应用的appsecret
AppSecret: ***********************************
scope: snsapi_login
#微信开放平台创建的网站 设置的授权回调域
redirect_url: 自己的回调地址,必须是公网能够访问的
2. 获取微信二维码信息
@Value("${AppID}")
private String appid;
@Value("${redirect_url}")
private String callBack;
@Value("${scope}")
private String scope;
@Value("${AppSecret}")
private String appsecret;
@Override
public String getWechatCode() {
try {
String oauthUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
String redirect_uri = URLEncoder.encode(callBack, "utf-8");
oauthUrl = oauthUrl.replace("APPID",appid).replace("REDIRECT_URI",redirect_uri).replace("SCOPE",scope);
logger.info(oauthUrl);
return ReturnMessage.success(0,"获取完成",oauthUrl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return ReturnMessage.fail(44,"失败");
}
备注:在前端页面直接加载oauthUrl 就可以出现二维码界面了。直接用的微信的页面,也可以根据自己的爱好进行设计页面。如下图
微信扫码登录.png
3. 接收扫码之后的信息
用户扫码之后,微信回返回code和state。code用来接下来获取用户标识(openid),作用是获取用户信息。代码如下:
@Override
public String callBackUserInfo(String code, String state) {
try {
//1.通过code获取access_token
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
url = url.replace("APPID",appid).replace("SECRET",appsecret).replace("CODE",code);
JSONObject tokenInfoObject = HttpUtils.httpGet(url);
logger.info("tokenInfoObject:{}",tokenInfoObject);
//2.通过access_token和openid获取用户信息
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN",tokenInfoObject.getString("access_token")).replace("OPENID",tokenInfoObject.getString("openid"));
JSONObject userInfoStr = HttpUtils.httpGet(userInfoUrl);
logger.info("userInfoObject:{}",userInfoStr);
if (userInfoStr == null) {
return ReturnMessage.fail(40,"获取失败");
}
//3.根据uuid查询用户是否存在,如果存在直接登录。如果不存在则自动注册,在登录
UserInfoModel userInfoByWechat = iUserDao.getUserInfoByWechat(userInfoStr.get("unionid").toString());
if (userInfoByWechat != null) {
return ReturnMessage.success(0,"获取成功",userInfoByWechat);
}
//4.数据库添加用户信息
String username = userInfoStr.get("nickname").toString();
String unionid = userInfoStr.get("unionid").toString();
UserInfoBean userInfoBean = new UserInfoBean();
userInfoBean.setUuid(unionid);
userInfoBean.setUsername(username);
// 微信登录
userInfoBean.setStatus(2);
iUserDao.insertUser(userInfoBean);
//5.根据uuid查询新注册的用户信息
UserInfoModel userInfoModel= iUserDao.getUserInfoByWechat(unionid);
if (userInfoModel == null) {
return ReturnMessage.fail(400,"用户添加失败,请重新操作");
}
return ReturnMessage.success(0,"获取成功",userInfoModel);
} catch (Exception e) {
e.printStackTrace();
}
return ReturnMessage.fail(400,"获取失败");
}
httpUtil--这部分代码是在网上找的,但是这个是后来写的。如果发现原作者请告知
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* 封装http get post
*/
public class HttpUtils {
private static Logger logger = LoggerFactory.getLogger(HttpUtils.class); // 日志记录
private static RequestConfig requestConfig = null;
static {
// 设置请求和传输超时时
requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
}
/**
* post请求传输json参数
*
* @param url url地址
* @param jsonParam 参数
* @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 {
System.out.println(jsonParam);
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
System.out.println(jsonParam);
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;
}
/**
* 发送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;
}
}
结尾:目的是为了记录自己这一段时间做的东西,如果有朋友在其中有更好的建议,愿意交流的话可以一起交流一下---来自刚刚入坑的小菜鸟
网友评论