ps: springboot combined with mybatisPlus and mysql to achieve, simple and easy to understand, one paste to use, see below for details↓
step:
1. Register a WeChat development platform account, create a mini program, and obtain the AppID and AppSecret of the mini program.
2. In the applet, guide the user to click the button to trigger WeChat login and get the code.
3. Send the code to the backend, and the backend obtains the user's openid and session_key through the code.
4. Use session_key to decrypt user data, and obtain user information, avatar, mobile phone number and other data.
5. Save user data in the database, or perform business processing in other ways.
Detailed code and steps:
1: Create a database
First, you need to create a MySQL database, name it wechat_mini_program
, and create the following data tables:
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`open_id` varchar(255) DEFAULT NULL COMMENT '用户唯一标识',
`session_key` varchar(255) DEFAULT NULL COMMENT '会话密钥',
`nickname` varchar(255) DEFAULT NULL COMMENT '用户昵称',
`avatar_url` varchar(255) DEFAULT NULL COMMENT '用户头像',
`gender` tinyint(1) DEFAULT NULL COMMENT '用户性别(0:未知,1:男性,2:女性)',
`country` varchar(255) DEFAULT NULL COMMENT '用户所在国家',
`province` varchar(255) DEFAULT NULL COMMENT '用户所在省份',
`city` varchar(255) DEFAULT NULL COMMENT '用户所在城市',
`phone_number` varchar(20) DEFAULT NULL COMMENT '用户手机号',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
2: Introduce dependencies
Add the following dependencies to pom.xml
the file :
<dependencies>
<!-- Spring Boot 相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Plus 相关依赖 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!-- MySQL 驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!-- 微信小程序 SDK 依赖 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.8.0</version>
</dependency>
</dependencies>
3: Configuration file
Add the following configuration to application.yml
the file :
spring:
datasource:
url: jdbc:mysql://localhost:3306/wechat_mini_program?useUnicode=true&characterEncoding=utf8mb4&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.demo.entity
global-config:
db-config:
id-type: auto
table-prefix: mp_
field-strategy: not_empty
#
4: Entity class
Create an User
entity class to represent user information:
package com.example.demo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("user")
public class User {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("open_id")
private String openId;
@TableField("session_key")
private String sessionKey;
@TableField("nickname")
private String nickname;
@TableField("avatar_url")
private String avatarUrl;
@TableField("gender")
private Integer gender;
@TableField("country")
private String country;
@TableField("province")
private String province;
@TableField("city")
private String city;
@TableField("phone_number")
private String phoneNumber;
}
5:Mapper interface
Create an UserMapper
interface that defines user
operations on the table:
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
6: Service layer
Create an UserService
interface to define operations on user information:
package com.example.demo.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.entity.User;
public interface UserService extends IService<User> {
User getUserByOpenId(String openId);
boolean saveOrUpdateUser(User user);
}
Create a UserServiceImpl
class that implements UserService
the interface:
package com.example.demo.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public User getUserByOpenId(String openId) {
return this.baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, openId));
}
@Override
public boolean saveOrUpdateUser(User user) {
return this.saveOrUpdate(user);
}
}
7: Controller layer
Create a UserController
class to handle requests for user information:
package com.example.demo.controller;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private WxMaService wxMaService;
@Autowired
private UserService userService;
/**
* 登录接口
*/
@PostMapping("/login")
public Result<Object> login(@RequestParam("code") String code, @RequestParam("encryptedData") String encryptedData,
@RequestParam("iv") String iv) {
try {
// 调用微信 API 获取用户的 openid 和 session_key
WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
String openid = session.getOpenid();
// 调用微信 API 获取用户的手机号
WxMaPhoneNumberInfo phoneInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(), encryptedData, iv);
String phoneNumber = phoneInfo.getPhoneNumber();
// 调用微信 API 获取用户的详细信息
WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), code);
// 获取用户昵称
String nickName = userInfo.getNickName();
// 获取用户头像
String avatarUrl = userInfo.getAvatarUrl();
// 获取用户国家
String country = userInfo.getCountry();
// 获取用户省份
String province = userInfo.getProvince();
// 获取用户城市
String city = userInfo.getCity();
// 将用户信息保存到数据库中
User user = userService.getByOpenId(openid);
if (user == null) {
user = new User();
user.setOpenId(openid);
user.setNickName(nickName);
user.setAvatarUrl(avatarUrl);
user.setCountry(country);
user.setProvince(province);
user.setCity(city);
user.setPhoneNumber(phoneNumber);
userService.add(user);
} else {
user.setNickName(nickName);
user.setAvatarUrl(avatarUrl);
user.setCountry(country);
user.setProvince(province);
user.setCity(city);
user.setPhoneNumber(phoneNumber);
userService.update(user);
}
// 返回用户信息
Map<String, Object> data = new HashMap<>();
data.put("openid", openid);
data.put("nickName", nickName);
data.put("avatarUrl", avatarUrl);
data.put("country", country);
data.put("province", province);
data.put("city", city);
data.put("phoneNumber", phoneNumber);
return Result.success(data);
} catch (WxErrorException e) {
log.error("登录失败:" + e.getMessage(), e);
return Result.error("登录失败:" + e.getMessage());
}
/**
* 更新用户信息接口
*/
@PostMapping("/update")
public String updateUserInfo(@RequestBody User user) {
if (user == null || user.getOpenId() == null) {
return "用户信息不能为空";
}
if (userService.saveOrUpdateUser(user)) {
return "更新用户信息成功";
} else {
return "更新用户信息失败";
}
}
}
8. Database table creation statement
创建 `user` 表的 SQL 语句如下:
```sql
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`open_id` varchar(255) NOT NULL COMMENT '用户 openid',
`session_key` varchar(255) DEFAULT NULL COMMENT '用户 session_key',
`nickname` varchar(255) DEFAULT NULL COMMENT '用户昵称',
`avatar_url` varchar(255) DEFAULT NULL COMMENT '用户头像 URL',
`gender` int(11) DEFAULT NULL COMMENT '用户性别,0:未知,1:男性,2:女性',
`country` varchar(255) DEFAULT NULL COMMENT '用户所在国家',
`province` varchar(255) DEFAULT NULL COMMENT '用户所在省份',
`city` varchar(255) DEFAULT NULL COMMENT '用户所在城市',
`phone_number` varchar(20) DEFAULT NULL COMMENT '用户手机号',
PRIMARY KEY (`id`),
UNIQUE KEY `open_id_UNIQUE` (`open_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
9: pom.xml configuration file
The following dependency packages need to be introduced:
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou.mybatisplus</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- weixin-java-miniapp -->
<dependency>
<groupId>me.chanjar.weixin</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.9.0</version>
</dependency>
10: Business explanation and calling process
This code implements the functions of applet user login and user information update.
The calling process is as follows:
- The front end of the applet calls
wx.login
the method to obtaincode
- The front-end of the applet will
code
pass to/user/login
the interface of the back-end - The backend call
wxMaService.getUserService().getSessionInfo(code)
method getssession_key
andopenid
- The backend
openid
queries , and creates a new user if the user does not exist - The backend returns
openid
to the applet frontend - The front-end of the applet uses
wx.getUserProfile
the method to obtain user information (such as nickname, avatar, etc.) - The front end of the applet transmits the user information
openid
together with/user/update
the interface of the back end -
The backend updates the user information and returns the update result to the frontend of the applet
over!
General: The above is the business process implemented by this code. For specific implementation, please refer to the code and comments given above.
It should be noted that when using this code, it is necessary to create an applet in the background of the applet and obtain appid
and appsecret
, and configure accordingly in the code. In addition, you need to apply for and obtain corresponding permissions on the WeChat open platform access_token
. For specific operations, please refer to the official WeChat documentation.
ps: The code given above can be used as a basic implementation, and further development and optimization can be carried out on this basis.