一:注册微信小程序:
- 注册小程序
- 完善小程序信息
- 下载开发者工具
注册小程序:
注册地址:https://mp.weixin.qq.com/wxopen/waregister?action=step1
选择主体类型为 “个人类型”。
查看小程序的 AppID:
下载开发者工具:
下载地址: https://developers.weixin.qq.com/miniprogram/dev/devtools/stable.html
设置不校验合法域名:
了解页面结构:
其中js和wxml两个文件比较重要。
二:编写入门小程序:
1:hello world:
index.wxml:
<view class = "container">
<view>
{{msg}}
</view>
index.js:
Page({
data: {
msg:'hello world',
nickname: '',
img:'',
},
)}
2:获取微信用户的头像和昵称 :
index.wxml:
<view>
<button bindtap="getUserInfo" type="primary">获取用户信息</button>
{{nickname}}
<image style = "height: 100px;width: 100px;" src="{{img}}"></image>
</view>
index.js:
//获取微信用户的头像和昵称
getUserInfo(){
wx.getUserProfile({
desc: '获取用户信息',
success: (res)=>{
console.log(res.userInfo)
//为数据赋值
this.setData({
nickname:res.userInfo.nickName,
img:res.userInfo.avatarUrl,
})
}
})
},
3:微信登录 获取登录用户的授权码:
index.wxml
<view>
<button type="warn" bindtap="WeCharLogin">微信登录</button>
</view>
index.js
WeCharLogin(){
wx.login({
success: (userid)=>{
console.log(userid.code)
}
})
},
4:发送请求:
index.wxml
<view>
<button type="default" bindtap="sendRequest">发送请求</button>
</view>
index.js
sendRequest(){
wx.request({
url: 'http://localhost:8080/user/shop/status',
method: 'GET',
success: (res)=>{
console.log(res.data)
}
})
},
运行最后一个发送请求的代码时,需要将后端服务开启。
三:微信登录功能实现:
- 导入小程序代码
- 微信登录流程
- 需求分析和设计
- 代码开发
- 功能测试
1:导入小程序代码:
2:微信登录流程:
3:需求设计和分析:
业务规则:
- 基于微信登录实现小程序的登录功能
- 如果是新用户需要自动完成注册
4:代码开发:
配置为微信用户生成jwt令牌时使用的配置项:
配置包括两个部分:
- 配置用户端的jwt令牌
- 配置微信的appid和secret
根据接口定义创建UserController的login方法:
Controll层代码:
package com.sky.controller.user;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.ptg.AreaNPtg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@RestController
@RequestMapping("/user/user")
@Api(tags = "用户模块接口")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
@Autowired
private JwtProperties jwtProperties;
/**
* 微信用户登录
* @param userLoginDTO
* @return
*/
@PostMapping("/login")
@ApiOperation("用户登录接口")
public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
log.info("用户端登录:{}",userLoginDTO.getCode());
//获取登录的用户
User user = userService.wxlogin(userLoginDTO);
//生成jwt令牌
HashMap<String, Object> claims = new HashMap<>();
claims.put(JwtClaimsConstant.USER_ID,user.getId());
String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
//封装这个UserLoginVO对象
final UserLoginVO userLoginVO = UserLoginVO.builder()
.id(user.getId())
.openid(user.getOpenid())
.token(token)
.build();
return Result.success(userLoginVO);
}
}
创建UserServiceImpl实现类
- 调用微信接口服务,获取当前微信用户的openid(httpt)
- 解析由httpclient返回的json格式的数据
- 判断这个openid是否为空,为空直接抛出异常
- 判断是否为新用户
- 如果是新用户,自动完成注册
Service层代码:
package com.sky.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Autowired
private WeChatProperties weChatProperties;
@Autowired
private UserMapper userMapper;
//微信服务接口地址
private final static String WX_Login = "https://api.weixin.qq.com/sns/jscode2session";
/**
* 微信登录
* @param userLoginDTO
* @return
*/
@Override
public User wxlogin(UserLoginDTO userLoginDTO) {
//调用微信接口服务,获得当前微信用户的openid
final HashMap<String, String> map = getStringStringHashMap(userLoginDTO);
String json = HttpClientUtil.doGet(WX_Login, map);//返回值是一个json格式的数据
//解析这个JSON的数据
final JSONObject jsonObject = JSON.parseObject(json);
final String openid = jsonObject.getString("openid");
//判断openid是否为空 为空,直接抛业务异常
if(openid == null){
throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
}
//判断当前用户是否为新用户
User user = userMapper.GetByopenid(openid);
//如果是新用户,自动完成注册
if(user==null){
//给这个新用户赋值
user = User.builder()
.openid(openid)
.createTime(LocalDateTime.now())
.build();
userMapper.insert(user);
}
return user;
}
private HashMap<String, String> getStringStringHashMap(UserLoginDTO userLoginDTO) {
HashMap<String,String> map = new HashMap<>();
map.put("appid",weChatProperties.getAppid());
map.put("secret",weChatProperties.getSecret());
map.put("js_code", userLoginDTO.getCode());
map.put("grant_type","authorization_code");
return map;
}
}
Mapper层及注解:
package com.sky.mapper;
import com.sky.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
/**
* 查询当前用户是否为新用户
* @param openid
*/
@Select("select * from sky_take_out.user where openid = #{openid}")
User GetByopenid(String openid);
/**
* 添加用户
* @param user
*/
void insert(User user);
}
<?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.sky.mapper.UserMapper">
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into sky_take_out.user(openid, name, phone, sex, id_number, avatar, create_time)
value (#{openid},#{name},#{phone},#{sex},#{idNumber},#{avatar},#{createTime})
</insert>
</mapper>