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
use std::collections::HashMap;

use crate::client::ApiClient;
use crate::common::{advanced_headers, PaymentId};
use crate::error::{ApiResult, Error};
use crate::models::payment::{NewPayment, Payment};

pub struct PaymentServiceImpl {
    client: ApiClient,
}

impl PaymentServiceImpl {
    const BASE_PATH: &'static str = "/payments";

    pub fn new(client: ApiClient) -> Self {
        Self { client }
    }
}

pub trait PaymentService {
    fn find_one(&self, payment_id: PaymentId) -> ApiResult<Payment>;

    fn create(&self, params: NewPayment, idempotency_key: Option<String>) -> ApiResult<Payment>;

    fn capture(&self, payment_id: PaymentId, idempotency_key: Option<String>)
        -> ApiResult<Payment>;

    fn cancel(&self, payment_id: PaymentId, idempotency_key: Option<String>) -> ApiResult<Payment>;

    fn list(&self) -> ApiResult<()>;
}

impl PaymentService for PaymentServiceImpl {
    fn find_one(&self, payment_id: PaymentId) -> ApiResult<Payment> {
        let request_path = format!("{}/{}", Self::BASE_PATH, payment_id);
        self.client.get(request_path.as_str())
    }

    fn create(&self, params: NewPayment, idempotency_key: Option<String>) -> ApiResult<Payment> {
        let advanced_headers: Option<HashMap<&'static str, String>> =
            advanced_headers(idempotency_key).into();

        self.client
            .post_form(Self::BASE_PATH, params, advanced_headers)
    }

    fn capture(
        &self,
        payment_id: PaymentId,
        idempotency_key: Option<String>,
    ) -> ApiResult<Payment> {
        let advanced_headers: Option<HashMap<&'static str, String>> =
            advanced_headers(idempotency_key).into();
        let url = format!("{}/{}/capture", Self::BASE_PATH, payment_id);
        self.client.post(&url, advanced_headers)
    }

    fn cancel(&self, payment_id: PaymentId, idempotency_key: Option<String>) -> ApiResult<Payment> {
        let advanced_headers: Option<HashMap<&'static str, String>> =
            advanced_headers(idempotency_key).into();
        let url = format!("{}/{}/cancel", Self::BASE_PATH, payment_id);
        self.client.post(&url, advanced_headers)
    }

    fn list(&self) -> ApiResult<()> {
        Err(Error::Unsupported("list payments not supported"))
    }
}