Skip to main content

fauna_api/
payments.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::json;
4
5use crate::authentification::{Credentials, CredentialsOrApiKey};
6use crate::billing::{RedirectUrl, ReturnOptions};
7use crate::error::Result;
8use crate::http::{client, encode, ok};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum PaymentStatus {
13    Pending,
14    Succeeded,
15    Expired,
16    Refunded,
17    Disputed,
18}
19
20/// A payment to a person through their payout account. Amounts are in dollars.
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct Payment {
23    pub id: String,
24    pub status: PaymentStatus,
25    pub amount: f64,
26    /// Fauna's fee, taken from what the payee receives.
27    pub fee: f64,
28    pub refunded: f64,
29    pub currency: String,
30    /// The payee's email.
31    pub payee: String,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub payer: Option<String>,
34    /// Your own label, to find the payment again.
35    pub reference: String,
36    pub description: String,
37    pub created: DateTime<Utc>,
38    /// Where the payer pays. Only returned by `create`.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub url: Option<String>,
41}
42
43/// What `create` needs. `amount` is in dollars; usd is the only currency for now.
44#[derive(Debug, Clone, Default, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct PaymentRequest {
47    /// Email of the Fauna account that gets paid.
48    pub payee: String,
49    pub amount: f64,
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub payer: Option<String>,
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub currency: Option<String>,
54    #[serde(default, skip_serializing_if = "Option::is_none")]
55    pub description: Option<String>,
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub reference: Option<String>,
58    /// Where Checkout sends the payer back, with ?payment=paid or ?payment=cancelled.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub return_url: Option<String>,
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub cancel_url: Option<String>,
63}
64
65/// Whether you can be paid. Payments need `charges_enabled`.
66#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
67#[serde(rename_all = "camelCase")]
68pub struct Payouts {
69    pub connected: bool,
70    pub charges_enabled: bool,
71    pub payouts_enabled: bool,
72    pub details_submitted: bool,
73}
74
75/// What a payment of `amount` costs: Fauna's fee and what the payee receives.
76#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
77pub struct Quote {
78    pub amount: f64,
79    pub fee: f64,
80    pub payout: f64,
81}
82
83/// The `{ reference }` filter of `list`.
84#[derive(Debug, Clone, Default)]
85pub struct PaymentQuery {
86    pub reference: Option<String>,
87}
88
89/// Start or continue setting up payouts. Open the returned URL; Stripe sends you
90/// back with ?payouts=connected.
91pub async fn connect(credentials: &Credentials, options: &ReturnOptions) -> Result<RedirectUrl> {
92    let response = client()
93        .post(format!("{}/payments/payouts/connect", crate::get_url()))
94        .header("Authorization", format!("Token {}", credentials.token))
95        .json(&json!({ "returnUrl": options.return_url }))
96        .send()
97        .await?;
98    Ok(ok(response).await?.json().await?)
99}
100
101pub async fn payouts(credentials: &Credentials) -> Result<Payouts> {
102    let response = client()
103        .get(format!("{}/payments/payouts", crate::get_url()))
104        .header("Authorization", format!("Token {}", credentials.token))
105        .send()
106        .await?;
107    Ok(ok(response).await?.json().await?)
108}
109
110/// A link into your payouts dashboard: balance, payouts and bank details.
111pub async fn dashboard(credentials: &Credentials) -> Result<RedirectUrl> {
112    let response = client()
113        .post(format!("{}/payments/payouts/dashboard", crate::get_url()))
114        .header("Authorization", format!("Token {}", credentials.token))
115        .send()
116        .await?;
117    Ok(ok(response).await?.json().await?)
118}
119
120pub async fn quote(authorization: &CredentialsOrApiKey, amount: f64) -> Result<Quote> {
121    let response = client()
122        .get(format!("{}/payments/quote", crate::get_url()))
123        .query(&[("amount", amount.to_string())])
124        .header(
125            "Authorization",
126            match authorization {
127                CredentialsOrApiKey::Credentials(credentials) => {
128                    format!("Token {}", credentials.token)
129                }
130                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
131            },
132        )
133        .send()
134        .await?;
135    Ok(ok(response).await?.json().await?)
136}
137
138/// Ask for a payment to `payee`. Send the payer to the returned `url`. With an API
139/// key, that key's webhooks hear `payment.succeeded`, `payment.expired`,
140/// `payment.refunded` and `payment.disputed`.
141pub async fn create(
142    authorization: &CredentialsOrApiKey,
143    request: &PaymentRequest,
144) -> Result<Payment> {
145    let response = client()
146        .post(format!("{}/payments", crate::get_url()))
147        .header(
148            "Authorization",
149            match authorization {
150                CredentialsOrApiKey::Credentials(credentials) => {
151                    format!("Token {}", credentials.token)
152                }
153                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
154            },
155        )
156        .json(request)
157        .send()
158        .await?;
159    Ok(ok(response).await?.json().await?)
160}
161
162/// A payment you made, paid or are paid by.
163pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Payment> {
164    let response = client()
165        .get(format!("{}/payments/{}", crate::get_url(), encode(id)))
166        .header(
167            "Authorization",
168            match authorization {
169                CredentialsOrApiKey::Credentials(credentials) => {
170                    format!("Token {}", credentials.token)
171                }
172                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
173            },
174        )
175        .send()
176        .await?;
177    Ok(ok(response).await?.json().await?)
178}
179
180/// Payments you asked for, newest first, optionally those with one reference.
181pub async fn list(
182    authorization: &CredentialsOrApiKey,
183    query: &PaymentQuery,
184) -> Result<Vec<Payment>> {
185    let mut request = client()
186        .get(format!("{}/payments", crate::get_url()))
187        .header(
188            "Authorization",
189            match authorization {
190                CredentialsOrApiKey::Credentials(credentials) => {
191                    format!("Token {}", credentials.token)
192                }
193                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
194            },
195        );
196    if let Some(reference) = &query.reference {
197        request = request.query(&[("reference", reference)]);
198    }
199    let response = request.send().await?;
200    Ok(ok(response).await?.json().await?)
201}
202
203/// Refund a completed payment in full, Fauna's fee included. Whoever made it, or
204/// its payee, can.
205pub async fn refund(authorization: &CredentialsOrApiKey, id: &str) -> Result<Payment> {
206    let response = client()
207        .post(format!(
208            "{}/payments/{}/refund",
209            crate::get_url(),
210            encode(id)
211        ))
212        .header(
213            "Authorization",
214            match authorization {
215                CredentialsOrApiKey::Credentials(credentials) => {
216                    format!("Token {}", credentials.token)
217                }
218                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
219            },
220        )
221        .send()
222        .await?;
223    Ok(ok(response).await?.json().await?)
224}