maib-client 0.2.0

An unofficial Rust client for MAIB API
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
use std::sync::Arc;

use rust_decimal::Decimal;
use sha2::Digest;

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ClientId(String);

impl ClientId {
    pub fn new(value: String) -> Self {
        Self(value)
    }
}

impl core::fmt::Display for ClientId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        return write!(f, "ClientId([redacted])");
    }
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ClientSecret(String);

impl ClientSecret {
    pub fn new(value: String) -> Self {
        Self(value)
    }
}

impl core::fmt::Display for ClientSecret {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        return write!(f, "ClientSecret([redacted])");
    }
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct AccessToken(pub(crate) String);

impl AccessToken {
    pub fn new(value: String) -> Self {
        Self(value)
    }

    /// This might leak the value in logs!!!
    pub fn as_str(&self) -> &str {
        return self.0.as_str();
    }
}

impl core::fmt::Display for AccessToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        return write!(f, "AccessToken([redacted])");
    }
}

#[derive(Debug)]
pub struct AccessTokenDuration(core::time::Duration);

impl From<AccessTokenDuration> for core::time::Duration {
    fn from(value: AccessTokenDuration) -> Self {
        return value.0;
    }
}

#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct QRId(String);

impl QRId {
    pub fn new(value: String) -> Self {
        return Self(value);
    }

    pub fn as_str(&self) -> &str {
        return self.0.as_str();
    }
}

impl std::cmp::PartialEq<str> for QRId {
    fn eq(&self, other: &str) -> bool {
        return self.0.eq(other);
    }
}

impl core::fmt::Display for QRId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        return write!(f, "{}", self.0);
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct Signature(String);

impl Signature {
    pub fn new(value: String) -> Self {
        return Self(value);
    }

    pub fn as_str(&self) -> &str {
        return self.0.as_str();
    }
}

impl core::fmt::Display for Signature {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        return write!(f, "Signature([redacted])");
    }
}

/// Signature key provided by MAIB.
#[derive(Debug)]
pub struct SignatureKey(Arc<str>);

impl SignatureKey {
    pub fn as_str(&self) -> &str {
        return &self.0;
    }
}

impl From<String> for SignatureKey {
    fn from(value: String) -> Self {
        return Self(Arc::from(value));
    }
}

#[derive(Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct ExtensionId(String);

impl ExtensionId {
    pub fn new(value: String) -> Self {
        return Self(value);
    }

    pub fn as_str(&self) -> &str {
        return self.0.as_str();
    }
}

impl core::fmt::Display for ExtensionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        return write!(f, "{}", self.0);
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
pub struct PaymentId(String);

impl PaymentId {
    pub fn new(value: String) -> Self {
        return Self(value);
    }

    pub fn as_str(&self) -> &str {
        return self.0.as_str();
    }
}

impl core::fmt::Display for PaymentId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        return write!(f, "{}", self.0);
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum PaymentType {
    Fixed,
    Controlled,
    Free,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum PaymentStatus {
    Executed,
    Refunded,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
pub enum TokenType {
    Bearer,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum QRType {
    /// QR payment that can be paid
    /// more than once.
    Static,

    /// QR payment that can be paid once.
    Dynamic,

    /// QR payment can pe paid more than once.
    ///
    /// This also allows to modify amount and expiration date
    /// while is considere valid payment.
    Hybrid,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Currency {
    MDL,
}

impl Currency {
    pub fn code(self) -> &'static str {
        match self {
            Currency::MDL => "MDL",
        }
    }

    pub fn minor_currency_unit(self) -> i32 {
        match self {
            Currency::MDL => 100,
        }
    }
}

impl core::fmt::Display for Currency {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        return write!(f, "{}", self.code());
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum QRStatus {
    Active,
    Inactive,
    Expired,
    Paid,
    Cancelled,
}

impl core::fmt::Display for QRStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match *self {
            QRStatus::Active => write!(f, "Active"),
            QRStatus::Inactive => write!(f, "Inactive"),
            QRStatus::Expired => write!(f, "Expired"),
            QRStatus::Paid => write!(f, "Paid"),
            QRStatus::Cancelled => write!(f, "Cancelled"),
        }
    }
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Notification {
    pub(crate) amount: Decimal,
    pub(crate) commission: Decimal,
    pub(crate) currency: Currency,
    pub(crate) executed_at: String,
    pub(crate) extension_id: ExtensionId,
    pub(crate) order_id: Option<String>,
    pub(crate) pay_id: PaymentId,
    pub(crate) payer_iban: String,
    pub(crate) payer_name: String,
    pub(crate) qr_id: QRId,
    pub(crate) qr_status: QRStatus,
    pub(crate) reference_id: String,
    pub(crate) terminal_id: Option<String>,
}

impl Notification {
    pub fn pay_id(&self) -> &PaymentId {
        &self.pay_id
    }
}

#[derive(Debug)]
pub struct ValidSignatureNotification(pub Notification);

#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NotificationPayload {
    pub(crate) result: Notification,
    pub(crate) signature: Signature,
}

impl NotificationPayload {
    pub(crate) fn build_signature(&self, key: SignatureKey) -> Signature {
        use base64::prelude::*;

        let n = &self.result;
        let mut this_signature = format!(
            "{}:{}:{}:{}:{}",
            n.amount, n.commission, n.currency, n.executed_at, n.extension_id
        );

        if let Some(ref order_id) = n.order_id {
            this_signature = format!("{this_signature}:{order_id}");
        }

        this_signature = format!(
            "{this_signature}:{}:{}:{}:{}:{}:{}",
            n.pay_id, n.payer_iban, n.payer_name, n.qr_id, n.qr_status, n.reference_id
        );

        if let Some(ref terminal_id) = n.terminal_id {
            this_signature = format!("{this_signature}:{terminal_id}");
        }

        this_signature = format!("{this_signature}:{}", key.0);

        let sig_sha256 = sha2::Sha256::digest(&this_signature);
        let encoded = hex::encode(sig_sha256);
        let signature = Signature::new(BASE64_STANDARD.encode(encoded));

        return signature;
    }

    /// Attempt to validate signature with provided key.
    ///
    /// If it is not valid, this will return [None].
    pub fn validate_signature(self, key: SignatureKey) -> Option<ValidSignatureNotification> {
        let signature = self.build_signature(key);

        if signature.eq(&self.signature) {
            return Some(ValidSignatureNotification(self.result));
        }

        return None;
    }

    pub fn notification(&self) -> &Notification {
        &self.result
    }
}

pub mod request {
    use rust_decimal::Decimal;

    use super::{ClientId, ClientSecret, Currency, PaymentType, QRType};

    #[derive(Debug, serde::Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct GetAccessToken<'a> {
        pub client_id: &'a ClientId,
        pub client_secret: &'a ClientSecret,
    }

    #[derive(Debug, serde::Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct CreateQR<'a> {
        pub r#type: super::QRType,
        /// Date time when Dynamic QR expires.
        ///
        /// Must be a valid ISO 8601-1:2019 value.
        pub expires_at: Option<&'a str>,
        pub amount_type: super::PaymentType,

        pub amount: rust_decimal::Decimal,
        pub amount_min: Option<rust_decimal::Decimal>,
        pub amount_max: Option<rust_decimal::Decimal>,

        pub currency: super::Currency,
        pub description: String,
        pub order_id: Option<&'a str>,
        pub callback_url: String,
        pub redirect_url: String,
        pub terminal_id: Option<String>,
    }

    impl<'a> CreateQR<'a> {
        pub fn new_dynamic_with_fixed_amount(
            amount: Decimal,
            expires_at: &'a str,
            description: String,
            callback_url: String,
            redirect_url: String,
        ) -> Self {
            return CreateQR {
                r#type: QRType::Dynamic,
                expires_at: Some(expires_at),
                amount_type: PaymentType::Fixed,
                amount,
                amount_min: None,
                amount_max: None,
                currency: Currency::MDL,
                description,
                order_id: None,
                callback_url,
                redirect_url,
                terminal_id: None,
            };
        }
    }

    #[derive(Debug, serde::Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct CancelQR {
        pub reason: String,
    }

    #[derive(Debug, serde::Serialize)]
    #[serde(rename_all = "camelCase")]
    pub struct RefundPayment {
        pub reason: String,
    }
}

pub mod response {
    use chrono::{DateTime, Utc};
    use rust_decimal::Decimal;

    use super::{Currency, ExtensionId, PaymentId, PaymentStatus, QRId};

    #[derive(Debug, serde::Deserialize)]
    pub struct ApiResponse<R> {
        pub(crate) result: Option<R>,
        pub(crate) errors: Option<Vec<crate::error::ApiError>>,
    }

    impl<R> From<ApiResponse<R>> for core::result::Result<R, crate::error::Error> {
        fn from(value: ApiResponse<R>) -> Self {
            if let Some(value) = value.result {
                return Ok(value);
            }

            if let Some(value) = value.errors {
                return Err(crate::error::Error::Api(value));
            }

            panic!();
        }
    }

    #[derive(Debug, serde::Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct AuthToken {
        access_token: super::AccessToken,
        expires_in: u64,
        token_type: super::TokenType,
    }

    impl AuthToken {
        /// Access token lifetime in seconds.
        pub fn expires_in(&self) -> super::AccessTokenDuration {
            return super::AccessTokenDuration(core::time::Duration::from_secs(self.expires_in));
        }

        pub fn access_token(&self) -> &super::AccessToken {
            &self.access_token
        }

        pub fn take_access_token(self) -> super::AccessToken {
            self.access_token
        }

        pub fn token_type(&self) -> super::TokenType {
            self.token_type
        }
    }

    #[derive(Debug, serde::Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct CreateQRResponse {
        pub qr_id: super::QRId,
        pub order_id: Option<String>,
        pub r#type: super::QRType,
        pub url: String,
        pub expires_at: String,
    }

    #[derive(Debug, serde::Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct GetQRDetails {
        pub qr_id: super::QRId,
        pub order_id: Option<String>,
        pub status: super::QRStatus,
        pub r#type: super::QRType,
        pub url: String,
        pub amount_type: super::PaymentType,
        pub currency: super::Currency,
        pub amount: Decimal,
        pub amount_min: Option<Decimal>,
        pub amount_max: Option<Decimal>,
        pub description: String,
        pub callback_url: String,
        pub redirect_url: String,
        pub terminal_id: String,
        pub created_at: DateTime<Utc>,
        pub updated_at: DateTime<Utc>,
        pub expires_at: DateTime<Utc>,
    }

    #[derive(Debug, serde::Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct CancelQR {
        pub qr_id: super::QRId,
        pub status: super::QRStatus,
    }

    #[derive(Debug, serde::Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct PaymentDetails {
        pub pay_id: PaymentId,
        pub reference_id: String,
        pub qr_id: QRId,
        pub extension_id: Option<ExtensionId>,
        pub order_id: Option<String>,
        pub amount: Decimal,
        pub commission: Decimal,
        pub currency: Currency,
        pub description: String,
        pub payer_name: String,
        pub payer_iban: String,
        pub status: PaymentStatus,
        pub executed_at: String,
        pub refunded_at: Option<String>,
        pub terminal_id: Option<String>,
    }

    #[derive(Debug, serde::Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct RefundPayment {
        pub pay_id: PaymentId,
        pub status: PaymentStatus,
    }
}