1 Star 0 Fork 0

张龙飞 / spring-boot-starter-social

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README

企业微信对接配置

一、基本使用方式

写在前边

img_1.png

读者需要先了解第三方的API文档,比如要获取企业微信的《获取第三方应用凭证API》接口,在spring-boot-starter-social包中搜getSuiteToken就可以找到对应的请求ThirdpartGetSuiteTokenRequest类和返回ThirdpartGetSuiteTokenResponse类, 进而通过ThirdpartQwService接口触发invoke方法进行调用API。

使用方法

1、先引入pom依赖

<dependency>
    <groupId>cn.basic.social</groupId>
    <artifactId>spring-boot-starter-social</artifactId>
    <version>0.0.2-SNAPSHOT</version>
</dependency>

2、配置yaml文件企业微信相关信息

# 企业微信对接配置
social:
  config:
    #只有为true的时候才会交给bean管理,使用SocialRequestFactory注入后即可使用,该服务会缓存accessToken等信息,用户只需要关心自己要调用的接口即可。
    #如果为false,用户只能使用cn/basic/social/api包下的请求,该服务不会缓存accessToken等信息。
    enabled: true
    type:
      QiWei_ThirdPart:  #SocialConfigProperties.TypeEnum取值,必须是这个枚举的值才能识别到
        corpID: aaaaaaa  #服务商的corpID
        providerSecret: bbbbb  #服务商的providerSecret
        m_corpID: cccccc  #客户微信的corpID,客户企业微信授权
        login:
          suiteId: ddddd   #登录授权应用的suiteId
          suiteSecret: eeeeeee  #登录授权应用的suiteSecret
          token: fffffffffffff  #登录授权应用的Token
          encodingAESKey: ggggggggggggg #登录授权应用的EncodingAESKey
        application:
          xiaochengxumingcheng:
            suiteId: hhhhhhhhhhh   #应用的suiteId
            suiteSecret: iiiiiiiiii  #应用的suiteSecret
            token: jjjjjjjjjjjjjjj  #应用的Token
            encodingAESKey: kkkkkkkkkkkkkkkkkk #应用的EncodingAESKey
      WeiXin:
        appid: llllllllllllllllll #微信登录应用唯一标识,在微信开放平台提交应用审核通过后获得
        secret: mmmmmmmmmmmmmmmmmmmmmmmmm  #微信登录应用密钥AppSecret,在微信开放平台提交应用审核通过后获得

3、使用demo


@SpringBootTest
@RunWith(SpringRunner.class)
public class DemoQwSocialTest {

    // yaml文件中设置了enabled=true,直接从spring容器中获取到SocialRequestFactory
    @Autowired
    private SocialRequestFactory factory;

    /**
     * 群发任务消息示例
     */
    @Test
    public void sendMessage() {
        try {
            ThirdpartAddMsgTemplateResponse baseResponse = factory.doExecute(SocialConfigProperties.TypeEnum.QiWei_ThirdPart, "xiaochengxumingcheng",
                    (providerConfig, redisCache) -> {
                        // 1. 要群发任务消息,初始化一个ThirdpartQwService接口的实现类ThirdpartAddMsgTemplateServiceImpl,暂时没有交给spring管理,用户需要自己new
                        ThirdpartQwService thirdpartQwService = new ThirdpartAddMsgTemplateServiceImpl();

                        // 2、封装发送的参数类ThirdpartAddMsgTemplateRequest,群发任务需要的参数信息等都set进去
                        ThirdpartAddMsgTemplateRequest request = new ThirdpartAddMsgTemplateRequest();

                        // 3、调用ThirdpartQwService接口的invoke方法,触发spring-boot-starter-social服务的请求调用企微API,并返回相应的返回值
                        return thirdpartQwService.invoke(request, providerConfig, redisCache);
                    });
            System.out.println("返回值:" + JSON.toJSONString(baseResponse, SerializerFeature.PrettyFormat));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 上传素材文件示例
     */
    @Test
    public void uploadMedia() {
        try {
            ThirdpartMediaUploadResponse baseResponse = factory.doExecute(SocialConfigProperties.TypeEnum.QiWei_ThirdPart, "xiaochengxumingcheng",
                    (providerConfig, redisCache) -> {
                        // 1. 要上传素材文件,初始化一个ThirdpartQwService接口的实现类ThirdpartMediaUploadServiceImpl,暂时没有交给spring管理,用户需要自己new
                        ThirdpartQwService thirdpartQwService = new ThirdpartMediaUploadServiceImpl();

                        // 2、封装发送的参数类ThirdpartMediaUploadRequestt,群发任务需要的参数信息等都set进去
                        ThirdpartMediaUploadRequest request = new ThirdpartMediaUploadRequest(new File("C:\\Users\\zhang\\Desktop\\aa.png"), "image");

                        // 3、调用ThirdpartQwService接口的invoke方法,触发spring-boot-starter-social服务的请求调用企微API,并返回相应的返回值
                        return thirdpartQwService.invoke(request, providerConfig, redisCache);
                    });
            System.out.println("返回值:" + JSON.toJSONString(baseResponse, SerializerFeature.PrettyFormat));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 第三方登录获取用户信息
     */
    @Test
    public void login() throws Exception {
        LoginResponse loginResponse = SocialRequestFactory.doLoginExecute("QiWei_ThirdPart",
                new LoginRequest("mmndsabnsbaamsabbmjbf", "login_state"));
        System.out.println("返回值:" + JSON.toJSONString(loginResponse, SerializerFeature.PrettyFormat));
    }
}

二、结构说明

img.png

  1. api包下都是每个单独的请求,不归spring容器管理,如果单纯用这个报下的class,则不需要yaml文件配置,业务端直接调用即可;
  2. manager包是封装了对spring自动扫描的支持,默认使用spring.redis的的配置,需要业务端配置yaml文件,如上3步骤。

三、第三方应用登录

例如:企业微信授权登录流程

img_2.png

具体操作

1、先获取state,用于回调请求登录接口时的校验;

@Slf4j
@RestController
@RequestMapping("/social")
public class SocialCallbackController {

    @Autowired
    private SocialRequestFactory socialRequestFactory;

    /**
     * 用于二维码登录时传递值,登录的时候透传校验
     * 缓存到内存中,登录socialFilter的时候再校验这个值
     */
    @GetMapping(value = "state")
    public JsonResult<String> state() throws Exception {
        String loginState = socialRequestFactory.getLoginState();
        return JsonResult.success(loginState);
    }
}

2、前端构建二维码,填充appid、回调地址redirect_uri、state等参数;

例如:
https://login.work.weixin.qq.com/wwlogin/sso/login?appid=APPID&redirect_uri=REDIRECT_URI&state=STATE

3、用户扫码后前端回调地址会拼接state和授权码code,前端请求后台登录接口获取token;(集成了Spring Security OAuth2组件,使用filter过滤器校验)

@Slf4j
@Setter
public class SocialLoginFilter extends AbstractAuthenticationProcessingFilter {

    private static final String CODE_PARAMETER = "code";
    private static final String STATE_PARAMETER = "state";

    private SocialRequestFactory socialRequestFactory;

    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/social/**/login", "GET");

    private static Pattern pattern = Pattern.compile("/social/([^/]+)/login");

    public SocialLoginFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (!request.getMethod().equals(HttpMethod.GET.name())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        } else {
            //校验code
            String code = this.obtainCode(CODE_PARAMETER, request);
            String state = this.obtainCode(STATE_PARAMETER, request);
            String type = this.obtainType(request);
            // 获取用户信息
            LoginResponse loginResponse = null;
            try {
                // 获取第三方扫码用户的基本信息
                loginResponse = socialRequestFactory.doLoginExecute(type, new LoginRequest(code, state));
            } catch (Exception e) {
                log.error("请求用户信息失败,case:" + e, e);
                throw new BusinessException("请求用户信息失败");
            }
            if (ObjectUtils.isEmpty(loginResponse)) {
                throw new BusinessException("请求用户信息失败");
            }
            log.info("第三方获取用户信息:{}", ObjectUtils.isNotEmpty(loginResponse) ? JSON.toJSONString(loginResponse) : null);
            SocialAuthenticationToken authRequestToken = new SocialAuthenticationToken(loginResponse, type);
            return this.getAuthenticationManager().authenticate(authRequestToken);
        }
    }

    private String obtainType(HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        Matcher matcher = pattern.matcher(requestURI);
        // 如果找到匹配项,提取捕获组中的字符串
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }

    private String obtainCode(String param, HttpServletRequest request) {
        String code = request.getParameter(param);
        return Optional.of(code).orElseThrow(() -> new AuthenticationServiceException(param + " is empty"));
    }
}

空文件

简介

第三方社交应用SDK 展开 收起
Java
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/zlfmm/spring-boot-starter-social.git
git@gitee.com:zlfmm/spring-boot-starter-social.git
zlfmm
spring-boot-starter-social
spring-boot-starter-social
master

搜索帮助