请写出带注释的Java的SpringCloud微信登录的插入和查询后端代码分为controller层,service接口,service实现类,mapper接口,mapper配置文件,调用微信API类
时间: 2024-06-09 19:10:25 浏览: 57
Controller层代码:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody User user) {
try {
// 调用微信API获取openid和session_key
WeChatUtil weChatUtil = new WeChatUtil();
JSONObject json = weChatUtil.getSessionKeyOrOpenId(user.getCode());
String openid = json.getString("openid");
String sessionKey = json.getString("session_key");
// 判断用户是否已存在
User userFromDB = userService.getUserByOpenId(openid);
if (userFromDB != null) {
// 更新session_key
userFromDB.setSessionKey(sessionKey);
userService.updateUser(userFromDB);
return new ResponseEntity<>(userFromDB, HttpStatus.OK);
} else {
// 新建用户
user.setOpenId(openid);
user.setSessionKey(sessionKey);
return new ResponseEntity<>(userService.insertUser(user), HttpStatus.OK);
}
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>("登录失败", HttpStatus.BAD_REQUEST);
}
}
}
```
Service接口代码:
```java
public interface UserService {
User insertUser(User user);
void updateUser(User user);
User getUserByOpenId(String openId);
}
```
Service实现类代码:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User insertUser(User user) {
userMapper.insertUser(user);
return user;
}
@Override
public void updateUser(User user) {
userMapper.updateUser(user);
}
@Override
public User getUserByOpenId(String openId) {
return userMapper.getUserByOpenId(openId);
}
}
```
Mapper接口代码:
```java
@Mapper
public interface UserMapper {
@Insert("insert into user(open_id,session_key,nick_name,gender,city,province,country,avatar_url,create_time) " +
"values(#{openId},#{sessionKey},#{nickName},#{gender},#{city},#{province},#{country},#{avatarUrl},#{createTime})")
void insertUser(User user);
@Update("update user set session_key=#{sessionKey} where open_id=#{openId}")
void updateUser(User user);
@Select("select * from user where open_id=#{openId}")
User getUserByOpenId(String openId);
}
```
Mapper配置文件:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
</mapper>
```
调用微信API类代码:
```java
public class WeChatUtil {
public static final String APP_ID = "your_app_id";
public static final String APP_SECRET = "your_app_secret";
public JSONObject getSessionKeyOrOpenId(String code) {
String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + APP_SECRET
+ "&js_code=" + code + "&grant_type=authorization_code";
JSONObject jsonObject = null;
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(requestUrl);
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSON.parseObject(result);
}
httpGet.releaseConnection();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
}
```
注:需要替换APP_ID和APP_SECRET为自己的微信小程序的信息。
阅读全文