一、需要的材料
1:一个可以测试的微信小程序
2:此微信小程序的APPID和APPscret
二、微信小程序前端获取code并发送到后台
//请求code
wx.login({
success(res) {
if (res.code) {
//把获取到的code通过一个request的请求发给java服务器
wx.request({
url:你的url地址,
data: {
code: res.code
},
method: 'POST',
dataType: 'json',
success: function (res) {
//请求成功的处理
}
}
},
fail: function () {
console.log("发送code失败:", res.data);
}
})
三、后台接收
/**
* 微信授权登录
* @return
* @throws Exception
*/
@RequestMapping("getWechatLogin")
public ResponseVos getWechatLogin(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
//微信公众号的APPID和APPSECRET
String code = request.getParameter("code");
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + AppId() +
"&secret=" + AppSecret() +
"&js_code=" + code +
"&grant_type=authorization_code";
String result = HttpClientManager.getUrlData(url);
if (result.contains("errcode")) {
return ResponseVos.serviceFail("错误code");
}
Map<String, Object> data = JSONObject.parseObject(result);
String openid = data.get("openid").toString();
String token = data.get("session_key").toString();
String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId() +
"&secret=" + AppSecret();
String tokenResult = HttpClientManager.getUrlData(tokenUrl);
Map<String, Object> tokenMap = JSONObject.parseObject(tokenResult);
if (ToolUtil.isNotEmpty(tokenMap.get("access_token"))) {
//根据场景不一样,授权成功后,在这里做一些业务逻辑的处理
return ResponseVos.success("获取授权成功");
} else {
return ResponseVos.serviceFail(DEFAULT_ERROR_CODE, "获取授权失败");
}
}
四、用到的工具类
package cn.stylefeng.guns.core.util.Wechat;
/**
* @Author ysy
*/
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;
}
}
如有疑问私信评论区发言