代码拉取完成,页面将自动刷新
读者需要先了解第三方的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));
}
}
例如:企业微信授权登录流程
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"));
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。