微信小程序之获取用户基本信息

一、使用Redis存储access-token

package com.qfjy.project.weixin.api.accessToken;import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;import java.util.concurrent.TimeUnit;@Component
@Slf4j
public class AccessTokenRedis {private static  String REDIS_ACCESS_TOKEN_KEY="wexin:access_token";@Autowiredprivate RedisTemplate<String,Object> redisTemplate;public String getAccessTokenValue(){if(redisTemplate.hasKey(REDIS_ACCESS_TOKEN_KEY)){return (String) redisTemplate.opsForValue().get(REDIS_ACCESS_TOKEN_KEY);}else{redisTemplate.opsForValue().set(REDIS_ACCESS_TOKEN_KEY, this.getAccessTokenVal());redisTemplate.expire(REDIS_ACCESS_TOKEN_KEY, 2, TimeUnit.HOURS);}return null;}private static String WERXIN_ACCESS_TOKEN_GET_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";private String getAccessTokenVal(){String path=WERXIN_ACCESS_TOKEN_GET_URL.replace("APPID", MenuManager.appId).replace("APPSECRET", MenuManager.appSecret);JSONObject jsonObject= WeixinUtil.httpRequest(path, "GET", null);return jsonObject.getString("access_token");}
}

二、调用微信服务器获取信息

package com.qfjy.project.weixin.api.UserInfo;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfjy.entity.po.WeiUser;
import com.qfjy.project.weixin.api.accessToken.AccessTokenRedis;
import com.qfjy.project.weixin.util.WeixinUtil;
import com.qfjy.service.WeiUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;@Component
@Slf4j
public class UserInfoUtil {/*** Redis 方式解决access_Token*/@Autowiredprivate AccessTokenRedis accessTokenRedis;/*** WeiUser 业务逻辑层*/@Autowiredprivate WeiUserService weiUserService;/*** 当用户关注微信公共号时,收集个人信息* */public void weixinUserInfoUtil(String openid){//1.调用微信,获取用户基本信息接口 完成JSONObjectJSONObject jsonObject=this.getWeixinUserByOpenid(openid);//2.需要将JSONObject转换成weiuser对象WeiUser weiUser=this.getJSONObjectConvertWeiUser(jsonObject);//3.对WeiUser接口实现 添加操作int num=this.addWeiUser(weiUser);}/*** 调用微信 获取用户基本信息接口*//*** 获取用户基本信息(包括UnionID机制)* 开发者通过OpenID来获取用户基本信息,请使用https协议*/private static String WEIXIN_API_GET_USER_INFO="https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";/*** 1. 调用微信 获取用户基本信息接口*/public JSONObject getWeixinUserByOpenid(String openid){String url = WEIXIN_API_GET_USER_INFO.replace("ACCESS_TOKEN", accessTokenRedis.getAccessTokenValue()).replace("OPENID", openid);JSONObject jsonObject = WeixinUtil.httpRequest(url,"GET", null);log.info("获取用户基本信息"+jsonObject.toString());return jsonObject;}/*** 2. 需要将JSONObject转换成weiuser对象*/public WeiUser getJSONObjectConvertWeiUser(JSONObject jsonObject){// WeiUser weiUser=new WeiUser();//weiUser.setNickname((jsonObject.getString("nickname")));//JSON直接转JAVA对象,需要注意点:JSON中的KEY和VALUE,对象中必须存在对应的SET方法ObjectMapper objectMapper=new ObjectMapper();WeiUser weiUser=new WeiUser();try {weiUser= objectMapper.readValue(jsonObject.toString(),WeiUser.class);} catch (JsonProcessingException e) {e.printStackTrace();}return weiUser;}/*** 3. 添加到weiuser表中*/public int addWeiUser(WeiUser weiUser){int num=  weiUserService.insertSelective(weiUser);log.info("收集到微信的个人信息存入到数据库"+num);return num;}
}

Quath的使用

package com.qfjy.project.ouath;import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;@RequestMapping("weixin")
@Controller
@Slf4j
public class  WeiXinOuath {@GetMapping("ouath")public void ouath(HttpServletResponse response)throws IOException {String url="http://njqfjy.natapp1.cc/weixin/invoke";url= URLEncoder.encode(url,"UTF-8");String path="https://open.weixin.qq.com/connect/oauth2/authorize?" +"appid=" + MenuManager.appId+"&redirect_uri=" +url+"&response_type=code" +"&scope=snsapi_userinfo" +"&state=java2101" +"#wechat_redirect";response.sendRedirect(path);}//http://njqfjy.natapp1.cc/weixin/invoke?code=CODE&state=STATE。@RequestMapping("invoke")public String invoke(HttpServletRequest request){//获得授权码code//如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。String code=request.getParameter("code");String state=request.getParameter("state");//通过code换取网页授权access_token(微信认证服务器)String path="https://api.weixin.qq.com/sns/oauth2/access_token?" +"appid=" +MenuManager.appId+"&secret=" + MenuManager.appSecret+"&code=" +code+"&grant_type=authorization_code";JSONObject jsonObject= WeixinUtil.httpRequest(path, "GET", null);log.info(jsonObject.toString());String access_token=jsonObject.getString("access_token");String openid=jsonObject.getString("openid");//通过access_token获取用户信息String url="https://api.weixin.qq.com/sns/userinfo?" +"access_token=" +access_token+"&openid=" +openid+"&lang=zh_CN";JSONObject jsonObject1= WeixinUtil.httpRequest(url, "GET", null);request.setAttribute("jsonObj",jsonObject1);return "Oauth";}
}
package com.qfjy.project.ouath;import com.qfjy.entity.po.User;
import com.qfjy.entity.po.WeiUser;
import com.qfjy.project.weixin.api.UserInfo.UserInfoUtil;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import com.qfjy.service.UserService;
import com.qfjy.service.WeiUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;/*** TODO 微信开发 菜单 Oauth* */
@RequestMapping("weixinMenu")
@Slf4j
@Controller
public class WeixinMenuOauth {@Autowiredprivate WeiUserService weiUserService;@Autowiredprivate UserInfoUtil userInfoUtil;/**用户表业务逻辑层*/@Autowiredprivate UserService userService;@GetMapping("userInfo")//weixinMenu/userInfopublic void ouath(HttpServletResponse response)throws IOException {String url=MenuManager.REAL_URL+"weixinMenu/userInfoInvoke";url= URLEncoder.encode(url,"UTF-8");String path="https://open.weixin.qq.com/connect/oauth2/authorize?" +"appid=" + MenuManager.appId+"&redirect_uri=" +url+"&response_type=code" +"&scope=snsapi_base" +"&state=java2101" +"#wechat_redirect";response.sendRedirect(path);}@RequestMapping("userInfoInvoke")public String invoke(HttpServletRequest request){//获得授权码code//如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。String code=request.getParameter("code");String state=request.getParameter("state");//通过code换取网页授权access_token(微信认证服务器)String path="https://api.weixin.qq.com/sns/oauth2/access_token?" +"appid=" +MenuManager.appId+"&secret=" + MenuManager.appSecret+"&code=" +code+"&grant_type=authorization_code";JSONObject jsonObject= WeixinUtil.httpRequest(path, "GET", null);log.info(jsonObject.toString());String access_token=jsonObject.getString("access_token");String openid=jsonObject.getString("openid");//根据weiUser查询openid表中是否存在WeiUser weiUser=weiUserService.selectWeiUserByOpenid(openid);if(weiUser==null){log.error("系统中未收集到该用户信息"+openid);//执行收集微信个人信息代码业务逻辑userInfoUtil.weixinUserInfoUtil(openid);weiUser=weiUserService.selectWeiUserByOpenid(openid);}//再去user表中查询wei值是否存在User user=  userService.selectUserByWid(weiUser.getId());if(user==null){//如果user为空  未登录request.setAttribute("wid", weiUser.getId());request.setAttribute("openid", weiUser.getOpenid());return "weixin/user/login";}else{//如果user不为空  已经登录request.setAttribute("user", user);return "weixin/user/userInfo";}}//###########TODO 会议发布按钮@GetMapping("meetingPub")//weixinMenu/userInfopublic void meetingPub(HttpServletResponse response)throws IOException {String url=MenuManager.REAL_URL+"weixinMenu/meetingPubInvoke";url= URLEncoder.encode(url,"UTF-8");String path="https://open.weixin.qq.com/connect/oauth2/authorize?" +"appid=" + MenuManager.appId+"&redirect_uri=" +url+"&response_type=code" +"&scope=snsapi_base" +"&state=java2101" +"#wechat_redirect";response.sendRedirect(path);}@RequestMapping("meetingPubInvoke")public String meetingPubInvoke(HttpServletRequest request){//获得授权码code//如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。String code=request.getParameter("code");String state=request.getParameter("state");//通过code换取网页授权access_token(微信认证服务器)String path="https://api.weixin.qq.com/sns/oauth2/access_token?" +"appid=" +MenuManager.appId+"&secret=" + MenuManager.appSecret+"&code=" +code+"&grant_type=authorization_code";JSONObject jsonObject= WeixinUtil.httpRequest(path, "GET", null);log.info(jsonObject.toString());String access_token=jsonObject.getString("access_token");String openid=jsonObject.getString("openid");//根据weiUser查询openid表中是否存在WeiUser weiUser=weiUserService.selectWeiUserByOpenid(openid);if(weiUser==null){log.error("系统中未收集到该用户信息"+openid);//执行收集微信个人信息代码业务逻辑userInfoUtil.weixinUserInfoUtil(openid);weiUser=weiUserService.selectWeiUserByOpenid(openid);}//再去user表中查询wei值是否存在User user=  userService.selectUserByWid(weiUser.getId());if(user==null){//如果user为空  未登录request.setAttribute("wid", weiUser.getId());request.setAttribute("openid", weiUser.getOpenid());return "weixin/user/login";}else{//如果user不为空  是否发单组权限if(user.getRid()==1){request.setAttribute("uid", user.getId());return "weixin/meetingPub/meetingPubAdd";}else if(user.getRid()==2){return "unauth";}return "unauth";}}
}
<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Oauth2.0页面</title><!-- 引入 jQuery Mobile 样式 -->
<link rel="stylesheet" href="http://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.css">
<!-- 引入 jQuery 库 -->
<script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- 引入 jQuery Mobile 库 -->
<script src="http://apps.bdimg.com/libs/jquerymobile/1.4.5/jquery.mobile-1.4.5.min.js"></script><link href="https://cdn.bootcss.com/jquery-mobile/1.4.5/jquery.mobile.theme.css" rel="stylesheet"><style type="text/css">body {font-family:"微软雅黑,Arial";font-size:18px;padding:0px;margin:0 auto;}.font-blue{color:#4E90C7!important;}.input-lightblue{background-color: #E5F2FD!important;}.font-label{color: black!important;font-size: 19px!important;}</style>
</head>
<body>
<div data-role="page" id="pageMain" style=""><div data-role="header"  style="background-color: #4E90C7;" data-position="fixed"><a href="#" data-icon="back" data-role="button">返回</a><h1>个人信息</h1><a href="#" data-role="button" data-icon="home">主页</a></div><div data-role="content" style="padding: 0;text-align:center;width: 100%;line-height:60px!important" ><br/><br/><div ><img th:src="${jsonObj.headimgurl}" style="border-radius:25px;"src="http://thirdwx.qlogo.cn/mmopen/mzWlopn7rjMPaUOSRkZw7K4IGGyPSLWYKNtkibibkTgBAkicddl5icj6GIOaxu2DiaecymXmECE6nxQ7vxSRdFnnlMoVo1fQa4cvN/132"></div><div style="float: left;color: black;font-size:20px;width:auto;max-width:40%;padding-left: 15px;white-space: nowrap;overflow:hidden;text-overflow:ellipsis;text-algin:left;"><span style="font-size:28px;color:#E57330" th:text="${jsonObj.nickname}">微信名称</span></div><div style="text-align: right;padding-right:10px;white-space: nowrap;"><font style="font-size:28px;color:#E57330"><span th:text="${jsonObj.city}">城市</span>/<span th:text="${jsonObj.province}">省份</span>/<span th:text="${jsonObj.province}">国家</span></font> </div></div>
</div>
</body>
</html>

下一节,获取到用户,更新用户信息

微信小程序之获取用户基本信息相关推荐

  1. 微信小程序制作——获取用户信息

    微信小程序制作--获取用户信息 1.获取用户信息 方式一 wxml <view bindtap="getUserName">获取当前用户名</view> j ...

  2. php取微信名字和头像,微信小程序如何获取用户头像和昵称

    本文介绍了微信小程序如何获取用户头像和昵称,分享给大家,具体如下: 代码user.wxml: {{userInfo.nickName}} user.js //sort.js //獲取應用實例 var ...

  3. 微信小程序 getPhoneNumber获取用户手机号

    微信小程序 getPhoneNumber获取用户手机号 在使用getPhoneNumber前,可以先看下官方文档:文档地址 在注意这里,官方提到如果不使用之前wx.login调用获取的sessionK ...

  4. 微信小程序 访问ip服务器,微信小程序如何获取code?微信小程序如何获取用户ip?...

    微信小程序如何获取code?微信小程序如何获取用户ip?最近小编收到很多问题,其中一个就是下面小编为大家整理一下关于微信小程序如何获取code的步骤,希望这些方法能够帮助到大家. 首先,调用 wx.l ...

  5. 微信小程序——最新获取用户昵称和头像的方法总结

    前段时间微信小程序对获取用户昵称和头像方法进行了更新,网上很多的文章都已经不适用了,这里简单总结一下 首先,传统接口wx.getUserInfo的效果会弹出一个给用户的弹窗,需要用户授权,经过测试传统 ...

  6. 微信小程序授权获取用户信息和手机号码

    微信小程序授权获取用户信息和手机号码 1.微信官方文档 登录:https://developers.weixin.qq.com/miniprogram/dev/framework/open-abili ...

  7. 微信小程序授权 获取用户信息

    微信小程序授权 获取用户信息 小程序昵称突然变成了"微信用户",头像也不显示, <!-- 近期很多小伙伴通过该方法获取头像和昵称,代码也没有做改变,突然就变成了下面这样子 - ...

  8. 微信小程序之获取用户地址

    在微信小程序中获取定位信息 今天一整天基本上都在处理在微信小程序中获取准确地址,给出定位并给出所在城市的问题.经过走了半天弯路,现在总结一下所需要的步骤. 一. 先到腾讯位置服务中心获取KEY 通过小 ...

  9. 微信小程序中获取用户微信公众号授权(openid)用来发送模板消息

    需求: 由于小程序不能直接向用户发送模板消息,所以需要用公众号向用户发送模板消息. 于是需要将小程序的openid和公众号的openid绑定在一起.提供两种思路: 方法一: 1.微信小程序和公众号都绑 ...

最新文章

  1. 3YAdmin-专注通用权限控制与表单的后台管理系统模板
  2. 【Python 爬虫】 4、爬虫基本原理
  3. 【深度学习】每个数据科学家都必须了解的 6 种神经网络类型
  4. 机器学习基石HOW部分(2)
  5. 图解cacti简单使用
  6. 【emWin】例程十五:触摸校准实例——五点校准法
  7. eclipse添加注释模板
  8. 2007级计算机技术专科毕业设计,2007级计算机科学与技术本科毕业设计选题
  9. 彻底搞懂Gradle、Gradle Wrapper与Android Plugin for Gradle的区别和联系
  10. strel函数c语言写法,全国计算机等级考试二级C语言题型总结(二)——选择循环结构程序设计部分(5篇范文)...
  11. 【事件相机整理】信号处理、噪声与滤波
  12. 威纶通触摸屏控制台达变频器
  13. MATLAB_数值计算_线性方程组
  14. vue实现ZKT(中控)身份证读卡器读卡功能
  15. 中石油布局天然气商储 天然气国家储备有望
  16. Linux查看各种解压文件
  17. 16 使用Python下载数据
  18. 美国计算机加音乐专业,美国留学:原来这就是传说中炫酷到炸裂的电子音乐制作专业...
  19. 初级计算机管理,电脑入门学习初级.pdf
  20. JAVA PHP 按位异或运算_对php位运算^(按位异或)的理解

热门文章

  1. Beginning C# 7 Programming with Visual Studio 2017 免积分下载
  2. python常用函数库-Python常用库大全及简要说明
  3. [ 代码审计篇 ] 代码审计案例详解(二) XXE代码审计案例
  4. 北京大学2019年优秀中学生暑期学堂招生简章发布!
  5. 【场景化能力包】满足不同场景使用的解决方案
  6. 通信协议设计注意事项
  7. 百度api 人物漫画脸
  8. matlab在解析几何教学中的应用,Matlab在解析几何教学中的应用
  9. 27.iPhone加速度传感器简单介绍
  10. 批量把大量图片名称批量导入记事本或excel表格里(生成图片名目录)