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

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

一、使用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";

    @Autowired
    private 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
     */
    @Autowired
    private AccessTokenRedis accessTokenRedis;
    /**
     * WeiUser 业务逻辑层
     */
    @Autowired
    private WeiUserService weiUserService;

    /**
     * 当用户关注微信公共号时,收集个人信息
     * */
    public void weixinUserInfoUtil(String openid){
        //1.调用微信,获取用户基本信息接口 完成JSONObject
        JSONObject 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 {

    @Autowired
    private WeiUserService weiUserService;

    @Autowired
    private UserInfoUtil userInfoUtil;
    /**用户表业务逻辑层*/
    @Autowired
    private UserService userService;

    @GetMapping("userInfo")
    //weixinMenu/userInfo
    public 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/userInfo
    public 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>

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值