epay-sdk 1.0.0

EPay (易支付) SDK for Rust — 彩虹易支付 V1 compatible client with an axum integration
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
//! Error type, stable numeric codes and log-safe redaction helpers.

use std::fmt;

use crate::endpoint::Endpoint;

/// SDK result type.
pub type Result<T, E = Error> = std::result::Result<T, E>;

/// Stable SDK error codes, compatible with the original Go SDK mapping.
pub mod code {
    /// Invalid configuration.
    pub const INVALID_CONFIG: i32 = 1001;
    /// Signature verification failed.
    pub const VERIFY_FAILED: i32 = 1003;
    /// The gateway answered with a business error.
    pub const API: i32 = 1004;
    /// Transport failure, unexpected HTTP status or oversized response.
    pub const NETWORK: i32 = 1005;
    /// Successful envelope with an unusable payload.
    pub const INVALID_RESPONSE: i32 = 1006;
    /// Invalid request parameter or notification.
    pub const INVALID_PARAM: i32 = 1007;
}

/// Coarse classification of transport failures.
///
/// Callers use this to decide whether a retry is reasonable. Retrying a
/// mutating call such as [`crate::Client::create_payment`] still requires the
/// application to reason about idempotency of the `out_trade_no`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TransportErrorKind {
    /// The request or the response body read timed out.
    Timeout,
    /// The TCP or TLS connection could not be established.
    Connect,
    /// A redirect was received and rejected.
    Redirect,
    /// The response body could not be read or decoded.
    Body,
    /// The request could not be built or sent.
    Request,
    /// Any other failure.
    Other,
}

/// Stable, coarse error category for metrics and HTTP mapping.
///
/// Low-cardinality and independent of the [`Error`] variants' payloads, so
/// it is the right thing to match on in application code. It is still
/// `#[non_exhaustive]`: keep a fallback arm, because a new category may be
/// added in a future minor release (always with a changelog entry).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
    /// Client or protocol configuration is invalid.
    Config,
    /// A request parameter or notification is invalid.
    InvalidParameter,
    /// Signature verification failed.
    Verification,
    /// The gateway answered with a business error.
    Provider,
    /// Transport failure, unexpected HTTP status or oversized response.
    Transport,
    /// Successful envelope with an unusable payload.
    InvalidResponse,
}

/// EPay SDK error.
///
/// Error text generated by the built-in client never includes a request URL.
/// Response previews are bounded and have `key` / `sign` values masked.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Invalid client or protocol configuration.
    #[error("invalid configuration: {0}")]
    Config(&'static str),

    /// Invalid outbound request parameter.
    #[error("invalid parameter: {0}")]
    Param(&'static str),

    /// A notification was malformed, unauthenticated by metadata, or
    /// structurally invalid. Signature mismatches use [`Error::VerifyFailed`].
    #[error("invalid notify: {message}")]
    Notify {
        /// Redacted description of the rejection.
        message: String,
    },

    /// MD5 signature verification failed.
    #[error("signature verification failed")]
    VerifyFailed,

    /// The gateway answered with a non-success `code`.
    #[error("epay API error at {endpoint} (code {code}): {message}")]
    Api {
        /// Endpoint that produced the error.
        endpoint: Endpoint,
        /// Gateway `code` value.
        code: i32,
        /// Gateway `msg` value, redacted.
        message: String,
    },

    /// The HTTP transport failed before a response status was available.
    #[error("HTTP transport error ({kind:?}): {message}")]
    Transport {
        /// Failure classification.
        kind: TransportErrorKind,
        /// Redacted, URL-free description.
        message: String,
    },

    /// The gateway returned a non-2xx status.
    #[error("unexpected HTTP status {status}: {body}")]
    Http {
        /// HTTP status code.
        status: u16,
        /// Redacted preview of the response body.
        body: String,
    },

    /// The gateway reported success but the payload is unusable.
    #[error("invalid response from {endpoint}: {message}")]
    InvalidResponse {
        /// Endpoint that produced the response.
        endpoint: Endpoint,
        /// Redacted description including a bounded body preview.
        message: String,
    },

    /// The response body exceeded the configured limit.
    #[error("response body exceeds configured limit of {limit} bytes")]
    ResponseTooLarge {
        /// Configured limit in bytes.
        limit: usize,
    },
}

impl Error {
    /// Coarse category; see [`ErrorKind`].
    pub fn kind(&self) -> ErrorKind {
        match self {
            Self::Config(_) => ErrorKind::Config,
            Self::Param(_) | Self::Notify { .. } => ErrorKind::InvalidParameter,
            Self::VerifyFailed => ErrorKind::Verification,
            Self::Api { .. } => ErrorKind::Provider,
            Self::Transport { .. } | Self::Http { .. } | Self::ResponseTooLarge { .. } => {
                ErrorKind::Transport
            }
            Self::InvalidResponse { .. } => ErrorKind::InvalidResponse,
        }
    }

    /// Numeric error code, compatible with the original Go SDK mapping.
    pub fn code(&self) -> i32 {
        match self.kind() {
            ErrorKind::Config => code::INVALID_CONFIG,
            ErrorKind::InvalidParameter => code::INVALID_PARAM,
            ErrorKind::Verification => code::VERIFY_FAILED,
            ErrorKind::Provider => code::API,
            ErrorKind::Transport => code::NETWORK,
            ErrorKind::InvalidResponse => code::INVALID_RESPONSE,
        }
    }

    /// Gateway endpoint involved, for [`Error::Api`] and
    /// [`Error::InvalidResponse`].
    pub fn endpoint(&self) -> Option<Endpoint> {
        match self {
            Self::Api { endpoint, .. } | Self::InvalidResponse { endpoint, .. } => Some(*endpoint),
            _ => None,
        }
    }

    /// Transport failure classification, if this is a transport error.
    pub fn transport_kind(&self) -> Option<TransportErrorKind> {
        match self {
            Self::Transport { kind, .. } => Some(*kind),
            _ => None,
        }
    }

    /// Whether the failure was a transport timeout.
    pub fn is_timeout(&self) -> bool {
        self.transport_kind() == Some(TransportErrorKind::Timeout)
    }

    /// Whether the request never reached (or never received an answer from)
    /// the gateway's application layer, so repeating it is safe for
    /// read-only endpoints: transport timeouts / connection failures and
    /// HTTP 502/503/504.
    ///
    /// [`crate::RetryPolicy`] consults this. Business errors
    /// ([`Error::Api`]) and malformed responses are never retryable.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::Transport { kind, .. } => {
                matches!(
                    kind,
                    TransportErrorKind::Timeout | TransportErrorKind::Connect
                )
            }
            Self::Http { status, .. } => matches!(status, 502..=504),
            _ => false,
        }
    }

    /// Build a transport error with a redacted message.
    ///
    /// Custom [`crate::Transport`] implementations should use this rather
    /// than formatting a URL-bearing error into the message.
    pub fn transport(kind: TransportErrorKind, message: impl fmt::Display) -> Self {
        Self::Transport {
            kind,
            message: redact_secrets(&message.to_string()),
        }
    }

    pub(crate) fn notify(message: impl Into<String>) -> Self {
        Self::Notify {
            message: redact_secrets(&message.into()),
        }
    }

    pub(crate) fn api(endpoint: Endpoint, code: i32, message: impl Into<String>) -> Self {
        Self::Api {
            endpoint,
            code,
            message: redact_secrets(&message.into()),
        }
    }

    pub(crate) fn invalid_response(
        endpoint: Endpoint,
        err: impl fmt::Display,
        body: &[u8],
    ) -> Self {
        Self::InvalidResponse {
            endpoint,
            message: format!("{err}: {}", body_preview(body)),
        }
    }

    pub(crate) fn invalid_response_message(endpoint: Endpoint, message: impl Into<String>) -> Self {
        Self::InvalidResponse {
            endpoint,
            message: redact_secrets(&message.into()),
        }
    }

    /// Build an [`Error::Http`] for a non-2xx response, keeping a bounded,
    /// redacted preview of `body`. Custom [`crate::Transport`]s should use
    /// this instead of embedding the raw body.
    pub fn http(status: u16, body: &[u8]) -> Self {
        Self::Http {
            status,
            body: body_preview(body),
        }
    }

    /// Re-sanitize errors returned by custom transports before surfacing them.
    pub(crate) fn sanitized(self) -> Self {
        match self {
            Self::Transport { kind, message } => Self::Transport {
                kind,
                message: redact_secrets(&message),
            },
            Self::Http { status, body } => Self::Http {
                status,
                body: redact_secrets(&body),
            },
            Self::Api {
                endpoint,
                code,
                message,
            } => Self::Api {
                endpoint,
                code,
                message: redact_secrets(&message),
            },
            Self::InvalidResponse { endpoint, message } => Self::InvalidResponse {
                endpoint,
                message: redact_secrets(&message),
            },
            Self::Notify { message } => Self::Notify {
                message: redact_secrets(&message),
            },
            other => other,
        }
    }
}

/// Well-known configuration and parameter errors.
impl Error {
    /// PID must be greater than zero.
    pub const INVALID_PID: Self = Self::Config("invalid PID: must be greater than 0");
    /// Merchant key must not be empty.
    pub const INVALID_KEY: Self = Self::Config("invalid Key: must not be empty");
    /// API base URL is malformed or carries credentials, query or fragment.
    pub const INVALID_API_URL: Self = Self::Config("invalid API base URL");
    /// API base URL uses plain HTTP without explicit opt-in.
    pub const INSECURE_API_URL: Self = Self::Config(
        "API base URL must use HTTPS; call allow_insecure_http(true) for a legacy HTTP gateway",
    );
    /// `notify_url` is not an absolute HTTP(S) URL.
    pub const INVALID_NOTIFY_URL: Self = Self::Param("notify_url must be an absolute HTTP(S) URL");
    /// `return_url` is not an absolute HTTP(S) URL.
    pub const INVALID_RETURN_URL: Self = Self::Param("return_url must be an absolute HTTP(S) URL");
    /// `notify_url` uses plain HTTP without explicit opt-in.
    pub const INSECURE_NOTIFY_URL: Self = Self::Param(
        "notify_url must use HTTPS; call allow_insecure_callback_http(true) for local testing",
    );
    /// `return_url` uses plain HTTP without explicit opt-in.
    pub const INSECURE_RETURN_URL: Self = Self::Param(
        "return_url must use HTTPS; call allow_insecure_callback_http(true) for local testing",
    );
    /// `out_trade_no` is empty.
    pub const MISSING_OUT_TRADE_NO: Self = Self::Param("out_trade_no is required");
    /// `out_trade_no` violates the accepted charset or length.
    pub const INVALID_OUT_TRADE_NO: Self =
        Self::Param("out_trade_no must be 1..=64 ASCII characters from [A-Za-z0-9._|-]");
    /// Neither the request nor the configuration provides a `notify_url`.
    pub const MISSING_NOTIFY_URL: Self = Self::Param("notify_url is required");
    /// Product `name` is blank.
    pub const MISSING_NAME: Self = Self::Param("name is required");
    /// Product `name` exceeds [`crate::limits::MAX_NAME_BYTES`].
    pub const NAME_TOO_LONG: Self = Self::Param("name exceeds 255 bytes");
    /// Product `name` contains control characters.
    pub const NAME_HAS_CONTROL_CHARS: Self =
        Self::Param("name must not contain control characters");
    /// `sitename` contains control characters.
    pub const SITENAME_HAS_CONTROL_CHARS: Self =
        Self::Param("sitename must not contain control characters");
    /// `param` exceeds [`crate::limits::MAX_PARAM_BYTES`].
    pub const PARAM_TOO_LONG: Self = Self::Param("param exceeds 255 bytes");
    /// `sitename` exceeds [`crate::limits::MAX_SITENAME_BYTES`].
    pub const SITENAME_TOO_LONG: Self = Self::Param("sitename exceeds 64 bytes");
    /// A callback URL exceeds [`crate::limits::MAX_CALLBACK_URL_BYTES`].
    pub const CALLBACK_URL_TOO_LONG: Self =
        Self::Param("notify_url / return_url exceeds 1024 bytes");
    /// The signed request exceeds [`crate::limits::MAX_REQUEST_BYTES`].
    pub const REQUEST_TOO_LARGE: Self =
        Self::Param("encoded request exceeds 4096 bytes; shorten name, param or callback URLs");
    /// Payment `type` is blank or not a short `[A-Za-z0-9_-]` identifier.
    pub const INVALID_PAY_TYPE: Self =
        Self::Param("payment type must be 1..=32 characters from [A-Za-z0-9_-]");
    /// `device` is blank or not a short `[A-Za-z0-9_-]` identifier.
    pub const INVALID_DEVICE: Self =
        Self::Param("device must be 1..=32 characters from [A-Za-z0-9_-]");
    /// Amount is not positive or not parseable.
    pub const INVALID_MONEY: Self = Self::Param("money must be greater than 0");
    /// Amount carries meaningful precision beyond two decimal places.
    pub const INVALID_MONEY_PRECISION: Self =
        Self::Param("money must have at most two fractional decimal places");
    /// Amount does not fit the `i64` fen range.
    pub const MONEY_OUT_OF_RANGE: Self = Self::Param("money exceeds the i64 fen range");
    /// Exactly one of `trade_no` / `out_trade_no` must be given.
    pub const MISSING_TRADE_NO: Self =
        Self::Param("exactly one of trade_no or out_trade_no is required");
    /// `trade_no` is not a non-blank ASCII identifier.
    pub const INVALID_TRADE_NO: Self = Self::Param("trade_no must be a non-blank ASCII identifier");
    /// `clientip` is required by `mapi.php`.
    pub const MISSING_CLIENT_IP: Self = Self::Param("clientip is required by mapi.php");
    /// `clientip` is not a valid IP address.
    pub const INVALID_CLIENT_IP: Self = Self::Param("clientip must be a valid IPv4/IPv6 address");
}

/// First 256 characters of a response body with secrets masked.
pub(crate) fn body_preview(body: &[u8]) -> String {
    redact_secrets(&String::from_utf8_lossy(body))
        .chars()
        .take(256)
        .collect()
}

/// Mask JSON members and form/query fragments named `key` or `sign`.
pub(crate) fn redact_secrets(input: &str) -> String {
    redact_form_secrets(&redact_json_secrets(input))
}

/// Mask the value of every `"key"` / `"sign"` member in JSON-like text.
pub(crate) fn redact_json_secrets(body: &str) -> String {
    let mut out = String::with_capacity(body.len());
    let mut rest = body;
    while let Some((idx, needle)) = find_secret_member(rest) {
        let (head, tail) = rest.split_at(idx + needle.len());
        out.push_str(head);
        let Some(after_colon) = tail.trim_start().strip_prefix(':') else {
            rest = tail;
            continue;
        };
        let Some(value) = after_colon.trim_start().strip_prefix('"') else {
            rest = tail;
            continue;
        };
        out.push_str(":\"***\"");
        rest = match json_string_end(value) {
            Some(end) => &value[end + 1..],
            None => "",
        };
    }
    out.push_str(rest);
    out
}

fn redact_form_secrets(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut rest = input;
    loop {
        let next = ["key=", "sign="]
            .into_iter()
            .filter_map(|needle| rest.find(needle).map(|idx| (idx, needle)))
            .filter(|(idx, _)| {
                *idx == 0
                    || rest[..*idx]
                        .chars()
                        .next_back()
                        .is_some_and(|c| matches!(c, '?' | '&' | ' ' | '\'' | '"'))
            })
            .min_by_key(|(idx, _)| *idx);
        let Some((idx, needle)) = next else {
            out.push_str(rest);
            break;
        };
        let value_start = idx + needle.len();
        out.push_str(&rest[..value_start]);
        out.push_str("***");
        let value = &rest[value_start..];
        let end = value
            .char_indices()
            .find(|(_, c)| matches!(c, '&' | ' ' | '\'' | '"' | ')' | ']'))
            .map(|(idx, _)| idx)
            .unwrap_or(value.len());
        rest = &value[end..];
    }
    out
}

fn find_secret_member(s: &str) -> Option<(usize, &'static str)> {
    ["\"key\"", "\"sign\""]
        .into_iter()
        .filter_map(|needle| s.find(needle).map(|idx| (idx, needle)))
        .min_by_key(|(idx, _)| *idx)
}

fn json_string_end(s: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => i += 2,
            b'"' => return Some(i),
            _ => i += 1,
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn display_and_code() {
        let err = Error::api(Endpoint::CreatePayment, -1, "余额不足");
        assert_eq!(err.code(), code::API);
        assert_eq!(err.kind(), ErrorKind::Provider);
        assert_eq!(err.endpoint(), Some(Endpoint::CreatePayment));
        assert_eq!(Error::VerifyFailed.kind(), ErrorKind::Verification);
        assert_eq!(Error::VerifyFailed.endpoint(), None);
        assert_eq!(Error::INVALID_PID.kind(), ErrorKind::Config);
        assert_eq!(
            Error::ResponseTooLarge { limit: 1 }.kind(),
            ErrorKind::Transport
        );
        assert!(err.to_string().contains("mapi.php"));
        assert!(err.to_string().contains("code -1"));
        assert!(err.to_string().contains("余额不足"));

        let timeout = Error::transport(TransportErrorKind::Timeout, "timeout");
        assert_eq!(timeout.code(), code::NETWORK);
        assert!(timeout.is_timeout());
        assert!(timeout.is_retryable());
        assert_eq!(timeout.transport_kind(), Some(TransportErrorKind::Timeout));
        assert_eq!(Error::VerifyFailed.transport_kind(), None);
        assert!(Error::http(503, b"").is_retryable());
        assert!(!Error::http(500, b"").is_retryable());
        assert!(!Error::transport(TransportErrorKind::Redirect, "x").is_retryable());
        assert!(!err.is_retryable());
    }

    #[test]
    fn transport_messages_are_redacted() {
        let err = Error::transport(
            TransportErrorKind::Other,
            "failed https://pay.example/api.php?key=super-secret",
        );
        assert!(!err.to_string().contains("super-secret"), "{err}");
    }

    #[test]
    fn redacts_json_and_url_secrets() {
        assert_eq!(
            redact_secrets(r#"{"code":1,"key":"super-secret","sign":"deadbeef"}"#),
            r#"{"code":1,"key":"***","sign":"***"}"#
        );
        let text =
            redact_secrets("request https://pay.example/api.php?act=query&key=super-secret&pid=1");
        assert!(!text.contains("super-secret"), "{text}");
        assert!(text.contains("key=***"), "{text}");
    }

    #[test]
    fn truncated_json_secret_is_removed() {
        assert_eq!(redact_secrets(r#"{"key":"super-sec"#), r#"{"key":"***""#);
    }

    #[test]
    fn error_previews_are_redacted_and_capped() {
        let body = br#"PHP Warning: x{"code":1,"key":"super-secret"}"#;
        let err = Error::invalid_response(Endpoint::QueryMerchant, "expected value", body);
        assert!(!err.to_string().contains("super-secret"), "{err}");
        let long = format!(r#"{{"msg":"{}","key":"super-secret"}}"#, "x".repeat(300));
        let err = Error::invalid_response(Endpoint::QueryMerchant, "eof", long.as_bytes());
        assert!(!err.to_string().contains("super-secret"), "{err}");
        assert!(err.to_string().len() < 350);
    }
}