Skip to main content

binance_sdk/pay/rest_api/apis/
pay_api.rs

1/*
2 * Binance Pay REST API
3 *
4 * OpenAPI Specification for the Binance Pay REST API
5 *
6 * The version of the OpenAPI document: 1.0.0
7 *
8 *
9 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
10 * https://openapi-generator.tech
11 * Do not edit the class manually.
12 */
13
14#![allow(unused_imports)]
15use async_trait::async_trait;
16use derive_builder::Builder;
17use reqwest;
18use rust_decimal::prelude::*;
19use serde::{Deserialize, Serialize};
20use serde_json::{Value, json};
21use std::collections::BTreeMap;
22
23use crate::common::{
24    config::ConfigurationRestApi,
25    models::{ParamBuildError, RestApiResponse},
26    utils::send_request,
27};
28use crate::pay::rest_api::models;
29
30const HAS_TIME_UNIT: bool = false;
31
32#[async_trait]
33pub trait PayApi: Send + Sync {
34    async fn get_pay_trade_history(
35        &self,
36        params: GetPayTradeHistoryParams,
37    ) -> anyhow::Result<RestApiResponse<models::GetPayTradeHistoryResponse>>;
38}
39
40#[derive(Debug, Clone)]
41pub struct PayApiClient {
42    configuration: ConfigurationRestApi,
43}
44
45impl PayApiClient {
46    pub fn new(configuration: ConfigurationRestApi) -> Self {
47        Self { configuration }
48    }
49}
50
51/// Request parameters for the [`get_pay_trade_history`] operation.
52///
53/// This struct holds all of the inputs you can pass when calling
54/// [`get_pay_trade_history`](#method.get_pay_trade_history).
55#[derive(Clone, Debug, Builder, Default)]
56#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
57pub struct GetPayTradeHistoryParams {
58    ///
59    /// The `start_time` parameter.
60    ///
61    /// This field is **optional.
62    #[builder(setter(into), default)]
63    pub start_time: Option<i64>,
64    ///
65    /// The `end_time` parameter.
66    ///
67    /// This field is **optional.
68    #[builder(setter(into), default)]
69    pub end_time: Option<i64>,
70    /// default 100, max 100
71    ///
72    /// This field is **optional.
73    #[builder(setter(into), default)]
74    pub limit: Option<i64>,
75    ///
76    /// The `recv_window` parameter.
77    ///
78    /// This field is **optional.
79    #[builder(setter(into), default)]
80    pub recv_window: Option<i64>,
81}
82
83impl GetPayTradeHistoryParams {
84    /// Create a builder for [`get_pay_trade_history`].
85    ///
86    #[must_use]
87    pub fn builder() -> GetPayTradeHistoryParamsBuilder {
88        GetPayTradeHistoryParamsBuilder::default()
89    }
90}
91
92#[async_trait]
93impl PayApi for PayApiClient {
94    async fn get_pay_trade_history(
95        &self,
96        params: GetPayTradeHistoryParams,
97    ) -> anyhow::Result<RestApiResponse<models::GetPayTradeHistoryResponse>> {
98        let GetPayTradeHistoryParams {
99            start_time,
100            end_time,
101            limit,
102            recv_window,
103        } = params;
104
105        let mut query_params = BTreeMap::new();
106        let body_params = BTreeMap::new();
107
108        if let Some(rw) = start_time {
109            query_params.insert("startTime".to_string(), json!(rw));
110        }
111
112        if let Some(rw) = end_time {
113            query_params.insert("endTime".to_string(), json!(rw));
114        }
115
116        if let Some(rw) = limit {
117            query_params.insert("limit".to_string(), json!(rw));
118        }
119
120        if let Some(rw) = recv_window {
121            query_params.insert("recvWindow".to_string(), json!(rw));
122        }
123
124        send_request::<models::GetPayTradeHistoryResponse>(
125            &self.configuration,
126            "/sapi/v1/pay/transactions",
127            reqwest::Method::GET,
128            query_params,
129            body_params,
130            if HAS_TIME_UNIT {
131                self.configuration.time_unit
132            } else {
133                None
134            },
135            true,
136        )
137        .await
138    }
139}
140
141#[cfg(all(test, feature = "pay"))]
142mod tests {
143    use super::*;
144    use crate::TOKIO_SHARED_RT;
145    use crate::{errors::ConnectorError, models::DataFuture, models::RestApiRateLimit};
146    use async_trait::async_trait;
147    use std::collections::HashMap;
148
149    struct DummyRestApiResponse<T> {
150        inner: Box<dyn FnOnce() -> DataFuture<Result<T, ConnectorError>> + Send + Sync>,
151        status: u16,
152        headers: HashMap<String, String>,
153        rate_limits: Option<Vec<RestApiRateLimit>>,
154    }
155
156    impl<T> From<DummyRestApiResponse<T>> for RestApiResponse<T> {
157        fn from(dummy: DummyRestApiResponse<T>) -> Self {
158            Self {
159                data_fn: dummy.inner,
160                status: dummy.status,
161                headers: dummy.headers,
162                rate_limits: dummy.rate_limits,
163            }
164        }
165    }
166
167    struct MockPayApiClient {
168        force_error: bool,
169    }
170
171    #[async_trait]
172    impl PayApi for MockPayApiClient {
173        async fn get_pay_trade_history(
174            &self,
175            _params: GetPayTradeHistoryParams,
176        ) -> anyhow::Result<RestApiResponse<models::GetPayTradeHistoryResponse>> {
177            if self.force_error {
178                return Err(ConnectorError::ConnectorClientError {
179                    msg: "ResponseError".to_string(),
180                    code: None,
181                }
182                .into());
183            }
184
185            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderType":"C2C","transactionId":"M_P_71505104267788288","transactionTime":1610090460133,"amount":"23.72469206","currency":"BNB","walletType":1,"walletTypes":[1,2],"fundsDetail":[{"currency":"USDT","amount":"1.2","walletAssetCost":{"1":"0.6","2":"0.6"}},{"currency":"ETH","amount":"0.0001","walletAssetCost":{"1":"0.00005","2":"0.00005"}}],"payerInfo":{"name":"Jack","type":"USER","binanceId":"12345678"},"receiverInfo":{"name":"Alan","type":"MERCHANT","email":"alan@binance.com","binanceId":"34355667","accountId":"21326891","countryCode":"1","phoneNumber":"8057651210","mobileCode":"US","extend":{"institutionName":"","cardNumber":"","digitalWalletId":""}}}],"success":true}"#).unwrap();
186            let dummy_response: models::GetPayTradeHistoryResponse =
187                serde_json::from_value(resp_json.clone())
188                    .expect("should parse into models::GetPayTradeHistoryResponse");
189
190            let dummy = DummyRestApiResponse {
191                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
192                status: 200,
193                headers: HashMap::new(),
194                rate_limits: None,
195            };
196
197            Ok(dummy.into())
198        }
199    }
200
201    #[test]
202    fn get_pay_trade_history_required_params_success() {
203        TOKIO_SHARED_RT.block_on(async {
204            let client = MockPayApiClient { force_error: false };
205
206            let params = GetPayTradeHistoryParams::builder().build().unwrap();
207
208            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderType":"C2C","transactionId":"M_P_71505104267788288","transactionTime":1610090460133,"amount":"23.72469206","currency":"BNB","walletType":1,"walletTypes":[1,2],"fundsDetail":[{"currency":"USDT","amount":"1.2","walletAssetCost":{"1":"0.6","2":"0.6"}},{"currency":"ETH","amount":"0.0001","walletAssetCost":{"1":"0.00005","2":"0.00005"}}],"payerInfo":{"name":"Jack","type":"USER","binanceId":"12345678"},"receiverInfo":{"name":"Alan","type":"MERCHANT","email":"alan@binance.com","binanceId":"34355667","accountId":"21326891","countryCode":"1","phoneNumber":"8057651210","mobileCode":"US","extend":{"institutionName":"","cardNumber":"","digitalWalletId":""}}}],"success":true}"#).unwrap();
209            let expected_response : models::GetPayTradeHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetPayTradeHistoryResponse");
210
211            let resp = client.get_pay_trade_history(params).await.expect("Expected a response");
212            let data_future = resp.data();
213            let actual_response = data_future.await.unwrap();
214            assert_eq!(actual_response, expected_response);
215        });
216    }
217
218    #[test]
219    fn get_pay_trade_history_optional_params_success() {
220        TOKIO_SHARED_RT.block_on(async {
221            let client = MockPayApiClient { force_error: false };
222
223            let params = GetPayTradeHistoryParams::builder().start_time(1623319461670).end_time(1641782889000).limit(100).recv_window(5000).build().unwrap();
224
225            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderType":"C2C","transactionId":"M_P_71505104267788288","transactionTime":1610090460133,"amount":"23.72469206","currency":"BNB","walletType":1,"walletTypes":[1,2],"fundsDetail":[{"currency":"USDT","amount":"1.2","walletAssetCost":{"1":"0.6","2":"0.6"}},{"currency":"ETH","amount":"0.0001","walletAssetCost":{"1":"0.00005","2":"0.00005"}}],"payerInfo":{"name":"Jack","type":"USER","binanceId":"12345678"},"receiverInfo":{"name":"Alan","type":"MERCHANT","email":"alan@binance.com","binanceId":"34355667","accountId":"21326891","countryCode":"1","phoneNumber":"8057651210","mobileCode":"US","extend":{"institutionName":"","cardNumber":"","digitalWalletId":""}}}],"success":true}"#).unwrap();
226            let expected_response : models::GetPayTradeHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetPayTradeHistoryResponse");
227
228            let resp = client.get_pay_trade_history(params).await.expect("Expected a response");
229            let data_future = resp.data();
230            let actual_response = data_future.await.unwrap();
231            assert_eq!(actual_response, expected_response);
232        });
233    }
234
235    #[test]
236    fn get_pay_trade_history_response_error() {
237        TOKIO_SHARED_RT.block_on(async {
238            let client = MockPayApiClient { force_error: true };
239
240            let params = GetPayTradeHistoryParams::builder().build().unwrap();
241
242            match client.get_pay_trade_history(params).await {
243                Ok(_) => panic!("Expected an error"),
244                Err(err) => {
245                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
246                }
247            }
248        });
249    }
250}