当前位置:   article > 正文

java微信小程序登录,公众号登录(复制即可使用)

java微信小程序登录

前置条件

一、需要开发者ID(AppId)和密钥(AppSecret)(注意:小程序和公众号主体需要和微信开放平台绑定,并进行开发者资质认定)

 二、代码实现

1.引入相关jar包

  1. <!--httpclient-->
  2. <dependency>
  3. <groupId>org.apache.httpcomponents</groupId>
  4. <artifactId>httpclient</artifactId>
  5. <version>4.5.6</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.alibaba</groupId>
  9. <artifactId>fastjson</artifactId>
  10. <version>2.0.4</version>
  11. </dependency>

2.所用工具类(小程序,公众号通用)

  1. package com.xiaoqiu.driving.utils;
  2. import org.apache.http.NameValuePair;
  3. import org.apache.http.client.entity.UrlEncodedFormEntity;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpGet;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.client.utils.URIBuilder;
  8. import org.apache.http.entity.ContentType;
  9. import org.apache.http.entity.StringEntity;
  10. import org.apache.http.impl.client.CloseableHttpClient;
  11. import org.apache.http.impl.client.HttpClients;
  12. import org.apache.http.message.BasicNameValuePair;
  13. import org.apache.http.util.EntityUtils;
  14. import java.io.*;
  15. import java.net.MalformedURLException;
  16. import java.net.URI;
  17. import java.net.URL;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Map;
  21. public class HttpClientUtil {
  22. public static String doGet(String url, Map<String, String> param) {
  23. // 创建Httpclient对象
  24. CloseableHttpClient httpclient = HttpClients.createDefault();
  25. String resultString = "";
  26. CloseableHttpResponse response = null;
  27. try {
  28. // 创建uri
  29. URIBuilder builder = new URIBuilder(url);
  30. if (param != null) {
  31. for (String key : param.keySet()) {
  32. builder.addParameter(key, param.get(key));
  33. }
  34. }
  35. URI uri = builder.build();
  36. // 创建http GET请求
  37. HttpGet httpGet = new HttpGet(uri);
  38. // 执行请求
  39. response = httpclient.execute(httpGet);
  40. // 判断返回状态是否为200
  41. if (response.getStatusLine().getStatusCode() == 200) {
  42. resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
  43. }
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. } finally {
  47. try {
  48. if (response != null) {
  49. response.close();
  50. }
  51. httpclient.close();
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. return resultString;
  57. }
  58. public static String doGet(String url) {
  59. return doGet(url, null);
  60. }
  61. public static String doPost(String url, Map<String, String> param) {
  62. // 创建Httpclient对象
  63. CloseableHttpClient httpClient = HttpClients.createDefault();
  64. CloseableHttpResponse response = null;
  65. String resultString = "";
  66. try {
  67. // 创建Http Post请求
  68. HttpPost httpPost = new HttpPost(url);
  69. // 创建参数列表
  70. if (param != null) {
  71. List<NameValuePair> paramList = new ArrayList<>();
  72. for (String key : param.keySet()) {
  73. paramList.add(new BasicNameValuePair(key, param.get(key)));
  74. }
  75. // 模拟表单
  76. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
  77. httpPost.setEntity(entity);
  78. }
  79. // 执行http请求
  80. response = httpClient.execute(httpPost);
  81. resultString = EntityUtils.toString(response.getEntity(), "utf-8");
  82. } catch (Exception e) {
  83. e.printStackTrace();
  84. } finally {
  85. try {
  86. response.close();
  87. } catch (IOException e) {
  88. e.printStackTrace();
  89. }
  90. }
  91. return resultString;
  92. }
  93. public static String doPost(String url) {
  94. return doPost(url, null);
  95. }
  96. public static String doPostJson(String url, String json) {
  97. // 创建Httpclient对象
  98. CloseableHttpClient httpClient = HttpClients.createDefault();
  99. CloseableHttpResponse response = null;
  100. String resultString = "";
  101. try {
  102. // 创建Http Post请求
  103. HttpPost httpPost = new HttpPost(url);
  104. // 创建请求内容
  105. StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
  106. httpPost.setEntity(entity);
  107. // 执行http请求
  108. response = httpClient.execute(httpPost);
  109. resultString = EntityUtils.toString(response.getEntity(), "utf-8");
  110. } catch (Exception e) {
  111. e.printStackTrace();
  112. } finally {
  113. try {
  114. response.close();
  115. } catch (IOException e) {
  116. e.printStackTrace();
  117. }
  118. }
  119. return resultString;
  120. }
  121. //链接url下载图片
  122. public static void downloadPicture(String urlList, String path) {
  123. URL url = null;
  124. try {
  125. url = new URL(urlList);
  126. DataInputStream dataInputStream = new DataInputStream(url.openStream());
  127. FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
  128. ByteArrayOutputStream output = new ByteArrayOutputStream();
  129. byte[] buffer = new byte[1024];
  130. int length;
  131. while ((length = dataInputStream.read(buffer)) > 0) {
  132. output.write(buffer, 0, length);
  133. }
  134. fileOutputStream.write(output.toByteArray());
  135. dataInputStream.close();
  136. fileOutputStream.close();
  137. } catch (MalformedURLException e) {
  138. e.printStackTrace();
  139. } catch (IOException e) {
  140. e.printStackTrace();
  141. }
  142. }
  143. }

3.小程序登录接口实现

  1. package com.xiaoqiu.driving.pojo.vo;
  2. import lombok.Data;
  3. @Data
  4. public class WxLoginVo {
  5. /** 微信code */
  6. private String code;
  7. /** 微信昵称 */
  8. private String nickName;
  9. /** 微信头像 */
  10. private String avatarUrl;
  11. }
  1. package com.xiaoqiu.driving.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  4. import com.xiaoqiu.driving.pojo.Users;
  5. import com.xiaoqiu.driving.pojo.vo.WxLoginVo;
  6. import com.xiaoqiu.driving.service.UsersService;
  7. import com.xiaoqiu.driving.utils.HttpClientUtil;
  8. import com.xiaoqiu.driving.utils.R;
  9. import io.swagger.annotations.Api;
  10. import io.swagger.annotations.ApiOperation;
  11. import org.apache.commons.codec.binary.Base64;
  12. import org.apache.commons.lang3.StringUtils;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.http.HttpEntity;
  15. import org.springframework.http.HttpHeaders;
  16. import org.springframework.http.ResponseEntity;
  17. import org.springframework.web.bind.annotation.*;
  18. import org.springframework.web.client.RestTemplate;
  19. import java.util.HashMap;
  20. import java.util.Map;
  21. /**
  22. * <p>
  23. * 用户信息表 前端控制器
  24. * </p>
  25. *
  26. * @author
  27. * @since 2023-04-13
  28. */
  29. @Api
  30. @RestController
  31. @RequestMapping("/driving/users")
  32. public class UsersController {
  33. public final static String appId = "********";
  34. public final static String secret = "*************";
  35. // 微信小程序授权登录请求的网址
  36. 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";
  37. @Autowired
  38. private UsersService userService;
  39. @Autowired
  40. private RestTemplate restTemplate;
  41. @PostMapping("/weixinLogin")
  42. @ResponseBody
  43. @ApiOperation("用户授权登录")
  44. public R weixinLogin(@RequestBody WxLoginVo userLoginVo) throws Exception {
  45. // 接收前端参数
  46. String code = userLoginVo.getCode(); //code
  47. String avatar = userLoginVo.getAvatarUrl(); //头像
  48. String nickname = userLoginVo.getNickName(); //微信昵称
  49. System.out.println("小程序登录");
  50. if (StringUtils.isEmpty(code)) {
  51. return R.error().message("code不能为空");
  52. }
  53. //需要拿客户端获得的code换取openId
  54. String url = String.format(WX_LOGIN_URL, appId, secret, code);
  55. //调用微信api授权
  56. String data = HttpClientUtil.doGet(url);
  57. System.out.println("请求结果:" + data);
  58. //解析返回的json字符串属性 类型 说明
  59. JSONObject jsonObject = JSONObject.parseObject(data);
  60. String openId = jsonObject.getString("openid");
  61. if (StringUtils.isEmpty(openId)){
  62. return R.error().message("未获取到openId");
  63. }
  64. Users user = this.userService.getOne(new QueryWrapper<Users>().eq("openid",openId));
  65. if (user != null){
  66. System.out.println("老用户");
  67. user.setAvatar(avatar);
  68. //存入数据库的微信昵称采用base64编码处理
  69. byte[] bytes = Base64.encodeBase64(nickname.getBytes("utf-8"));
  70. user.setNickname(new String(bytes));
  71. this.userService.updateById(user);
  72. //返回昵称还用原来的
  73. user.setNickname(nickname);
  74. return R.ok().data("user",user);
  75. }else {
  76. System.out.println("新用户");
  77. // 新用户
  78. Users newUser = new Users();
  79. newUser.setOpenid(openId);
  80. newUser.setAvatar(avatar);
  81. //存入数据库的微信昵称采用base64编码处理
  82. byte[] bytes = Base64.encodeBase64(nickname.getBytes("utf-8"));
  83. newUser.setNickname(new String(bytes));
  84. boolean save = this.userService.save(newUser);
  85. // 返回用户信息
  86. Users byId = this.userService.getById(newUser.getId());
  87. //返回昵称还用原来的
  88. byId.setNickname(nickname);
  89. return save ? R.ok().data("user",byId) : R.error().message("添加新用户失败");
  90. }
  91. }
  92. }

4.公众号登录实现

  1. package com.xqkj.jingqu.controller;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  4. import com.xqkj.jingqu.entity.Fangwen;
  5. import com.xqkj.jingqu.entity.User;
  6. import com.xqkj.jingqu.service.FangwenService;
  7. import com.xqkj.jingqu.service.UserService;
  8. import com.xqkj.jingqu.util.*;
  9. import io.swagger.annotations.ApiOperation;
  10. import org.apache.commons.codec.binary.Base64;
  11. import org.apache.commons.lang3.StringUtils;
  12. import org.apache.http.entity.ContentType;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.mock.web.MockMultipartFile;
  15. import org.springframework.web.bind.annotation.*;
  16. import org.springframework.web.multipart.MultipartFile;
  17. import javax.validation.Valid;
  18. import java.io.*;
  19. import java.text.SimpleDateFormat;
  20. import java.util.ArrayList;
  21. import java.util.Date;
  22. import java.util.List;
  23. /**
  24. * <p>
  25. * 用户 前端控制器
  26. * </p>
  27. *
  28. * @author yaodongqiang
  29. * @since 2022-08-05
  30. */
  31. @RestController
  32. @CrossOrigin
  33. @RequestMapping("/jingqu/user")
  34. public class UserController {
  35. public final static String appId = "*********";
  36. public final static String secret = "*********";
  37. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  38. // 微信公众号授权登录请求的网址
  39. 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";
  40. @Autowired
  41. private UserService userService;
  42. @GetMapping("/weixinLoginCeshi/{code}")
  43. @ResponseBody
  44. @ApiOperation("用户授权登录")
  45. public R weixinLoginCeshi(@PathVariable String code) throws Exception {
  46. System.out.println("公众号登录");
  47. if (StringUtils.isEmpty(code)) {
  48. return R.error().message("code不能为空");
  49. }
  50. //需要拿客户端获得的code换取openId
  51. String url = String.format(WX_LOGIN_URL, appId, secret, code);
  52. //调用微信api授权
  53. String data = HttpClientUtil.doGet(url);
  54. System.out.println("请求结果:" + data);
  55. //解析返回的json字符串
  56. JSONObject jsonObject = JSONObject.parseObject(data);
  57. //获取openid和token值
  58. String openId = jsonObject.getString("openid");
  59. String accessToken = jsonObject.getString("access_token");
  60. if (StringUtils.isEmpty(openId)) {
  61. return R.error().message("未获取到openId");
  62. }
  63. // 通过openid 和 accessToken 来获取用户信息
  64. // 拼接请求地址
  65. String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
  66. requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
  67. //发送请求
  68. String urlRequest = HttpClientUtil.doGet(requestUrl);
  69. //解析返回的json字符串
  70. JSONObject userInfo = JSONObject.parseObject(urlRequest);
  71. //获取用户微信昵称和头像
  72. String nickname = userInfo.getString("nickname");
  73. String avatar = userInfo.getString("headimgurl");
  74. //根据openid从数据库中查询用户
  75. User user = this.userService.getOne(new QueryWrapper<User>().eq("openid",openId));
  76. if (user != null) {
  77. System.out.println("老用户");
  78. user.setAvatar(avatar);
  79. //存入数据库的微信昵称采用base64编码处理
  80. byte[] bytes = Base64.encodeBase64(nickname.getBytes("utf-8"));
  81. user.setNickname(new String(bytes));
  82. this.userService.updateById(user);
  83. //返回昵称还用原来的
  84. user.setNickname(nickname);
  85. return R.ok().data("user", user);
  86. } else {
  87. System.out.println("新用户");
  88. // 新用户
  89. User newUser = new User();
  90. newUser.setOpenid(openId);
  91. newUser.setAvatar(avatar);
  92. //存入数据库的微信昵称采用base64编码处理
  93. byte[] bytes = Base64.encodeBase64(nickname.getBytes("utf-8"));
  94. newUser.setNickname(new String(bytes));
  95. boolean save = this.userService.save(newUser);
  96. //返回昵称还用原来的
  97. newUser.setNickname(nickname);
  98. return save ? R.ok().data("user", newUser) : R.error().message("添加新用户失败");
  99. }
  100. }
  101. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/635690
推荐阅读
相关标签
  

闽ICP备14008679号