前置条件
一、需要开发者ID(AppId)和密钥(AppSecret)(注意:小程序和公众号主体需要和微信开放平台绑定,并进行开发者资质认定)
二、代码实现
1.引入相关jar包
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.4</version>
</dependency>
2.所用工具类(小程序,公众号通用)
package com.xiaoqiu.driving.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
//链接url下载图片
public static void downloadPicture(String urlList, String path) {
URL url = null;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.小程序登录接口实现
package com.xiaoqiu.driving.pojo.vo;
import lombok.Data;
@Data
public class WxLoginVo {
/** 微信code */
private String code;
/** 微信昵称 */
private String nickName;
/** 微信头像 */
private String avatarUrl;
}
package com.xiaoqiu.driving.controller;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoqiu.driving.pojo.Users;
import com.xiaoqiu.driving.pojo.vo.WxLoginVo;
import com.xiaoqiu.driving.service.UsersService;
import com.xiaoqiu.driving.utils.HttpClientUtil;
import com.xiaoqiu.driving.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 用户信息表 前端控制器
* </p>
*
* @author
* @since 2023-04-13
*/
@Api
@RestController
@RequestMapping("/driving/users")
public class UsersController {
public final static String appId = "********";
public final static String secret = "*************";
// 微信小程序授权登录请求的网址
public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
@Autowired
private UsersService userService;
@Autowired
private RestTemplate restTemplate;
@PostMapping("/weixinLogin")
@ResponseBody
@ApiOperation("用户授权登录")
public R weixinLogin(@RequestBody WxLoginVo userLoginVo) throws Exception {
// 接收前端参数
String code = userLoginVo.getCode(); //code
String avatar = userLoginVo.getAvatarUrl(); //头像
String nickname = userLoginVo.getNickName(); //微信昵称
System.out.println("小程序登录");
if (StringUtils.isEmpty(code)) {
return R.error().message("code不能为空");
}
//需要拿客户端获得的code换取openId
String url = String.format(WX_LOGIN_URL, appId, secret, code);
//调用微信api授权
String data = HttpClientUtil.doGet(url);
System.out.println("请求结果:" + data);
//解析返回的json字符串属性 类型 说明
JSONObject jsonObject = JSONObject.parseObject(data);
String openId = jsonObject.getString("openid");
if (StringUtils.isEmpty(openId)){
return R.error().message("未获取到openId");
}
Users user = this.userService.getOne(new QueryWrapper<Users>().eq("openid",openId));
if (user != null){
System.out.println("老用户");
user.setAvatar(avatar);
//存入数据库的微信昵称采用base64编码处理
byte[] bytes = Base64.encodeBase64(nickname.getBytes("utf-8"));
user.setNickname(new String(bytes));
this.userService.updateById(user);
//返回昵称还用原来的
user.setNickname(nickname);
return R.ok().data("user",user);
}else {
System.out.println("新用户");
// 新用户
Users newUser = new Users();
newUser.setOpenid(openId);
newUser.setAvatar(avatar);
//存入数据库的微信昵称采用base64编码处理
byte[] bytes = Base64.encodeBase64(nickname.getBytes("utf-8"));
newUser.setNickname(new String(bytes));
boolean save = this.userService.save(newUser);
// 返回用户信息
Users byId = this.userService.getById(newUser.getId());
//返回昵称还用原来的
byId.setNickname(nickname);
return save ? R.ok().data("user",byId) : R.error().message("添加新用户失败");
}
}
}
4.公众号登录实现
package com.xqkj.jingqu.controller;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xqkj.jingqu.entity.Fangwen;
import com.xqkj.jingqu.entity.User;
import com.xqkj.jingqu.service.FangwenService;
import com.xqkj.jingqu.service.UserService;
import com.xqkj.jingqu.util.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* <p>
* 用户 前端控制器
* </p>
*
* @author yaodongqiang
* @since 2022-08-05
*/
@RestController
@CrossOrigin
@RequestMapping("/jingqu/user")
public class UserController {
public final static String appId = "*********";
public final static String secret = "*********";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 微信公众号授权登录请求的网址
public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
@Autowired
private UserService userService;
@GetMapping("/weixinLoginCeshi/{code}")
@ResponseBody
@ApiOperation("用户授权登录")
public R weixinLoginCeshi(@PathVariable String code) throws Exception {
System.out.println("公众号登录");
if (StringUtils.isEmpty(code)) {
return R.error().message("code不能为空");
}
//需要拿客户端获得的code换取openId
String url = String.format(WX_LOGIN_URL, appId, secret, code);
//调用微信api授权
String data = HttpClientUtil.doGet(url);
System.out.println("请求结果:" + data);
//解析返回的json字符串
JSONObject jsonObject = JSONObject.parseObject(data);
//获取openid和token值
String openId = jsonObject.getString("openid");
String accessToken = jsonObject.getString("access_token");
if (StringUtils.isEmpty(openId)) {
return R.error().message("未获取到openId");
}
// 通过openid 和 accessToken 来获取用户信息
// 拼接请求地址
String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
//发送请求
String urlRequest = HttpClientUtil.doGet(requestUrl);
//解析返回的json字符串
JSONObject userInfo = JSONObject.parseObject(urlRequest);
//获取用户微信昵称和头像
String nickname = userInfo.getString("nickname");
String avatar = userInfo.getString("headimgurl");
//根据openid从数据库中查询用户
User user = this.userService.getOne(new QueryWrapper<User>().eq("openid",openId));
if (user != null) {
System.out.println("老用户");
user.setAvatar(avatar);
//存入数据库的微信昵称采用base64编码处理
byte[] bytes = Base64.encodeBase64(nickname.getBytes("utf-8"));
user.setNickname(new String(bytes));
this.userService.updateById(user);
//返回昵称还用原来的
user.setNickname(nickname);
return R.ok().data("user", user);
} else {
System.out.println("新用户");
// 新用户
User newUser = new User();
newUser.setOpenid(openId);
newUser.setAvatar(avatar);
//存入数据库的微信昵称采用base64编码处理
byte[] bytes = Base64.encodeBase64(nickname.getBytes("utf-8"));
newUser.setNickname(new String(bytes));
boolean save = this.userService.save(newUser);
//返回昵称还用原来的
newUser.setNickname(nickname);
return save ? R.ok().data("user", newUser) : R.error().message("添加新用户失败");
}
}
}