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
use crate::error::{self, Error};
use reqwest::header::{AUTHORIZATION, USER_AGENT};

#[cfg(not(feature = "async"))]
use reqwest::{
    Client as HttpClient,
    multipart::Form,
};

#[cfg(feature = "async")]
use reqwest::{
    r#async::Client as HttpClient,
    multipart::Form
};

#[cfg(feature = "async")]
use futures::{
    future::Future,
    stream::Stream
};

#[cfg(feature = "async")]
use std::{
    io::{self, Cursor}
};

use reqwest::Method;

use crate::resources::common::path::{UrlPath};
use crate::{Result};

#[derive(Clone)]
pub struct Client {
    key: String,
    account: Option<String>,
    idempotency: Option<String>,
}

impl Default for Client {
    fn default() -> Self {
        Client {
            key: String::new(),
            account: None,
            idempotency: None,
        }
    }
}

impl Client {
    pub fn new<S: AsRef<str>>(api_key: S) -> Client {
        let mut client = Client::default();
        client.stripe_key(api_key);
        client
    }

    pub fn stripe_key<S: AsRef<str>>(&mut self, key: S) {
        self.key = key.as_ref().into();
    }

    pub fn stripe_account(&mut self, acct: &str) {
        self.account = Some(acct.to_string());
    }

    pub fn idempotency(&mut self, key: &str) {
        self.idempotency = Some(key.to_string());
    }

    pub fn get<A, B>(&self, path: UrlPath, param: Vec<&str>, data: B) -> Result<A>
    where
        A: serde::de::DeserializeOwned + Send + 'static,
        B: serde::Serialize,
    {
        self.request(Method::GET, path, param, data, None)
    }

    pub fn post<A, B>(&self, path: UrlPath, param: Vec<&str>, data: B) -> Result<A>
    where
        A: serde::de::DeserializeOwned + Send + 'static,
        B: serde::Serialize,
    {
        self.request(Method::POST, path, param, data, None)
    }

    pub fn delete<A, B>(&self, path: UrlPath, param: Vec<&str>, data: B) -> Result<A>
    where
        A: serde::de::DeserializeOwned + Send + 'static,
        B: serde::Serialize,
    {
        self.request(Method::DELETE, path, param, data, None)
    }

    #[cfg(not(feature = "async"))]
    pub fn upload<A, B>(&self, path: UrlPath, param: Vec<&str>, data: B, form: Form) -> Result<A>
    where
        A: serde::de::DeserializeOwned + Send + 'static,
        B: serde::Serialize,
    {
        self.request(Method::POST, path, param, data, Some(form))
    }

    #[cfg(not(feature = "async"))]
    pub fn request<A, B>(
        &self,
        method: Method,
        path: UrlPath,
        param: Vec<&str>,
        data: B,
        form: Option<Form>,
    ) -> Result<A>
    where
        A: serde::de::DeserializeOwned + Send + 'static,
        B: serde::Serialize,
    {
        let mut param = param
                .iter()
                .map(|s| s.to_string())
                .collect::<Vec<String>>()
                .join("/");

        if param.len() > 0 {
            param = format!("/{}", param);
        }

        let uri = match path {
            UrlPath::File(true) => format!("https://files.stripe.com/v1{}{}", path, param),
            _ => format!("https://api.stripe.com/v1{}{}", path, param),
        };

        let client = HttpClient::new();
        let query = serde_qs::to_string(&data)?;
        let mut req = client
            .request(method, &uri)
            .body(query)
            .header(AUTHORIZATION, format!("Bearer {}", self.key))
            .header(USER_AGENT, "libstripe-rs/(crates.io/crates/libstripe)");

        if let Some(account) = self.account.clone() {
            req = req.header("Stripe-Account", account);
        }

        if let Some(idemp) = self.idempotency.clone() {
            req = req.header("Idempotency-Key", idemp);
        }

        if let Some(multipart) = form {
            req = req.multipart(multipart);
        }

        req.send().map_err(Error::from).and_then(|mut res| {
            if res.status().is_success() {
                res.json().map_err(Error::from)
            } else {
                let err: error::StripeErrorObject =
                    res.json().map_err(|e| error::StripeErrorObject {
                        error: error::StripeRequestObject {
                            error_type: error::ErrorType::Unknown,
                            message: Some(format!("{}", e)),
                            ..Default::default()
                        },
                    })?;
                Err(Error::from(err))
            }
        })
    }

    #[cfg(feature = "async")]
    pub fn request<A, B>(
        &self,
        method: Method,
        path: UrlPath,
        param: Vec<&str>,
        data: B,
        _form: Option<Form>,
    ) -> Result<A>
        where
            A: serde::de::DeserializeOwned + Send + 'static,
            B: serde::Serialize,
    {
        let mut param = param
            .iter()
            .map(|s| s.to_string())
            .collect::<Vec<String>>()
            .join("/");

        if param.len() > 0 {
            param = format!("/{}", param);
        }

        let uri = match path {
            UrlPath::File(true) => format!("https://files.stripe.com/v1{}{}", path, param),
            _ => format!("https://api.stripe.com/v1{}{}", path, param),
        };

        let client = HttpClient::new();
        let query = serde_qs::to_string(&data).unwrap_or_default();
        let mut req = client
            .request(method, &uri)
            .body(query)
            .header(AUTHORIZATION, format!("Bearer {}", self.key))
            .header(USER_AGENT, "libstripe-rs/(crates.io/crates/libstripe)");

        if let Some(account) = self.account.clone() {
            req = req.header("Stripe-Account", account);
        }

        if let Some(idemp) = self.idempotency.clone() {
            req = req.header("Idempotency-Key", idemp);
        }

        Box::new(req.send().map_err(Error::from).and_then(|res| {
            let status = res.status();

            res.into_body().concat2().map_err(Error::from).and_then(move |body| {
                let mut body = Cursor::new(body);
                let mut buffer = Vec::new();

                io::copy(&mut body, &mut buffer)?;

                if status.is_success() {
                    serde_json::from_slice(&buffer).map_err(Error::from)
                } else {
                    let err: error::StripeErrorObject =
                        serde_json::from_slice(&buffer).unwrap_or_else(|e| error::StripeErrorObject {
                            error: error::StripeRequestObject {
                                error_type: error::ErrorType::Unknown,
                                message: Some(format!("{}", e)),
                                ..Default::default()
                            },
                        });
                    Err(Error::from(err))
                }
            })
        }))
    }
}