我们想要引一个maven用来处理JSON数据 ,当然你也可以选择其他的json包来替代
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.23</version>
</dependency>
在创建一个请求微信接口的工具类
/**
* 获取连接的json对象
*
* @param url 路径
*/
public static JSONObject loadJson(String url) {
StringBuffer json = new StringBuffer();
try {
URL urlObject = new URL(url);
URLConnection uc = urlObject.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jSONObject = new JSONObject();
jSONObject = JSON.parseObject(json.toString());
return jSONObject;
}
在创建一个微信的配置类
package com.longlongUtil.props;
/**
* @author 29027
* 第三方登录参数
*/
public class ThirdPartyLoginsProps {
/**微信登录appid;*/
public final static String WX_APPID = "";
/**微信登录scope*/
public final static String WX_SCOPE = "";
/**微信登录http*/
public final static String WX_HTTP = "";
}
package com.longlongUtil.util;
import com.alibaba.fastjson.JSONObject;
import com.longlongUtil.props.ThirdPartyLoginsProps;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 29027
* <p>
* 第三方登录工具类
*/
public class ThirdPartyLoginsUtil {
/**
* 微信登录
*/
public static void wxLogin(HttpServletRequest request, HttpServletResponse response, String tenantId) throws IOException, IOException {
String appId = ThirdPartyLoginsProps.WX_APPID;
String scope = ThirdPartyLoginsProps.WX_SCOPE;
String http = ThirdPartyLoginsProps.WX_HTTP;
// 第一步:用户同意授权,获取code
/*APPID&secret=SECRET&code=CODE&grant_type=authorization_code*/
String url = "https://open.weixin.qq.com/connect/qrconnect?"
+ "appid=" + appId + "&scope=" + scope + "&redirect_uri=" + http;
response.sendRedirect(url);
}
/**
* 微信登录后回调
*/
public JSONObject wxcallback(String code) throws IOException {
String appid = ThirdPartyLoginsProps.WX_APPID;
String appSecret = ThirdPartyLoginsProps.WX_SCOPE;
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid +
"&secret=" + appSecret +
"&code=" + code +
"&grant_type=authorization_code";
JSONObject token = HttpUtils.loadJson(url);
System.out.println(token);
//获取用户的openid和access_token
String access_token = token.get("access_token").toString();
String openid = token.get("openid").toString();
return this.userWx(access_token, openid);
}
/**
* 获取微信用户信息
* */
/**
* 获取微信的用户信息
*/
@GetMapping("/userWx")
public JSONObject userWx(String access_token, String openid) throws IOException {
String url = "https://api.weixin.qq.com/sns/userinfo?" +
"access_token=" + access_token +
"&openid=" + openid;
JSONObject token = HttpUtils.loadJson(url);
return token;
}
}