一、逻辑
- 使用wx.login()获得code(或是和其他你需要的信息)传到你写的接口
- 在接口中使用url用get的方式访问微信服务器接口(jscode2session)
- 将在接口中获得的openid和你所要信息联系起来存进数据库(注册)
- 返回一个 自己生成的 sessionid返回给小程序端,用于判断
a. 还未绑定过信息(注册)、上次获取sessionid的信息已经超过你所规定的时间(“过期”)、清楚了本地数据,则重新发起请求
b. 反之,则不用请求,直接使用存储在本地的数据
二、小程序端
Page({
onLoad() {
//查询本地是否有sessionId
var sessionId = wx.getStorageSync("sessionId");
if (!sessionId)
//还没绑定过(注册)
this.login();
else {
//一天之后更新一次
if (Date.now() - sessionId.time > 24 * 60 * 60 * 1000) this.login();
//我这里并没存贮用户信息,你可以自己尝试,比较简单
else console.log("直接获取用户信息继续进一步的操作!");
}
},
// 登录
login() {
wx.login({
success: (res) => {
console.log(res);
// 将code发送到服务器后台
wx.request({
url: "http://localhost:8080/user/login",
data: {
code: res.code,
},
header: { "content-type": "application/json" },
method: "GET",
dataType: "json",
responseType: "text",
success: (result) => {
console.log(result);
//在这里将sessionId存在本地,当做预先判断是否发起请求
if (result.statusCode == 200) {
wx.setStorageSync("sessionId", {
time: Date.now(),
data: result.data.sessionId,
});
}
//这里编写你的其他需求
},
fail: () => {
console.log("获取sessionId失败!");
},
});
},
fail: () => {
console.log("获取code失败!");
},
});
}
});
三、后端controller
引入json jar包
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
接口
@Controller
@RequestMapping("/user")
public class userController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping("/login")
public JSONObject login(@Param("code") String code){
//小程序端发送过来的code
String result = "";
//微信服务器接口
String url="https://api.weixin.qq.com/sns/jscode2session?appid=你的appid&secret=你的secret&js_code=";
url+=code+"&grant_type=authorization_code";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
JSONObject jsonObject = JSONObject.parseObject(result);
System.out.println(jsonObject);
//将openId存进数据库,进行用户绑定(理解为注册就行)
//userService.addUser(jsonObject.get("openid"))
//将用户的uid作为sessionId(我自己这样子做的,你们可以弄得复杂)
//int sessionId =userService.getUserId(jsonObject.get("openid"))
//下面展示不使用数据库了,直接传个1
JSONObject json=new JSONObject();
json.put("sessionId",1);
return json;
}
}
四、展示结果
第一次进入小程序
第二次进入小程序
有什么其他想法欢迎在评论区交流
【推荐】
小程序npm引入weui,最详细的教程了吧
小程序数据缓存