美文网首页唯爱微服务架构与应用SpringHome
spring-boot 微信授权及获取用户信息

spring-boot 微信授权及获取用户信息

作者: aef5bc56a01e | 来源:发表于2017-09-28 17:06 被阅读92次

    之前做了好几个项目,都需要用到微信授权,闲来没事就把微信授权登陆功能进行了简单封装,项目地址spring-boot-wechat-starter

    • wechat-starter 主要功能模块
    • demo 测试模块

    wechat-starter模块

    jar依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-autoconfigure</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
    </dependency>
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
    </dependency>
    

    主要功能类

    1. 配置类
    @ConfigurationProperties(prefix = "spring.social.wx")
    public class WxProperties extends SocialProperties {
    
        private String appName;
    
        private int deviceType;
    
        public String getAppName() {
            return appName;
        }
    
        public void setAppName(String appName) {
            this.appName = appName;
        }
    
        public int getDeviceType() {
            return deviceType;
        }
    
        public void setDeviceType(int deviceType) {
            this.deviceType = deviceType;
        }
    }
    

    2.逻辑类

    package com.lyf.springboot.wx;
    
    import com.lyf.springboot.wx.auto.WxProperties;
    import com.lyf.springboot.wx.req.WeChatAuthResponse;
    import com.lyf.springboot.wx.req.WeChatUserInfo;
    import com.lyf.springboot.wx.utils.HttpClientUtil;
    import com.lyf.springboot.wx.utils.JsonHelper;
    import com.lyf.springboot.wx.utils.WxHelper;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    
    /**
     * Created by 永锋 on 2017/9/28.
     */
    public class WxAuthService {
        private static Logger logger = LoggerFactory.getLogger(WxAuthService.class);
        @Autowired
        private WxProperties wxProperties;
    
        public WxAuthService() {
        }
    
        /**
         * 进行微信授权,获取用户信息 存入进本库 和 关系库
         * @param code
         * @return
         */
        public WeChatUserInfo auth(String code){
            if(StringUtils.isEmpty(code) || "null".equalsIg(code)){
                logger.warn("error code: {}", code);
                return null;
            }
    
            String accessUrl = WxHelper.getWXAccessUrl(code, wxProperties.getAppId(),
                            wxProperties.getAppSecret());
            logger.info("accessUrl:{}", accessUrl);
            String result = HttpClientUtil.getHttpsContent(accessUrl);
            WeChatAuthResponse response = JsonHelper.fromJsonString(result, WeChatAuthResponse.class);
    
            if(response == null || response.getErrcode() != 0 || StringUtils.isBlank(response.getOpenid())){
                return null;
            }
            WeChatUserInfo userInfo = WxHelper.requestUserInfo(response.getAccess_token(), response.getOpenid());
            if(userInfo == null || StringUtils.isBlank(userInfo.getUnionid())){
                return null;
            }
            return userInfo;
        }
    }
    
    1. 自动注入类
    package com.lyf.springboot.wx.auto;
    
    import com.lyf.springboot.wx.WxAuthService;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * Created by 永锋 on 2017/9/28.
     */
    @Configuration
    @EnableConfigurationProperties(WxProperties.class)
    public class WxAutoConfiguration {
        @Bean(name = "wxAuthService")
        public WxAuthService wxAuthService(){
            return new WxAuthService();
        }
    }
    

    4.配置自动注入类,在resources/META-INF/目录下创建spring.factories文件

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
      com.lyf.springboot.wx.auto.WxAutoConfiguration
    
    1. 对WxProperties类的属性进行配置,在resources/META-INF/目录下创建spring-configuration-metadata.json文件
    {
      "properties": [
        {
          "name": "spring.social.wx.app-id",
          "type": "java.lang.String",
          "sourceType": "com.lyf.springboot.wx.auto.WxProperties"
        },
        {
          "name": "spring.social.wx.app-secret",
          "type": "java.lang.String",
          "sourceType": "com.lyf.springboot.wx.auto.WxProperties"
        },
        {
          "name": "spring.social.wx.app-name",
          "type": "java.lang.String",
          "sourceType": "com.lyf.springboot.wx.auto.WxProperties"
        },
        {
          "name": "spring.social.wx.device-type",
          "type": "java.lang.String",
          "description": "wx platform type, 1 for app, 2 for web",
          "defaultValue": 1,
          "sourceType": "com.lyf.springboot.wx.auto.WxProperties"
        }
      ],
      "hints": []
    }
    

    wechat-starter的使用

    1. maven中引入wechat-starter
    <dependency>
        <groupId>com.lyf.springboot.wechat</groupId>
        <artifactId>wechat-starter</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    
    1. 在application.yml中配置自己的微信App信息
    spring:
      social:
        wx:
          app-id: # 配置自己申请的appId
          app-secret: #配置为自己申请的appSecret
          app-name: #此处是为了区分多个app进行的配置 可选
          device-type: 2
    
    1. 在自己的controller里面调用wechat-starter的逻辑类,实现授权登陆(获取用户信息)

    相关文章

      网友评论

      • 维尼_7cec:请问下这个 微信授权及获取用户信息后台 ,适用于微信公众号,还是APP授权登录
        维尼_7cec:@蒼白_4ade /**
        * 使用即答服务号授权
        * @Return
        * @Throws UnsupportedEncodingException
        */
        private String buildRedirectUrl() throws UnsupportedEncodingException {
        //TODO 此处应根据实际的域名修改
        String redirectUrl = "http://localhost/"; + request.getServerName() + "/wx/auth";
        String redirect_url = String.format(WxHelper.WX_LOGIN_URL, wxProperties.getAppId(),
        URLEncoder.encode(redirectUrl, "UTF8"));
        logger.info("url: {}", redirect_url);
        return redirect_url;
        }

        这里的localhost/是公网域名吗
        维尼_7cec:@蒼白_4ade 是APP端将code传给后台,后台通过 auth方法这样吧?
        aef5bc56a01e:我demo里面写的是适用于公众号的。starter的service也适用于APP,APP端点击授权后,获得的code,调用后台WxAuthService的auth方法即可获得详细的微信用户信息

      本文标题:spring-boot 微信授权及获取用户信息

      本文链接:https://www.haomeiwen.com/subject/vklvextx.html