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