wechat-mp-sdk 0.3.0

WeChat Mini Program SDK for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! OpenAPI Management API
//!
//! Endpoints for managing API quotas, rate limits, and diagnostic information.
//!
//! # Endpoints
//!
//! - [`OpenApiApi::clear_quota`] - Reset all API call quotas
//! - [`OpenApiApi::get_api_quota`] - Query API call quota for a specific endpoint
//! - [`OpenApiApi::clear_api_quota`] - Reset quota for a specific endpoint
//! - [`OpenApiApi::clear_quota_by_app_secret`] - Reset quota using AppSecret (no token)
//! - [`OpenApiApi::get_rid_info`] - Get request debug information by rid
//! - [`OpenApiApi::callback_check`] - Check callback URL connectivity
//! - [`OpenApiApi::get_api_domain_ip`] - Get WeChat API server IP addresses
//! - [`OpenApiApi::get_callback_ip`] - Get WeChat callback server IP addresses

use std::fmt;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use super::{WechatApi, WechatContext};
use crate::error::WechatError;

// ============================================================================
// Request Types (internal)
// ============================================================================

#[derive(Debug, Clone, Serialize)]
struct ClearQuotaRequest {
    appid: String,
}

#[derive(Debug, Clone, Serialize)]
struct GetApiQuotaRequest {
    cgi_path: String,
}

#[derive(Debug, Clone, Serialize)]
struct ClearApiQuotaRequest {
    cgi_path: String,
}

#[derive(Clone, Serialize)]
struct ClearQuotaByAppSecretRequest {
    appid: String,
    appsecret: String,
}

impl fmt::Debug for ClearQuotaByAppSecretRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClearQuotaByAppSecretRequest")
            .field("appid", &self.appid)
            .field("appsecret", &"[REDACTED]")
            .finish()
    }
}

#[derive(Debug, Clone, Serialize)]
struct GetRidInfoRequest {
    rid: String,
}

#[derive(Debug, Clone, Serialize)]
struct CallbackCheckRequest {
    action: String,
    check_operator: String,
}

// ============================================================================
// Internal Response Types
// ============================================================================

/// Internal response for endpoints that only return errcode/errmsg
#[derive(Debug, Clone, Deserialize)]
struct BaseApiResponse {
    #[serde(default)]
    errcode: i32,
    #[serde(default)]
    errmsg: String,
}

// ============================================================================
// Public Response Types
// ============================================================================

/// API quota details
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct QuotaInfo {
    /// Daily API call limit
    #[serde(default)]
    pub daily_limit: i64,
    /// Number of calls used today
    #[serde(default)]
    pub used: i64,
    /// Remaining calls today
    #[serde(default)]
    pub remain: i64,
}

/// Response from getApiQuota
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ApiQuotaResponse {
    /// Quota details
    #[serde(default)]
    pub quota: QuotaInfo,
    /// Error code (0 means success)
    #[serde(default)]
    pub(crate) errcode: i32,
    /// Error message
    #[serde(default)]
    pub(crate) errmsg: String,
}

/// Request debug information
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct RidRequestInfo {
    /// Request invocation timestamp (Unix epoch seconds)
    #[serde(default)]
    pub invoke_time: i64,
    /// Request cost in milliseconds
    #[serde(default)]
    pub cost_in_ms: i64,
    /// Request URL
    #[serde(default)]
    pub request_url: String,
    /// Request body
    #[serde(default)]
    pub request_body: String,
    /// Response body
    #[serde(default)]
    pub response_body: String,
    /// Client IP address
    #[serde(default)]
    pub client_ip: String,
}

/// Response from getRidInfo
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RidInfoResponse {
    /// Request debug information
    #[serde(default)]
    pub request: RidRequestInfo,
    /// Error code (0 means success)
    #[serde(default)]
    pub(crate) errcode: i32,
    /// Error message
    #[serde(default)]
    pub(crate) errmsg: String,
}

/// DNS check result entry
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct DnsInfo {
    /// IP address
    #[serde(default)]
    pub ip: String,
    /// Real network operator
    #[serde(default)]
    pub real_operator: String,
}

/// Ping check result entry
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct PingInfo {
    /// IP address
    #[serde(default)]
    pub ip: String,
    /// Source operator
    #[serde(default)]
    pub from_operator: String,
    /// Packet loss rate
    #[serde(default)]
    pub package_loss: String,
    /// Response time
    #[serde(default)]
    pub time: String,
}

/// Response from callbackCheck
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CallbackCheckResponse {
    /// DNS check results
    #[serde(default)]
    pub dns: Vec<DnsInfo>,
    /// Ping check results
    #[serde(default)]
    pub ping: Vec<PingInfo>,
    /// Error code (0 means success)
    #[serde(default)]
    pub(crate) errcode: i32,
    /// Error message
    #[serde(default)]
    pub(crate) errmsg: String,
}

/// Response from getApiDomainIp and getCallbackIp
#[non_exhaustive]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct IpListResponse {
    /// List of IP addresses
    #[serde(default)]
    pub ip_list: Vec<String>,
    /// Error code (0 means success)
    #[serde(default)]
    pub(crate) errcode: i32,
    /// Error message
    #[serde(default)]
    pub(crate) errmsg: String,
}

// ============================================================================
// OpenApiApi
// ============================================================================

/// OpenAPI Management API
///
/// Provides methods for managing API quotas, debugging, and server info.
pub struct OpenApiApi {
    context: Arc<WechatContext>,
}

impl OpenApiApi {
    /// Create a new OpenApiApi instance
    pub fn new(context: Arc<WechatContext>) -> Self {
        Self { context }
    }

    /// Clear all API call quotas for this appid
    ///
    /// POST /cgi-bin/clear_quota?access_token=ACCESS_TOKEN
    ///
    /// # Returns
    /// `Ok(())` on success
    pub async fn clear_quota(&self) -> Result<(), WechatError> {
        let body = ClearQuotaRequest {
            appid: self.context.client.appid().to_string(),
        };
        let response: BaseApiResponse = self
            .context
            .authed_post("/cgi-bin/clear_quota", &body)
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(())
    }

    /// Get API call quota for a specific endpoint
    ///
    /// POST /cgi-bin/openapi/quota/get?access_token=ACCESS_TOKEN
    ///
    /// # Arguments
    /// * `cgi_path` - The API path to query (e.g., "/cgi-bin/message/custom/send")
    pub async fn get_api_quota(&self, cgi_path: &str) -> Result<ApiQuotaResponse, WechatError> {
        let body = GetApiQuotaRequest {
            cgi_path: cgi_path.to_string(),
        };
        let response: ApiQuotaResponse = self
            .context
            .authed_post("/cgi-bin/openapi/quota/get", &body)
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(response)
    }

    /// Clear API call quota for a specific endpoint
    ///
    /// POST /cgi-bin/openapi/quota/clear?access_token=ACCESS_TOKEN
    ///
    /// # Arguments
    /// * `cgi_path` - The API path to clear quota for
    pub async fn clear_api_quota(&self, cgi_path: &str) -> Result<(), WechatError> {
        let body = ClearApiQuotaRequest {
            cgi_path: cgi_path.to_string(),
        };
        let response: BaseApiResponse = self
            .context
            .authed_post("/cgi-bin/openapi/quota/clear", &body)
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(())
    }

    /// Clear all API call quotas using AppSecret (no access_token required)
    ///
    /// POST /cgi-bin/clear_quota/v2
    ///
    /// This endpoint authenticates with appid + appsecret directly,
    /// bypassing the access_token mechanism.
    pub async fn clear_quota_by_app_secret(&self) -> Result<(), WechatError> {
        let path = "/cgi-bin/clear_quota/v2";
        let body = ClearQuotaByAppSecretRequest {
            appid: self.context.client.appid().to_string(),
            appsecret: self.context.client.secret().to_string(),
        };
        let response: BaseApiResponse = self.context.client.post(path, &body).await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(())
    }

    /// Get request debug information by rid
    ///
    /// POST /cgi-bin/openapi/rid/get?access_token=ACCESS_TOKEN
    ///
    /// # Arguments
    /// * `rid` - The request ID to look up
    pub async fn get_rid_info(&self, rid: &str) -> Result<RidInfoResponse, WechatError> {
        let body = GetRidInfoRequest {
            rid: rid.to_string(),
        };
        let response: RidInfoResponse = self
            .context
            .authed_post("/cgi-bin/openapi/rid/get", &body)
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(response)
    }

    /// Check callback URL connectivity
    ///
    /// POST /cgi-bin/callback/check?access_token=ACCESS_TOKEN
    ///
    /// # Arguments
    /// * `action` - Check action type (e.g., "all", "dns", "ping")
    /// * `check_operator` - Operator to check (e.g., "DEFAULT", "CHINANET", "UNICOM", "CAP")
    pub async fn callback_check(
        &self,
        action: &str,
        check_operator: &str,
    ) -> Result<CallbackCheckResponse, WechatError> {
        let body = CallbackCheckRequest {
            action: action.to_string(),
            check_operator: check_operator.to_string(),
        };
        let response: CallbackCheckResponse = self
            .context
            .authed_post("/cgi-bin/callback/check", &body)
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(response)
    }

    /// Get WeChat API server IP addresses
    ///
    /// GET /cgi-bin/get_api_domain_ip?access_token=ACCESS_TOKEN
    pub async fn get_api_domain_ip(&self) -> Result<IpListResponse, WechatError> {
        let response: IpListResponse = self
            .context
            .authed_get("/cgi-bin/get_api_domain_ip", &[])
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(response)
    }

    /// Get WeChat callback server IP addresses
    ///
    /// GET /cgi-bin/getcallbackip?access_token=ACCESS_TOKEN
    pub async fn get_callback_ip(&self) -> Result<IpListResponse, WechatError> {
        let response: IpListResponse = self
            .context
            .authed_get("/cgi-bin/getcallbackip", &[])
            .await?;
        WechatError::check_api(response.errcode, &response.errmsg)?;
        Ok(response)
    }
}

impl WechatApi for OpenApiApi {
    fn context(&self) -> &WechatContext {
        &self.context
    }

    fn api_name(&self) -> &'static str {
        "openapi"
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::WechatClient;
    use crate::token::TokenManager;
    use crate::types::{AppId, AppSecret};

    fn create_test_context(base_url: &str) -> Arc<WechatContext> {
        let appid = AppId::new("wx1234567890abcdef").unwrap();
        let secret = AppSecret::new("secret1234567890ab").unwrap();
        let client = Arc::new(
            WechatClient::builder()
                .appid(appid)
                .secret(secret)
                .base_url(base_url)
                .build()
                .unwrap(),
        );
        let token_manager = Arc::new(TokenManager::new((*client).clone()));
        Arc::new(WechatContext::new(client, token_manager))
    }

    // ---- Deserialization Tests ----

    #[test]
    fn test_api_quota_response_parse() {
        let json = r#"{
            "quota": {
                "daily_limit": 10000000,
                "used": 500,
                "remain": 9999500
            },
            "errcode": 0,
            "errmsg": "ok"
        }"#;

        let response: ApiQuotaResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.quota.daily_limit, 10_000_000);
        assert_eq!(response.quota.used, 500);
        assert_eq!(response.quota.remain, 9_999_500);
        assert_eq!(response.errcode, 0);
    }

    #[test]
    fn test_api_quota_response_missing_quota() {
        let json = r#"{"errcode": 0, "errmsg": "ok"}"#;
        let response: ApiQuotaResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.quota.daily_limit, 0);
        assert_eq!(response.quota.used, 0);
        assert_eq!(response.quota.remain, 0);
    }

    #[test]
    fn test_rid_info_response_parse() {
        let json = r#"{
            "request": {
                "invoke_time": 1635927298,
                "cost_in_ms": 100,
                "request_url": "access_token=xxx",
                "request_body": "{\"appid\":\"wx1234\"}",
                "response_body": "{\"errcode\":0}",
                "client_ip": "1.2.3.4"
            },
            "errcode": 0,
            "errmsg": "ok"
        }"#;

        let response: RidInfoResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.request.invoke_time, 1_635_927_298);
        assert_eq!(response.request.cost_in_ms, 100);
        assert_eq!(response.request.client_ip, "1.2.3.4");
        assert_eq!(response.errcode, 0);
    }

    #[test]
    fn test_rid_info_response_missing_request() {
        let json = r#"{"errcode": 0, "errmsg": "ok"}"#;
        let response: RidInfoResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.request.invoke_time, 0);
        assert!(response.request.client_ip.is_empty());
    }

    #[test]
    fn test_callback_check_response_parse() {
        let json = r#"{
            "dns": [
                {"ip": "1.2.3.4", "real_operator": "unicom"}
            ],
            "ping": [
                {"ip": "1.2.3.4", "from_operator": "cap", "package_loss": "0%", "time": "20.536ms"}
            ],
            "errcode": 0,
            "errmsg": "ok"
        }"#;

        let response: CallbackCheckResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.dns.len(), 1);
        assert_eq!(response.dns[0].ip, "1.2.3.4");
        assert_eq!(response.dns[0].real_operator, "unicom");
        assert_eq!(response.ping.len(), 1);
        assert_eq!(response.ping[0].from_operator, "cap");
        assert_eq!(response.ping[0].package_loss, "0%");
        assert_eq!(response.ping[0].time, "20.536ms");
    }

    #[test]
    fn test_callback_check_response_empty_arrays() {
        let json = r#"{"errcode": 0, "errmsg": "ok"}"#;
        let response: CallbackCheckResponse = serde_json::from_str(json).unwrap();
        assert!(response.dns.is_empty());
        assert!(response.ping.is_empty());
    }

    #[test]
    fn test_ip_list_response_parse() {
        let json = r#"{
            "ip_list": ["101.226.62.77", "101.226.62.78", "101.226.62.79"],
            "errcode": 0,
            "errmsg": "ok"
        }"#;

        let response: IpListResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.ip_list.len(), 3);
        assert_eq!(response.ip_list[0], "101.226.62.77");
    }

    #[test]
    fn test_ip_list_response_empty() {
        let json = r#"{"errcode": 0, "errmsg": "ok"}"#;
        let response: IpListResponse = serde_json::from_str(json).unwrap();
        assert!(response.ip_list.is_empty());
    }

    #[test]
    fn test_api_name() {
        let context = create_test_context("http://localhost:0");
        let api = OpenApiApi::new(context);
        assert_eq!(api.api_name(), "openapi");
    }

    // ---- Wiremock Integration Tests ----

    async fn setup_token_mock(mock_server: &wiremock::MockServer) {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, ResponseTemplate};

        Mock::given(method("GET"))
            .and(path("/cgi-bin/token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "test_token",
                "expires_in": 7200,
                "errcode": 0,
                "errmsg": ""
            })))
            .mount(mock_server)
            .await;
    }

    #[tokio::test]
    async fn test_clear_quota_success() {
        use wiremock::matchers::{method, path, query_param};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        setup_token_mock(&mock_server).await;

        Mock::given(method("POST"))
            .and(path("/cgi-bin/clear_quota"))
            .and(query_param("access_token", "test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "errcode": 0,
                "errmsg": "ok"
            })))
            .mount(&mock_server)
            .await;

        let context = create_test_context(&mock_server.uri());
        let api = OpenApiApi::new(context);
        let result = api.clear_quota().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_clear_quota_api_error() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        setup_token_mock(&mock_server).await;

        Mock::given(method("POST"))
            .and(path("/cgi-bin/clear_quota"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "errcode": 40013,
                "errmsg": "invalid appid"
            })))
            .mount(&mock_server)
            .await;

        let context = create_test_context(&mock_server.uri());
        let api = OpenApiApi::new(context);
        let result = api.clear_quota().await;
        assert!(result.is_err());
        if let Err(WechatError::Api { code, message }) = result {
            assert_eq!(code, 40013);
            assert_eq!(message, "invalid appid");
        } else {
            panic!("Expected WechatError::Api");
        }
    }

    #[tokio::test]
    async fn test_get_api_quota_success() {
        use wiremock::matchers::{method, path, query_param};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        setup_token_mock(&mock_server).await;

        Mock::given(method("POST"))
            .and(path("/cgi-bin/openapi/quota/get"))
            .and(query_param("access_token", "test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "quota": {
                    "daily_limit": 10000000,
                    "used": 500,
                    "remain": 9999500
                },
                "errcode": 0,
                "errmsg": "ok"
            })))
            .mount(&mock_server)
            .await;

        let context = create_test_context(&mock_server.uri());
        let api = OpenApiApi::new(context);
        let result = api.get_api_quota("/cgi-bin/message/custom/send").await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.quota.daily_limit, 10_000_000);
        assert_eq!(response.quota.used, 500);
    }

    #[tokio::test]
    async fn test_clear_quota_by_app_secret_success() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        // No token mock needed — this endpoint doesn't use access_token

        Mock::given(method("POST"))
            .and(path("/cgi-bin/clear_quota/v2"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "errcode": 0,
                "errmsg": "ok"
            })))
            .mount(&mock_server)
            .await;

        let context = create_test_context(&mock_server.uri());
        let api = OpenApiApi::new(context);
        let result = api.clear_quota_by_app_secret().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_get_rid_info_success() {
        use wiremock::matchers::{method, path, query_param};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        setup_token_mock(&mock_server).await;

        Mock::given(method("POST"))
            .and(path("/cgi-bin/openapi/rid/get"))
            .and(query_param("access_token", "test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "request": {
                    "invoke_time": 1635927298,
                    "cost_in_ms": 100,
                    "request_url": "/cgi-bin/clear_quota",
                    "request_body": "",
                    "response_body": "{\"errcode\":0}",
                    "client_ip": "1.2.3.4"
                },
                "errcode": 0,
                "errmsg": "ok"
            })))
            .mount(&mock_server)
            .await;

        let context = create_test_context(&mock_server.uri());
        let api = OpenApiApi::new(context);
        let result = api
            .get_rid_info("61234567-abcd-1234-abcd-123456789012")
            .await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.request.invoke_time, 1_635_927_298);
        assert_eq!(response.request.cost_in_ms, 100);
        assert_eq!(response.request.client_ip, "1.2.3.4");
    }

    #[tokio::test]
    async fn test_callback_check_success() {
        use wiremock::matchers::{method, path, query_param};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        setup_token_mock(&mock_server).await;

        Mock::given(method("POST"))
            .and(path("/cgi-bin/callback/check"))
            .and(query_param("access_token", "test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "dns": [{"ip": "1.2.3.4", "real_operator": "unicom"}],
                "ping": [{"ip": "1.2.3.4", "from_operator": "cap", "package_loss": "0%", "time": "20.536ms"}],
                "errcode": 0,
                "errmsg": "ok"
            })))
            .mount(&mock_server)
            .await;

        let context = create_test_context(&mock_server.uri());
        let api = OpenApiApi::new(context);
        let result = api.callback_check("all", "DEFAULT").await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.dns.len(), 1);
        assert_eq!(response.ping.len(), 1);
    }

    #[tokio::test]
    async fn test_get_api_domain_ip_success() {
        use wiremock::matchers::{method, path, query_param};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        setup_token_mock(&mock_server).await;

        Mock::given(method("GET"))
            .and(path("/cgi-bin/get_api_domain_ip"))
            .and(query_param("access_token", "test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "ip_list": ["101.226.62.77", "101.226.62.78"],
                "errcode": 0,
                "errmsg": "ok"
            })))
            .mount(&mock_server)
            .await;

        let context = create_test_context(&mock_server.uri());
        let api = OpenApiApi::new(context);
        let result = api.get_api_domain_ip().await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.ip_list.len(), 2);
        assert_eq!(response.ip_list[0], "101.226.62.77");
    }

    #[tokio::test]
    async fn test_get_callback_ip_success() {
        use wiremock::matchers::{method, path, query_param};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let mock_server = MockServer::start().await;
        setup_token_mock(&mock_server).await;

        Mock::given(method("GET"))
            .and(path("/cgi-bin/getcallbackip"))
            .and(query_param("access_token", "test_token"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "ip_list": ["101.226.103.61", "101.226.103.62"],
                "errcode": 0,
                "errmsg": "ok"
            })))
            .mount(&mock_server)
            .await;

        let context = create_test_context(&mock_server.uri());
        let api = OpenApiApi::new(context);
        let result = api.get_callback_ip().await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.ip_list.len(), 2);
        assert_eq!(response.ip_list[0], "101.226.103.61");
    }

    #[test]
    fn test_clear_quota_by_app_secret_request_debug_redacts_secret() {
        let request = ClearQuotaByAppSecretRequest {
            appid: "wx1234567890abcdef".to_string(),
            appsecret: "top-secret-appsecret".to_string(),
        };

        let output = format!("{:?}", request);
        assert!(output.contains("appsecret"));
        assert!(output.contains("[REDACTED]"));
        assert!(!output.contains("top-secret-appsecret"));
    }
}