文档地址:构造网页授权链接 - 接口文档 - 企业微信开发者中心

注意:

        1.redirect_uri:回调链接地址,需要使用urlencode对链接进行处理

        2.scope:如果需要获取成员的头像、手机号等信息需要设为snsapi_privateinfo

例如前端地址为:https://test.com

构造成的链接为:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=https%3A%2F%2Ftest.com&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=AGENTID#wechat_redirect

已管理员身份登录企业微信后台-应用管理-创建应用:

 

设置可信域名以及可信IP:

 

 添加之后可以在企业微信-工作台中找到相关的应用,点击后会跳转到https://test.com?code=CODE,可以通过code请求后端获取到用户的相关信息

接口文档:获取访问用户身份 - 接口文档 - 企业微信开发者中心

以下为JAVA使用 weixin-java-cp的实现代码

<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-cp</artifactId>
    <version>4.0.0</version>
</dependency>
QYWeixinProperties qyWeixinProperties = SpringUtil.getBean(QYWeixinProperties.class);

// 企业微信相关配置
WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
config.setCorpId(qyWeixinProperties.getCorpId());
config.setCorpSecret(qyWeixinProperties.getCorpSecret());
config.setAgentId(qyWeixinProperties.getAgentId());

WxCpServiceImpl wxCpService = new WxCpServiceImpl();
wxCpService.setWxCpConfigStorage(config);

String mobile;

try {
    WxCpOauth2UserInfo userInfo = wxCpService.getOauth2Service().getUserInfo(code);

	if (Func.notNull(userInfo)) {
		String userId = userInfo.getUserId();
		// 用户userId
		if (Func.isBlank(userId)) {
			return;
		}
		// 根据userId查询微信中用户详情,注意需要构造链接中scope=snsapi_privateinfo且用户授权才能获取到
		WxCpUserDetail userDetail = wxCpService.getOauth2Service().getUserDetail(userInfo.getUserTicket());

		mobile = userDetail.getMobile();
		if (Func.isBlank(mobile)) {
		    return;
		}

    // 接下来是通过手机号获取用户信息的逻辑,按照自己系统的逻辑来写

	} else {
		return;
    }
} catch (WxErrorException e) {
    return;
}

 

更多推荐