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
use crate::{Result, SumUpClient, Transaction, TransactionHistoryResponse};
use serde::Serialize;
#[derive(Debug, Clone, Serialize, Default)]
pub struct TransactionHistoryQuery<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub order: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub newest_time: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub oldest_time: Option<&'a str>,
// Add other query parameters as needed
}
impl SumUpClient {
/// Lists detailed history of all transactions associated with the merchant profile.
/// Uses the modern v2.1 endpoint.
///
/// # Arguments
/// * `merchant_code` - The merchant's unique code.
/// * `query` - A struct with query parameters for filtering and pagination.
pub async fn list_transactions_history(
&self,
merchant_code: &str,
query: &TransactionHistoryQuery<'_>,
) -> Result<TransactionHistoryResponse> {
let url = self.build_url(&format!(
"/v2.1/merchants/{}/transactions/history",
merchant_code
))?;
let response = self
.http_client
.get(url)
.bearer_auth(&self.api_key)
.query(query)
.send()
.await?;
if response.status().is_success() {
let history = response.json::<TransactionHistoryResponse>().await?;
Ok(history)
} else {
self.handle_error(response).await
}
}
/// Retrieves the full details of an identified transaction.
/// Uses the modern v2.1 endpoint.
///
/// # Arguments
/// * `merchant_code` - The merchant's unique code.
/// * `transaction_id` - The transaction's unique ID.
pub async fn retrieve_transaction_by_id(
&self,
merchant_code: &str,
transaction_id: &str,
) -> Result<Transaction> {
let mut url = self.build_url(&format!("/v2.1/merchants/{}/transactions", merchant_code))?;
url.query_pairs_mut().append_pair("id", transaction_id);
let response = self
.http_client
.get(url)
.bearer_auth(&self.api_key)
.send()
.await?;
if response.status().is_success() {
let transaction = response.json::<Transaction>().await?;
Ok(transaction)
} else {
self.handle_error(response).await
}
}
/// Refunds a transaction.
///
/// # Arguments
/// * `merchant_code` - The merchant's unique code.
/// * `transaction_id` - The transaction's unique ID.
/// * `amount` - The amount to refund (optional, defaults to full amount).
/// * `reason` - The reason for the refund.
pub async fn refund_transaction(
&self,
merchant_code: &str,
transaction_id: &str,
amount: Option<f64>,
reason: &str,
) -> Result<Transaction> {
let url = self.build_url(&format!(
"/v0.1/merchants/{}/transactions/{}/refunds",
merchant_code, transaction_id
))?;
let mut body = serde_json::Map::new();
body.insert(
"reason".to_string(),
serde_json::Value::String(reason.to_string()),
);
if let Some(amt) = amount {
body.insert(
"amount".to_string(),
serde_json::Value::Number(serde_json::Number::from_f64(amt).unwrap()),
);
}
let response = self
.http_client
.post(url)
.bearer_auth(&self.api_key)
.json(&body)
.send()
.await?;
if response.status().is_success() {
let transaction = response.json::<Transaction>().await?;
Ok(transaction)
} else {
self.handle_error(response).await
}
}
}
// --- Pagination Helpers ---
impl SumUpClient {
/// Extracts the next page URL from a transaction history response.
/// Returns `None` if there are no more pages.
///
/// # Arguments
/// * `history` - The transaction history response to extract from
///
/// # Returns
/// * `Some(url)` - The URL for the next page, if available
/// * `None` - If there are no more pages
///
/// # Examples
///
/// ```rust,no_run
/// use sumup_rs::{SumUpClient, TransactionHistoryQuery};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = SumUpClient::new("your-api-key".to_string(), true)?;
/// let query = TransactionHistoryQuery {
/// limit: Some(10),
/// order: Some("desc"),
/// newest_time: None,
/// oldest_time: None,
/// };
/// let history = client.list_transactions_history("merchant123", &query).await?;
///
/// if let Some(next_url) = SumUpClient::get_next_page_url_from_history(&history) {
/// println!("Next page available at: {}", next_url);
/// } else {
/// println!("No more pages available");
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_next_page_url_from_history(history: &TransactionHistoryResponse) -> Option<String> {
history
.links
.iter()
.find(|link| link.rel == "next")
.map(|link| link.href.clone())
}
/// Extracts the previous page URL from a transaction history response.
/// Returns `None` if there is no previous page.
///
/// # Arguments
/// * `history` - The transaction history response to extract from
///
/// # Returns
/// * `Some(url)` - The URL for the previous page, if available
/// * `None` - If there is no previous page
///
/// # Examples
///
/// ```rust,no_run
/// use sumup_rs::{SumUpClient, TransactionHistoryQuery};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = SumUpClient::new("your-api-key".to_string(), true)?;
/// let query = TransactionHistoryQuery {
/// limit: Some(10),
/// order: Some("desc"),
/// newest_time: None,
/// oldest_time: None,
/// };
/// let history = client.list_transactions_history("merchant123", &query).await?;
///
/// if let Some(prev_url) = SumUpClient::get_previous_page_url_from_history(&history) {
/// println!("Previous page available at: {}", prev_url);
/// } else {
/// println!("No previous page available");
/// }
/// # Ok(())
/// # }
/// ```
pub fn get_previous_page_url_from_history(
history: &TransactionHistoryResponse,
) -> Option<String> {
history
.links
.iter()
.find(|link| link.rel == "prev")
.map(|link| link.href.clone())
}
/// Checks if there are more pages available in a transaction history response.
///
/// # Arguments
/// * `history` - The transaction history response to check
///
/// # Returns
/// * `true` - If there are more pages available
/// * `false` - If this is the last page
///
/// # Examples
///
/// ```rust,no_run
/// use sumup_rs::{SumUpClient, TransactionHistoryQuery};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = SumUpClient::new("your-api-key".to_string(), true)?;
/// let query = TransactionHistoryQuery {
/// limit: Some(10),
/// order: Some("desc"),
/// newest_time: None,
/// oldest_time: None,
/// };
/// let history = client.list_transactions_history("merchant123", &query).await?;
///
/// if SumUpClient::has_next_page_from_history(&history) {
/// println!("More pages available");
/// } else {
/// println!("This is the last page");
/// }
/// # Ok(())
/// # }
/// ```
pub fn has_next_page_from_history(history: &TransactionHistoryResponse) -> bool {
history.links.iter().any(|link| link.rel == "next")
}
/// Fetches all transactions for a merchant by automatically handling pagination.
/// This is a convenience method that fetches all pages and combines the results.
///
/// # Arguments
/// * `merchant_code` - The merchant's unique code
/// * `order` - Sort order (e.g., "asc", "desc")
/// * `max_pages` - Maximum number of pages to fetch (None for unlimited)
///
/// # Returns
/// * `Vec<Transaction>` - All transactions from all pages
///
/// # Examples
///
/// ```rust,no_run
/// use sumup_rs::SumUpClient;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let client = SumUpClient::new("your-api-key".to_string(), true)?;
///
/// // Fetch all transactions (up to 5 pages to avoid overwhelming the API)
/// let all_transactions = client.list_all_transactions_history("merchant123", Some("desc"), Some(5)).await?;
/// println!("Fetched {} transactions", all_transactions.len());
///
/// // Fetch all transactions without page limit (use with caution)
/// let all_transactions = client.list_all_transactions_history("merchant123", Some("desc"), None).await?;
/// println!("Fetched {} transactions", all_transactions.len());
/// # Ok(())
/// # }
/// ```
pub async fn list_all_transactions_history(
&self,
merchant_code: &str,
order: Option<&str>,
max_pages: Option<usize>,
) -> Result<Vec<Transaction>> {
let mut all_transactions = Vec::new();
let mut page_count = 0;
let mut newest_time: Option<String> = None;
loop {
// Check if we've reached the maximum number of pages
if let Some(max) = max_pages {
if page_count >= max {
break;
}
}
// Fetch the current page
let history = self
.list_transactions_history(
merchant_code,
&TransactionHistoryQuery {
limit: Some(100), // Use a reasonable page size
order,
newest_time: newest_time.as_deref(),
oldest_time: None, // No oldest_time for this convenience method
},
)
.await?;
// Check if there are more pages before moving data
let has_next_page = Self::has_next_page_from_history(&history);
// Get the newest time from the last transaction for the next page
let last_transaction = history.items.last().map(|t| t.timestamp.clone());
// Add transactions from this page
all_transactions.extend(history.items);
// Update newest_time for next iteration
if let Some(timestamp) = last_transaction {
newest_time = Some(timestamp);
} else {
break;
}
// Check if we should continue
if !has_next_page {
break;
}
page_count += 1;
}
Ok(all_transactions)
}
}