-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
feat: 支持企业微信智能机器人 API 模式 #4100
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat: 支持企业微信智能机器人 API 模式 #4100
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
88 changes: 88 additions & 0 deletions
88
...java-cp/src/main/java/me/chanjar/weixin/cp/util/crypto/WxCpIntelligentRobotCryptUtil.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| package me.chanjar.weixin.cp.util.crypto; | ||
|
|
||
| import com.google.gson.JsonObject; | ||
| import me.chanjar.weixin.common.util.crypto.SHA1; | ||
| import me.chanjar.weixin.common.util.crypto.WxCryptUtil; | ||
| import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder; | ||
| import me.chanjar.weixin.common.error.WxRuntimeException; | ||
| import org.apache.commons.codec.binary.Base64; | ||
|
|
||
| import javax.crypto.Cipher; | ||
| import javax.crypto.spec.IvParameterSpec; | ||
| import javax.crypto.spec.SecretKeySpec; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Arrays; | ||
| import java.util.UUID; | ||
|
|
||
| /** | ||
| * 企业微信智能机器人 API 模式消息加解密工具. | ||
| * | ||
| * <p>机器人 API 模式使用机器人后台配置的 Token、EncodingAESKey 和机器人 ID, | ||
| * 与企业应用 access_token 无关。</p> | ||
| */ | ||
| public class WxCpIntelligentRobotCryptUtil extends WxCryptUtil { | ||
|
|
||
| public WxCpIntelligentRobotCryptUtil(String token, String encodingAesKey, String aiBotId) { | ||
| super(token, encodingAesKey, aiBotId); | ||
| } | ||
|
|
||
| /** | ||
| * 解密机器人 API 模式的 JSON 回调消息. | ||
| */ | ||
| public String decrypt(String msgSignature, String timestamp, String nonce, String encryptedContent) { | ||
| String signature = SHA1.gen(this.token, timestamp, nonce, encryptedContent); | ||
| if (!signature.equals(msgSignature)) { | ||
| throw new WxRuntimeException("加密消息签名校验失败"); | ||
| } | ||
|
|
||
| try { | ||
| Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); | ||
| cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(this.aesKey, "AES"), | ||
| new IvParameterSpec(Arrays.copyOfRange(this.aesKey, 0, 16))); | ||
| byte[] bytes = me.chanjar.weixin.common.util.crypto.PKCS7Encoder.decode( | ||
| cipher.doFinal(Base64.decodeBase64(encryptedContent))); | ||
| if (bytes.length < 20) { | ||
| throw new WxRuntimeException("解密后数据长度异常,可能为错误的密文或EncodingAESKey"); | ||
| } | ||
|
|
||
| int plainTextLength = 0; | ||
| for (int index = 16; index < 20; index++) { | ||
| plainTextLength = (plainTextLength << 8) | (bytes[index] & 0xff); | ||
| } | ||
| int plainTextEnd = 20 + plainTextLength; | ||
| if (plainTextLength < 0 || plainTextEnd > bytes.length) { | ||
| throw new WxRuntimeException("解密后数据格式非法:消息长度不正确,可能为错误的密文或EncodingAESKey"); | ||
| } | ||
|
|
||
| String receiverId = new String(Arrays.copyOfRange(bytes, plainTextEnd, bytes.length), StandardCharsets.UTF_8); | ||
| if (!this.appidOrCorpid.equals(receiverId)) { | ||
| throw new WxRuntimeException("智能机器人ID不正确,请核实!"); | ||
| } | ||
| return new String(Arrays.copyOfRange(bytes, 20, plainTextEnd), StandardCharsets.UTF_8); | ||
| } catch (WxRuntimeException e) { | ||
| throw e; | ||
| } catch (Exception e) { | ||
| throw new WxRuntimeException(e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * 加密机器人 API 模式的 JSON 回复消息. | ||
| */ | ||
| public String encrypt(String plainJson, String timestamp, String nonce) { | ||
| String encryptedContent = encrypt(UUID.randomUUID().toString().replace("-", "").substring(0, 16), plainJson); | ||
| JsonObject result = new JsonObject(); | ||
| result.addProperty("encrypt", encryptedContent); | ||
| result.addProperty("msg_signature", SHA1.gen(this.token, timestamp, nonce, encryptedContent)); | ||
| result.addProperty("timestamp", timestamp); | ||
| result.addProperty("nonce", nonce); | ||
| return WxCpGsonBuilder.create().toJson(result); | ||
| } | ||
|
|
||
| /** | ||
| * 解密 URL 校验请求中的 echostr. | ||
| */ | ||
| public String verifyUrl(String msgSignature, String timestamp, String nonce, String echoStr) { | ||
| return decrypt(msgSignature, timestamp, nonce, echoStr); | ||
| } | ||
| } |
19 changes: 19 additions & 0 deletions
19
weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/BaseWxCpServiceImplLogTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package me.chanjar.weixin.cp.api.impl; | ||
|
|
||
| import org.testng.annotations.Test; | ||
|
|
||
| import static org.testng.Assert.assertEquals; | ||
|
|
||
| public class BaseWxCpServiceImplLogTest { | ||
|
|
||
| @Test | ||
| public void redactQueryStringShouldHideTemporaryResponseUrlCredentials() { | ||
| assertEquals(BaseWxCpServiceImpl.redactQueryString("https://example.com/reply?token=temporary-secret&nonce=123"), | ||
| "https://example.com/reply?******"); | ||
| } | ||
|
|
||
| @Test | ||
| public void redactQueryStringShouldKeepUrlWithoutQueryString() { | ||
| assertEquals(BaseWxCpServiceImpl.redactQueryString("https://example.com/reply"), "https://example.com/reply"); | ||
| } | ||
| } |
57 changes: 57 additions & 0 deletions
57
...p/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpIntelligentRobotApiModeServiceTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| package me.chanjar.weixin.cp.api.impl; | ||
|
|
||
| import com.google.gson.JsonObject; | ||
| import me.chanjar.weixin.common.util.json.GsonParser; | ||
| import me.chanjar.weixin.cp.api.WxCpService; | ||
| import me.chanjar.weixin.cp.bean.intelligentrobot.WxCpIntelligentRobotMessage; | ||
| import me.chanjar.weixin.cp.util.crypto.WxCpIntelligentRobotCryptUtil; | ||
| import org.mockito.ArgumentCaptor; | ||
| import org.testng.annotations.Test; | ||
|
|
||
| import static org.mockito.ArgumentMatchers.anyString; | ||
| import static org.mockito.Mockito.mock; | ||
| import static org.mockito.Mockito.verify; | ||
| import static org.mockito.Mockito.when; | ||
| import static org.testng.Assert.assertEquals; | ||
|
|
||
| public class WxCpIntelligentRobotApiModeServiceTest { | ||
|
binarywang marked this conversation as resolved.
|
||
| private static final String TOKEN = "test-token"; | ||
| private static final String AES_KEY = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFA"; | ||
| private static final String AI_BOT_ID = "bot_1"; | ||
| private static final String TIMESTAMP = "1710000000"; | ||
| private static final String NONCE = "test-nonce"; | ||
|
|
||
|
binarywang marked this conversation as resolved.
|
||
| @Test | ||
| public void shouldParseEncryptedCallbackMessage() { | ||
| String callbackJson = "{\"msgid\":\"msg_1\",\"aibotid\":\"bot_1\",\"msgtype\":\"text\"," | ||
| + "\"from\":{\"userid\":\"user_1\"},\"text\":{\"content\":\"hello\"}}"; | ||
| WxCpIntelligentRobotCryptUtil cryptUtil = new WxCpIntelligentRobotCryptUtil(TOKEN, AES_KEY, AI_BOT_ID); | ||
| JsonObject encrypted = GsonParser.parse(cryptUtil.encrypt(callbackJson, TIMESTAMP, NONCE)); | ||
| WxCpIntelligentRobotServiceImpl service = new WxCpIntelligentRobotServiceImpl(mock(WxCpService.class)); | ||
|
|
||
| WxCpIntelligentRobotMessage message = service.parseEncryptedCallbackMessage( | ||
| encrypted.get("msg_signature").getAsString(), TIMESTAMP, NONCE, encrypted.get("encrypt").getAsString(), | ||
| TOKEN, AES_KEY, AI_BOT_ID); | ||
|
|
||
| assertEquals(message.getMsgId(), "msg_1"); | ||
| assertEquals(message.getText().getContent(), "hello"); | ||
| } | ||
|
|
||
| @Test | ||
| public void shouldReplyThroughResponseUrlWithoutAccessToken() throws Exception { | ||
| WxCpService cpService = mock(WxCpService.class); | ||
| when(cpService.postWithoutToken(anyString(), anyString())).thenReturn("ok"); | ||
| WxCpIntelligentRobotServiceImpl service = new WxCpIntelligentRobotServiceImpl(cpService); | ||
| String responseUrl = "https://example.com/response"; | ||
| String plainJson = "{\"msgtype\":\"text\"}"; | ||
|
|
||
| assertEquals(service.replyMessage(responseUrl, plainJson, TOKEN, AES_KEY, AI_BOT_ID, TIMESTAMP, NONCE), "ok"); | ||
|
|
||
| ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class); | ||
| verify(cpService).postWithoutToken(org.mockito.ArgumentMatchers.eq(responseUrl), bodyCaptor.capture()); | ||
| JsonObject encrypted = GsonParser.parse(bodyCaptor.getValue()); | ||
| WxCpIntelligentRobotCryptUtil cryptUtil = new WxCpIntelligentRobotCryptUtil(TOKEN, AES_KEY, AI_BOT_ID); | ||
| assertEquals(cryptUtil.decrypt(encrypted.get("msg_signature").getAsString(), TIMESTAMP, NONCE, | ||
| encrypted.get("encrypt").getAsString()), plainJson); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.