【微信公众号开发Java版】获取用户信息

概述

新项目需要用到微信公众号的开发功能,所以整理了一篇相关的笔记,以供后续参考学习。

一、前期工作

(1)去微信公众平台申请一个测试公众号

怎么去申请微信公众号测试号可以去看我这篇文章:https://juejin.im/post/5ebf5a6a5188256d877dc509

申请成功后即可获取到一个测试公众账号的信息。主要有 appIDappsecret 两个参数,这将唯一标示一个公众号,并且需要将他们作为参数获取用户的信息(后面代码里面需要用!)。

(2)关注测试公众号

用户只有关注了这个公众号了,才能通过打开有公众号信息的链接去授权第三方登录,并获取用户信息的操作。故我们还需要用我们的微信关注微信号,

(3)设置回调域名

需要注意的是,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com 无法进行OAuth2.0鉴权





这里的回调页面域名我填写的是内网穿透的域名(切记,这里一定要填穿透的域名,否则调不通!!):


二、正式开发

如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。

首先可以看看我的项目整体结构(项目是用SpringBoot来构建的):


其中pom.xml引入的依赖如下:

<dependencies>
    <!--阿里巴巴 fastjson依赖-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.10</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.6</version>
    </dependency>


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>

其中WeChatUtil类的代码如下:

扫描二维码关注公众号,回复: 11322063 查看本文章
/**
 * 工具类
 * @Date: 2020/5/15 11:17
 */
public class WeChatUtil {

  public static final String TOKEN = "myJavaTokenStr";
  public static final String APP_ID = "wx3f4de6110bc03c95";
  public static final String APP_SECRET = "79b114b3e6492b3340b37a13c4081721";


  /**
   * @param url
   * @return
   * @throws Exception
   */
  public static JSONObject doGetJson(String url) throws Exception {
    JSONObject jsonObject =null;
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet httpGet =new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    HttpEntity entity =response.getEntity();
    if(entity!=null)
    {
      //把返回的结果转换为JSON对象
      String result = EntityUtils.toString(entity, "UTF-8");
      jsonObject =JSON.parseObject(result);
    }
    return jsonObject;
  }

  /**
   * shal加密
   * @param src
   * @return
   */
  public static String shal(String src){
    //获取一个加密对象
    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("sha1");

      char[] chars={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
      StringBuilder sb = new StringBuilder();
      //加密
      byte[] digest = md.digest(src.getBytes());
      //处理加密结果
      for (byte b : digest) {
        sb.append(chars[(b>>4)&15]) ;
        sb.append(chars[b&15]);
      }
      return sb.toString();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return null;
  }

}

根据官方文档,我分为了3步来获取用户得基本信息:

(1)第一步:用户同意授权,获取code

首先我们需要在关注的微信公众号里打开链接,以此来引导用户授权打开页面

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_re

参数说明:

参数 是否必填 说明
appid 公众号的唯一标识
redirect_uri 授权后重定向的回调链接地址,
response_type 返回类型,固定填写code
scope 应用授权作用域,snsapi_base ,snsapi_userinfo
state 可以不填
#wechat_redirect 必须带此参数

所以我的链接为(因为我需要获取到用户信息,所以scope我这里是snsapi_userinfo ):

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3f4de6110bc03c95&redirect_uri=http://b23f8223.ngrok.io/callBack&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect

(2)第二步:通过code换取网页授权access_token

上面的链接放到关注的微信公众号里面,然后点击进入如下图授权界面:


需要注意的是如果你没有关注该测试公众号,会出现如下界面(所以必须要关注了该公众号才能授权访问哦!):


点击允许之后就会请求以下的接口:http://b23f8223.ngrok.io/callBack ,并且会将code传递过来。

/**
 * 公众号微信登录授权同意之后回调地址
 * @param code
 * @return
 * @throws Exception
 */
@RequestMapping("/callBack")
public String callBack(String code) throws Exception{
 //通过code换取网页授权access_token
  String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ WeChatUtil.APP_ID
         + "&secret="+ WeChatUtil.APP_SECRET
         + "&code="+code
         + "&grant_type=authorization_code";
  JSONObject jsonObject = WeChatUtil.doGetJson(url);
  String openid = jsonObject.getString("openid");
  String access_token = jsonObject.getString("access_token");
  String refresh_token = jsonObject.getString("refresh_token");
  // 拉取用户信息(需scope为 snsapi_userinfo)
  String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token
        + "&openid="+openid
        + "&lang=zh_CN";
  System.out.println("infoUrl:"+infoUrl);
  JSONObject userInfo = WeChatUtil.doGetJson(infoUrl);
  System.out.println(userInfo);
  return "login";
}

(3)第三步:拉取用户信息(需scope为 snsapi_userinfo)

通过上面的步骤,我们可以成功获取到当前点击链接的用户信息:


小结

以上就是我关于微信公众号网页授权获取用户信息的相关总结内容,后续还会出其他的教程。如果在开发过程中遇到问题,可以参考微信开发平台官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

猜你喜欢

转载自blog.csdn.net/weixin_42135693/article/details/106162168
今日推荐