weixin-java-cp-demo:基于Spring Boot和WxJava实现的微信企业号集群环境配置

pom依赖

<dependencies>
		<!--微信服务号第三方SDK-->
		<dependency>
			<groupId>com.github.binarywang</groupId>
			<artifactId>weixin-java-cp</artifactId>
			<version>${weixin-java}</version>
		</dependency>
	</dependencies>

Redis初始类

@Component
public class RedissonClientInitializer {

    @Value("${wecom.redis.database}")
    private int database;

    @Value("${wecom.redis.host}")
    private String host;

    @Value("${wecom.redis.port}")
    private String port;

    @Value("${wecom.redis.password}")
    private String password;

    public RedissonClient initialize() {

        Config config = new Config();
        config.useSingleServer().setAddress(String.format("redis://%s:%s", this.host, this.port));
        if (!this.password.isEmpty()) {
            config.useSingleServer().setPassword(this.password);
        }
        config.useSingleServer().setDatabase(this.database);

        StringCodec codec = new StringCodec();
        config.setCodec(codec);
        return Redisson.create(config);
    }

}

企业微信配置类

@Configuration
@RequiredArgsConstructor
@Slf4j
public class WxCpConfiguration {


    private final AccountMapper accountMapper;
	private final TenantMapper tenantMapper;
	private final RedissonClientInitializer initializer;

	private static Map<String, WxCpService> cpServices = new ConcurrentHashMap<>();

    public WxCpService getCpService(String corpId, Integer agentId) {
		WxCpService cpService = cpServices.get(corpId + agentId);
		if (!Optional.ofNullable(cpService).isPresent()) {
			//若缓存中未找到,去数据库再查一次
			Account account = accountMapper.selectOne(Wrappers.<Account>lambdaQuery().eq(Account::getUniqueId, corpId + agentId));
			//若查询结果不为空,更新缓存
			if (!ObjectUtils.isEmpty(account)) {
				WxCpDefaultConfigImpl config = JSONObject.parseObject(account.getAccountConfig(), WxCpDefaultConfigImpl.class);
				log.info("config:{}",config);
				WxCpRedissonConfigImpl redissonConfig = new WxCpRedissonConfigImpl(initializer.initialize(), "workRedis:");
				redissonConfig.setCorpId(config.getCorpId());
				redissonConfig.setAgentId(config.getAgentId());
				redissonConfig.setCorpSecret(config.getCorpSecret());
				WxCpServiceImpl wxCpService = new WxCpServiceImpl();
				wxCpService.setWxCpConfigStorage(redissonConfig);
				setCpService(corpId, agentId, wxCpService);
				log.info("缓存已更新:corpId:{},agentId:{}",corpId,agentId);
				return wxCpService;
			}
		}
		return Optional.ofNullable(cpService).orElseThrow(() -> {
			log.error("未找到 corpId: {}, agentId: {} 对应的 WxCpService", corpId, agentId);
			return new CommonException("未配置此service");
		});
	}

	public static void setCpService(String corpId, Integer agentId,WxCpServiceImpl service) {
		cpServices.put(corpId + agentId, service);
	}

    @PostConstruct
    public void initServices() {
		try {
			List<Tenant> tenants = tenantMapper.selectList(Wrappers.emptyWrapper());
			for (Tenant tenant : tenants) {
				String dsKey = SecurityConstants.PROJECT_PREFIX + tenant.getTenantId();
				DynamicDataSourceContextHolder.push(dsKey);
				List<Account> accounts = accountMapper.selectList(new LambdaQueryWrapper<Account>().eq(Account::getSendChannel, 1));
				// 提取 accountConfig 字段,并将其映射为 List<WxCpDefaultConfigImpl>
				List<WxCpDefaultConfigImpl> list = accounts.stream()
						.map(account -> JSON.parseObject(account.getAccountConfig(), WxCpDefaultConfigImpl.class))
						.collect(Collectors.toList());
				cpServices = list.stream().map(this::apply).filter(Optional::isPresent).map(Optional::get)
						.collect(Collectors.toMap(service -> service.getWxCpConfigStorage().getCorpId() + service.getWxCpConfigStorage().getAgentId(), a -> a));
			}
		} catch (Exception e) {
			log.error("企业微信初始化失败",e);
		} finally {
			DynamicDataSourceContextHolder.clear();
		}
	}


	private Optional<WxCpServiceImpl> apply(WxCpDefaultConfigImpl a) {
		if (ObjectUtils.isEmpty(a)) {
			Optional.ofNullable(new WxCpServiceImpl());
		}
		WxCpRedissonConfigImpl config = new WxCpRedissonConfigImpl(initializer.initialize(), "workRedis:");
		config.setCorpId(a.getCorpId());
		config.setAgentId(a.getAgentId());
		config.setCorpSecret(a.getCorpSecret());
		config.setToken(a.getToken());
		config.setAesKey(a.getAesKey());

		val service = new WxCpServiceImpl();
		service.setWxCpConfigStorage(config);
		log.info("初始化企业微信服务:corpId:{},agentId:{}",a.getCorpId(),a.getAgentId());
		return Optional.of(service);
	}
}

企业微信保存

@PostMapping("/wecom/save")
    @ApiOperation("企业微信保存数据")
    public R saveWecom(@RequestBody WxCpAccountDTO channelAccount) {
        AccountService accountService = accountServiceFactory.getAccountService(ENTERPRISE_WE_CHAT_SERVICE_NAME+ACCOUNT);
        accountService.save(channelAccount);
        return R.ok();
    }

@Override
	@Transactional
	public void save(WxCpAccountDTO accountDTO) {
		//校验账号是否存在
		Account existAccount = getExistAccount(accountDTO.getConfig());
		if (existAccount != null) {
			throw new CommonException("07020004", existAccount.getName(), userInfoMapper.selectByUsername(existAccount.getCreateBy()).getTrueName());
		}// 处理企业微信渠道的逻辑
		WxCpDefaultConfigImpl config = BeanCopyUtils.turnToVO(accountDTO.getConfig(), WxCpDefaultConfigImpl.class);
		WxCpServiceImpl wxCpService = new WxCpServiceImpl();
		wxCpService.setWxCpConfigStorage(config);
		String name;
		try {
			WxCpAgent wxCpAgent = wxCpService.getAgentService().get(config.getAgentId());
			name = wxCpAgent.getName();
			String cover = wxCpAgent.getSquareLogoUrl();

			accountDTO.setName(name);
			accountDTO.setCover(cover);
			accountDTO.setAccountConfig(JSONObject.toJSONString(accountDTO.getConfig()));
			accountDTO.setUniqueId(config.getCorpId() + config.getAgentId());
			//更新缓存
			WxCpRedissonConfigImpl redissonConfig = new WxCpRedissonConfigImpl(initializer.initialize(), "workRedis:");
			redissonConfig.setCorpId(config.getCorpId());
			redissonConfig.setAgentId(config.getAgentId());
			redissonConfig.setCorpSecret(config.getCorpSecret());
			wxCpService.setWxCpConfigStorage(redissonConfig);
			WxCpConfiguration.setCpService(config.getCorpId(), config.getAgentId(), wxCpService);
		} catch (WxErrorException e) {
			log.error("企业微信用户信息绑定失败:", e);
			throw new CommonException("07020002", WxCpErrorMsgEnum.findMsgByCode(e.getError().getErrorCode()));
		}

		// 其他保存逻辑
		accountDomainService.save(accountDTO);
	}

账号表

@Data
@TableName("new_media_account")
@Accessors(chain = true)
public class Account extends BaseDomain {

    /**
     * 账号名称
     */
    private String name;

	/**
	 * 唯一id
	 */
	private String uniqueId;

	/**
	 * 头像
	 */
	private String cover;

    /**
     * 发送渠道
     */
    private Integer sendChannel;

    /**
     * 账号配置
     */
    private String accountConfig;

	/**
	 * 账号状态 0-登录失效 1-登录成功
	 */
	private Integer status;
}

基类

@Getter
@Setter
@Accessors(chain = true)
public class BaseDomain extends BaseEntity{
	/**
	 * 自增主键
	 */
	private Integer autoPk;

	/**
	 * 业务主键
	 */
	@TableId(type = IdType.ASSIGN_ID)
	private Long id;

	/**
	 * 租户id
	 */
	@TableField(fill = FieldFill.INSERT)
	private Integer tenantId;

	@TableField(exist=false)
	private Integer tenantIdManual;

	@TableField(exist=false)
	private Long groupByCount;

	/**
	 * 逻辑删除的标记位(0:否,1:是)
	 * 赋予默认值是为了批量新增的时候不报非空字段的错误
	 */
	@TableLogic
	private Integer isDelete=0;

	public Long generateId(){
		IdentifierGenerator identifierGenerator = SpringContextHolder.getBean(IdentifierGenerator.class);
		Number number = identifierGenerator.nextId(this);
		this.setId(number.longValue());
		return getId();
	}
}

@Getter
@Setter
@Accessors(chain = true)
public class BaseEntity implements Serializable {

	/**
	 * 创建者
	 */
	@TableField(fill = FieldFill.INSERT)
	private String createBy;

	/**
	 * 创建时间
	 */
	@TableField(fill = FieldFill.INSERT)
	private LocalDateTime createTime;

	/**
	 * 更新者
	 */
	@TableField(fill = FieldFill.INSERT_UPDATE)
	private String updateBy;

	/**
	 * 更新时间
	 */
	@TableField(fill = FieldFill.INSERT_UPDATE)
	private LocalDateTime updateTime;

}
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
weixin-java-cp是一个用于企业微信开发的Java SDK。根据引用[1],weixin-java-cp有以下几个文件提供: 1. weixin-java-cp-2.8.0.jar:这是SDK的jar包。 2. weixin-java-cp-2.8.0-javadoc.jar:这是SDK的API文档的jar包。 3. weixin-java-cp-2.8.0-sources.jar:这是SDK的源代码的jar包。 4. weixin-java-cp-2.8.0.pom:这是SDK的Maven依赖信息文件。 根据引用和引用,weixin-java-cp还有一个基于Spring BootWxJava实现微信企业企业微信放置演示项目称为weixin-java-cp-demo。这个项目是一个企业微信替代开发功能的演示程序。该项目使用了Spring Boot框架,并且使用了weixin-java-cp这个SDK。 在使用weixin-java-cp时,首先需要配置项目。根据引用中的描述,你需要复制/src/main/resources/application.yml.template文件并将其扩展名修改为application.yml。然后根据自己的需要填充相关配置信息。配置文件中包含了一些主要配置说明,需要根据实际情况进行填写。其中,如果要配置通讯录agentId的应用,可以随便配置一个agentId,只要保证和服务器URL地址中的一致即可。 总之,weixin-java-cp是一个用于企业微信开发的Java SDK,它提供了jar包、API文档、源代码和Maven依赖信息文件。同时,还有一个基于Spring BootWxJava实现微信企业企业微信放置演示项目weixin-java-cp-demo。在使用weixin-java-cp时,需要配置相关信息,可以参考引用中的说明。 : 赠送jar包:weixin-java-cp-2.8.0.jar; 赠送原API文档:weixin-java-cp-2.8.0-javadoc.jar; 赠送源代码:weixin-java-cp-2.8.0-sources.jar; 赠送Maven依赖信息文件:weixin-java-cp-2.8.0.pom; : @[TOC](<font color=#a5c>) 🐱‍🏍 weixin-java-cp-demo:基于Spring BootWxJava实现微信企业企业微信放置演示 。 : ✨企业微信WxJavaDemo演示程序介绍 本项目为,基于Spring Boot实现企业微信替代开发功能。 更多信息请查阅: : 使用步骤: 请注意,本演示为简化代码编译时加入了lombok支持,如果不了解lombok的话,请先学习下相关知识,可以比如阅读; 另外,新手遇到问题,请首先阅读主页的常见问题部分,可以少走很多弯路,节省大量时间。 配置:复制/src/main/resources/application.yml.template修改其扩展名生成application.yml文件,根据自己需要填充相关配置(需要注意的是:yml文件内部的属性冒后面的文字之前需要加空格,可参考已有配置,否则属性会设置不成功); 主要配置说明如下:(注意:如果是要配置通讯录agentId的应用, agentId可以随便配置一个,保证跟下面服务器URL地址里的一致即可。) wechat: cp: corpId: 111 (企业ID 在此页面查看:https://work.weixin.qq.com/wework_admin/frame#profile) appConfigs: ✨ 。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

里丶夜行人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值