1
+ package ai .chat2db .server .domain .core .notification ;
2
+
3
+ import ai .chat2db .server .domain .api .param .message .MessageCreateParam ;
4
+ import okhttp3 .*;
5
+
6
+ import javax .crypto .Mac ;
7
+ import javax .crypto .spec .SecretKeySpec ;
8
+ import java .io .IOException ;
9
+ import java .nio .charset .StandardCharsets ;
10
+ import java .security .InvalidKeyException ;
11
+ import java .security .NoSuchAlgorithmException ;
12
+
13
+ import org .apache .commons .codec .binary .Base64 ;
14
+ import org .springframework .stereotype .Service ;
15
+
16
+ /**
17
+ * @author Juechen
18
+ * @version : LarkWebhookSender.java
19
+ */
20
+ @ Service
21
+ public class LarkWebhookSender extends BaseWebhookSender {
22
+
23
+ private static final String HMAC_SHA256_ALGORITHM = "HmacSHA256" ;
24
+
25
+ @ Override
26
+ public void sendMessage (MessageCreateParam param ) {
27
+ try {
28
+ OkHttpClient client = new OkHttpClient ();
29
+ String webhookUrl = param .getServiceUrl ();
30
+ String secret = param .getSecretKey ();
31
+ int timestamp = (int ) (System .currentTimeMillis () / 1000 );
32
+
33
+ String signature = GenSign (secret , timestamp );
34
+
35
+ String payload = "{\" timestamp\" : \" " + timestamp
36
+ + "\" ,\" sign\" : \" " + signature
37
+ + "\" ,\" msg_type\" :\" text\" ,\" content\" :{\" text\" :\" " + param .getTextTemplate () +"\" }}" ;
38
+ RequestBody body = RequestBody .create (payload , MediaType .parse ("application/json; charset=utf-8" ));
39
+
40
+
41
+ Request request = new Request .Builder ()
42
+ .url (webhookUrl )
43
+ .post (body )
44
+ .addHeader ("Content-Type" , "application/json" )
45
+ .build ();
46
+
47
+ Response response = client .newCall (request ).execute ();
48
+ if (!response .isSuccessful ()) {
49
+ throw new RuntimeException ("Failed to send message: " + response .code ());
50
+ }
51
+ System .out .println (response .body ().string ());
52
+ } catch (NoSuchAlgorithmException e ) {
53
+ throw new RuntimeException (e );
54
+ } catch (InvalidKeyException e ) {
55
+ throw new RuntimeException (e );
56
+ } catch (IOException e ) {
57
+ throw new RuntimeException (e );
58
+ }
59
+
60
+ }
61
+
62
+ private static String GenSign (String secret , int timestamp ) throws NoSuchAlgorithmException , InvalidKeyException {
63
+ String stringToSign = timestamp + "\n " + secret ;
64
+ Mac mac = Mac .getInstance (HMAC_SHA256_ALGORITHM );
65
+ mac .init (new SecretKeySpec (stringToSign .getBytes (StandardCharsets .UTF_8 ), HMAC_SHA256_ALGORITHM ));
66
+ byte [] signData = mac .doFinal (new byte []{});
67
+ return new String (Base64 .encodeBase64 (signData ));
68
+ }
69
+ }
0 commit comments