Skip to main content

epay_sdk/
order.rs

1//! Order queries (`act=order`, `act=orders`) and order-number generation.
2
3use std::collections::BTreeMap;
4use std::sync::atomic::{AtomicU32, Ordering};
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use serde::Deserialize;
8use serde_json::Value;
9
10use crate::endpoint::Endpoint;
11use crate::error::{Error, Result};
12use crate::money::Money;
13use crate::serde_util::{default_on_null, flex_i32, flex_u64};
14use crate::types::OrderStatus;
15use crate::validation::{
16    Identifier, exactly_one_identifier, validate_out_trade_no, validate_trade_no,
17};
18
19/// Query a single order by merchant id or EPay id.
20///
21/// Exactly one identifier must be set.
22#[derive(Clone, Debug, Default)]
23#[non_exhaustive]
24pub struct OrderQueryRequest {
25    /// EPay order number.
26    pub trade_no: Option<String>,
27    /// Merchant order number.
28    pub out_trade_no: Option<String>,
29}
30
31impl OrderQueryRequest {
32    /// Query by merchant order number.
33    pub fn out_trade_no(no: impl Into<String>) -> Self {
34        Self {
35            trade_no: None,
36            out_trade_no: Some(no.into()),
37        }
38    }
39
40    /// Query by EPay order number.
41    pub fn trade_no(no: impl Into<String>) -> Self {
42        Self {
43            trade_no: Some(no.into()),
44            out_trade_no: None,
45        }
46    }
47
48    /// Check that exactly one well-formed identifier is present.
49    pub fn validate(&self) -> Result<()> {
50        self.identifier().map(|_| ())
51    }
52
53    pub(crate) fn identifier(&self) -> Result<Identifier<'_>> {
54        exactly_one_identifier(self.trade_no.as_deref(), self.out_trade_no.as_deref())
55    }
56}
57
58/// Order row returned by `act=order` / `act=orders`.
59///
60/// Text columns that the gateway reports as `null` are exposed as empty
61/// strings. Successful single-order queries are additionally checked to
62/// match the requested identifier and the configured PID. Anything the
63/// gateway returns beyond the modelled columns is kept in
64/// [`OrderDetail::extra`]. `Debug` shows `buyer` and `param` (possibly
65/// personal data) as lengths and `extra` as its keys.
66#[derive(Clone, Deserialize)]
67#[non_exhaustive]
68pub struct OrderDetail {
69    /// EPay order number.
70    #[serde(default, deserialize_with = "default_on_null")]
71    pub trade_no: String,
72    /// Merchant order number.
73    #[serde(default, deserialize_with = "default_on_null")]
74    pub out_trade_no: String,
75    /// Upstream channel transaction id.
76    #[serde(default, deserialize_with = "default_on_null")]
77    pub api_trade_no: String,
78    /// Payment channel (`type`).
79    #[serde(default, rename = "type", deserialize_with = "default_on_null")]
80    pub pay_type: String,
81    /// Merchant id.
82    #[serde(default, deserialize_with = "flex_u64")]
83    pub pid: u64,
84    /// Creation time (`addtime`) as `YYYY-MM-DD HH:MM:SS` in the gateway's
85    /// local time zone (Beijing time, UTC+8, on official deployments).
86    #[serde(default, alias = "addtime", deserialize_with = "default_on_null")]
87    pub add_time: String,
88    /// Completion time (`endtime`), same format as [`OrderDetail::add_time`];
89    /// empty while unpaid.
90    #[serde(default, alias = "endtime", deserialize_with = "default_on_null")]
91    pub end_time: String,
92    /// Product name.
93    #[serde(default, deserialize_with = "default_on_null")]
94    pub name: String,
95    /// Amount as a decimal string (`"10.00"`).
96    #[serde(default, deserialize_with = "default_on_null")]
97    pub money: String,
98    /// Raw status integer; see [`OrderDetail::status`].
99    #[serde(default, deserialize_with = "flex_i32")]
100    pub status: i32,
101    /// Opaque merchant data from the original request.
102    #[serde(default, deserialize_with = "default_on_null")]
103    pub param: String,
104    /// Payer account, when the channel reports it.
105    #[serde(default, deserialize_with = "default_on_null")]
106    pub buyer: String,
107    /// Fields returned by the gateway that this SDK does not model, e.g.
108    /// fork-specific `bill_trade_no` or `pay_fee`. The client strips the
109    /// envelope `code`; `msg` may be present.
110    #[serde(flatten)]
111    pub extra: BTreeMap<String, Value>,
112}
113
114impl std::fmt::Debug for OrderDetail {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        let extra_keys: Vec<&str> = self.extra.keys().map(String::as_str).collect();
117        f.debug_struct("OrderDetail")
118            .field("trade_no", &self.trade_no)
119            .field("out_trade_no", &self.out_trade_no)
120            .field("api_trade_no", &self.api_trade_no)
121            .field("pay_type", &self.pay_type)
122            .field("pid", &self.pid)
123            .field("add_time", &self.add_time)
124            .field("end_time", &self.end_time)
125            .field("name", &self.name)
126            .field("money", &self.money)
127            .field("status", &self.status)
128            .field("param", &format_args!("<{} bytes>", self.param.len()))
129            .field("buyer", &format_args!("<{} bytes>", self.buyer.len()))
130            .field("extra_keys", &extra_keys)
131            .finish()
132    }
133}
134
135impl OrderDetail {
136    /// Typed payment status.
137    pub fn status(&self) -> OrderStatus {
138        OrderStatus::from_i32(self.status)
139    }
140
141    /// Whether the order is paid.
142    pub fn is_paid(&self) -> bool {
143        self.status().is_paid()
144    }
145
146    /// Whether the order is unpaid (status `0`).
147    pub fn is_unpaid(&self) -> bool {
148        matches!(self.status(), OrderStatus::Unpaid)
149    }
150
151    /// Parse [`OrderDetail::money`] as a strict [`Money`].
152    pub fn amount(&self) -> Result<Money> {
153        Money::from_yuan_str(&self.money)
154    }
155
156    pub(crate) fn validate_success(&self, request: &OrderQueryRequest, pid: u64) -> Result<()> {
157        let endpoint = Endpoint::QueryOrder;
158        match request.identifier()? {
159            Identifier::TradeNo(expected) if self.trade_no != expected => {
160                return Err(Error::invalid_response_message(
161                    endpoint,
162                    "returned trade_no does not match the request",
163                ));
164            }
165            Identifier::OutTradeNo(expected) if self.out_trade_no != expected => {
166                return Err(Error::invalid_response_message(
167                    endpoint,
168                    "returned out_trade_no does not match the request",
169                ));
170            }
171            _ => {}
172        }
173        self.validate_row(endpoint, pid)
174    }
175
176    fn validate_row(&self, endpoint: Endpoint, pid: u64) -> Result<()> {
177        validate_trade_no(&self.trade_no).map_err(|_| {
178            Error::invalid_response_message(endpoint, "returned trade_no is invalid")
179        })?;
180        validate_out_trade_no(&self.out_trade_no).map_err(|_| {
181            Error::invalid_response_message(endpoint, "returned out_trade_no is invalid")
182        })?;
183        if self.pid != pid {
184            return Err(Error::invalid_response_message(
185                endpoint,
186                "returned pid does not match the configured pid",
187            ));
188        }
189        self.amount()
190            .map_err(|_| Error::invalid_response_message(endpoint, "returned money is invalid"))?;
191        Ok(())
192    }
193}
194
195/// Batch order query result (`act=orders`).
196#[derive(Clone, Debug, Deserialize)]
197#[non_exhaustive]
198pub struct OrderListResponse {
199    /// Order count reported by the gateway: the total on some forks, the
200    /// page size on others. Pagination helpers ignore it.
201    #[serde(default, deserialize_with = "flex_i32")]
202    pub count: i32,
203    /// Orders on the requested page.
204    #[serde(default, alias = "data", deserialize_with = "default_on_null")]
205    pub orders: Vec<OrderDetail>,
206    /// Unmodelled members of the response object.
207    #[serde(flatten)]
208    pub extra: BTreeMap<String, Value>,
209}
210
211impl OrderListResponse {
212    /// Whether another page probably exists: the page was full for the
213    /// `limit` that was requested (clamped like the client clamps it).
214    pub fn has_more(&self, limit: u32) -> bool {
215        self.orders.len() as u64 >= u64::from(limit.clamp(1, 50))
216    }
217
218    /// Page number to request next, if [`OrderListResponse::has_more`].
219    pub fn next_page(&self, page: u32, limit: u32) -> Option<u32> {
220        self.has_more(limit).then(|| page.max(1).saturating_add(1))
221    }
222
223    pub(crate) fn validate_success(&self, pid: u64) -> Result<()> {
224        let endpoint = Endpoint::QueryOrders;
225        if self.count < 0 {
226            return Err(Error::invalid_response_message(
227                endpoint,
228                "returned count is negative",
229            ));
230        }
231        for order in &self.orders {
232            order.validate_row(endpoint, pid)?;
233        }
234        Ok(())
235    }
236}
237
238/// Generate a protocol-valid, probabilistically unique merchant order number.
239///
240/// The result is `prefix` + nanosecond timestamp + a 4-digit in-process
241/// sequence. Multiple processes can still collide in theory; persist your
242/// own identifiers when strict uniqueness is required.
243pub fn generate_out_trade_no(prefix: &str) -> Result<String> {
244    static SEQUENCE: AtomicU32 = AtomicU32::new(0);
245    let nanos = SystemTime::now()
246        .duration_since(UNIX_EPOCH)
247        .map_err(|_| Error::Param("system clock is before the Unix epoch"))?
248        .as_nanos();
249    let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) % 10_000;
250    let value = format!("{prefix}{nanos}{sequence:04}");
251    validate_out_trade_no(&value)?;
252    Ok(value)
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn parses_nullable_text_columns_from_php_database_rows() {
261        let json = r#"{
262            "code":1,
263            "msg":"succ",
264            "trade_no":"T202608280001",
265            "out_trade_no":"ORDER001",
266            "api_trade_no":"UPSTREAM001",
267            "bill_trade_no":null,
268            "type":"wxpay",
269            "pid":"1001",
270            "addtime":"2026-08-28 12:00:00",
271            "endtime":null,
272            "name":null,
273            "money":"0.01",
274            "status":"1",
275            "param":null,
276            "buyer":null
277        }"#;
278        let order: OrderDetail = serde_json::from_str(json).unwrap();
279        assert_eq!(order.end_time, "");
280        assert_eq!(order.name, "");
281        assert_eq!(order.param, "");
282        assert_eq!(order.buyer, "");
283        assert!(order.is_paid());
284        assert!(order.extra["bill_trade_no"].is_null());
285        assert!(!order.extra.contains_key("addtime"), "aliases are modelled");
286
287        let with_pii: OrderDetail = serde_json::from_str(
288            r#"{"trade_no":"T1","out_trade_no":"O1","buyer":"someone@example.com","param":"uid=7","fork":"x"}"#,
289        )
290        .unwrap();
291        let debug = format!("{with_pii:?}");
292        assert!(
293            !debug.contains("example.com") && !debug.contains("uid=7"),
294            "{debug}"
295        );
296        assert!(debug.contains("fork") && debug.contains("O1"), "{debug}");
297        assert_eq!(order.amount().unwrap().to_epay_string(), "0.01");
298        assert!(
299            order
300                .validate_success(&OrderQueryRequest::out_trade_no("ORDER001"), 1001)
301                .is_ok()
302        );
303        assert!(
304            order
305                .validate_success(&OrderQueryRequest::out_trade_no("OTHER"), 1001)
306                .is_err()
307        );
308    }
309
310    #[test]
311    fn parses_list_with_string_count_data_alias_and_null_data() {
312        let json = r#"{"code":"1","msg":"ok","count":"1","data":[{"trade_no":"T1","out_trade_no":"O1","status":"1","money":"10.00","pid":"1001"}]}"#;
313        let list: OrderListResponse = serde_json::from_str(json).unwrap();
314        assert_eq!(list.count, 1);
315        assert_eq!(list.orders.len(), 1);
316        assert!(list.orders[0].is_paid());
317        assert_eq!(list.orders[0].pid, 1001);
318        assert!(list.validate_success(1001).is_ok());
319        assert!(list.validate_success(2002).is_err());
320
321        let empty: OrderListResponse =
322            serde_json::from_str(r#"{"code":1,"count":0,"data":null}"#).unwrap();
323        assert!(empty.orders.is_empty());
324        assert!(empty.validate_success(1001).is_ok());
325        assert!(!empty.has_more(1));
326        assert_eq!(empty.next_page(1, 1), None);
327        assert!(list.has_more(1));
328        assert_eq!(list.next_page(0, 1), Some(2));
329        assert_eq!(list.next_page(7, 1), Some(8));
330    }
331
332    #[test]
333    fn generated_order_number_is_validated() {
334        let first = generate_out_trade_no("ORDER").unwrap();
335        let second = generate_out_trade_no("ORDER").unwrap();
336        assert_ne!(first, second);
337        assert!(first.starts_with("ORDER"));
338        assert!(validate_out_trade_no(&generate_out_trade_no("").unwrap()).is_ok());
339        assert!(generate_out_trade_no("bad/").is_err());
340    }
341}