目录
1 WeChatProperties的赋值
现在有WeChatProperties.class如下:
@Component
@ConfigurationProperties(prefix = "xxx.wechat")
@Data
public class WeChatProperties {
private String appid; //小程序的appid
private String secret; //小程序的秘钥
//其它微信支付相关内容...
}
在application.yml中,配置appid和secert,如下:
xxx:
wechat:
appid: xx
secret: yy
其中appid和 secert的获取方式,如下:
2 控制层相关操作
通过微信小程序官方文档的文档,我们可以知道我们需要获取code,如下:
所以我们就可以设计一个DTO来接收,如下:
@Data
public class UserLoginDTO implements Serializable {
private String code;
}
因此,我们在控制层有代码如下:
public class UserController {
//从请求中获取code
public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
// 微信登录
User user = userService.wxLogin(userLoginDTO);
//为用户生成JWT令牌,这里因人而异就不提供相关代码了
//主要返回用户数据库中的id和JWT令牌外加登录获得的的openid(用户唯一标识)
UserLoginVO userLoginVO = UserLoginVO.builder()
.id(user.getId())
.token(token)
.openid(user.getOpenid())
.build();
return Result.success(userLoginVO);
}
}
3 服务层相关操作
在控制层得到code之后,我们就能向小程序官方文档指定的连接发出Get请求,如下:
https://api.weixin.qq.com/sns/jscode2session
先整一个发送Get请求的工具类,如下:
public class HttpClientUtil {
public static String doGet(String url,Map<String,String> paramMap){
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
CloseableHttpResponse response = null;
try{
URIBuilder builder = new URIBuilder(url);
if(paramMap != null){
for (String key : paramMap.keySet()) {
builder.addParameter(key,paramMap.get(key));
}
}
URI uri = builder.build();
//创建GET请求
HttpGet httpGet = new HttpGet(uri);
//发送请求
response = httpClient.execute(httpGet);
//判断响应状态
if(response.getStatusLine().getStatusCode() == 200){
result = EntityUtils.toString(response.getEntity(),"UTF-8");
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
然后我们就可以在服务层发送Get请求获取openid,请求的内容为控制层相关操作中所示请求参数
@Service
public class UserServiceImpl implements UserService {
//get请求的链接
public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
/**
* 微信登录
* @param userLoginDTO
* @return
*/
@Override
public User wxLogin(UserLoginDTO userLoginDTO) {
//调用微信接口服务,获取openId
String openid = getOpenId(userLoginDTO.getCode());
//判断openId是否为空,为空则抛出异常
//判断是否为新用户,是则插入数据库,不是则返回
User user = userMapper.getByOpenId(openid);
if (user == null) {
//其它代码
}
return user;
}
/**
* 获取openId
* @param code
* @return
*/
private String getOpenId(String code) {
Map<String, String> map = new HashMap<>();
map.put("appid", weChatProperties.getAppid());
map.put("secret", weChatProperties.getSecret());
map.put("js_code", code);
map.put("grant_type", "authorization_code");
String json = HttpClientUtil.doGet(WX_LOGIN, map);
JSONObject jsonObj = JSON.parseObject(json);
String openid = jsonObj.getString("openid");
return openid;
}
}