fauna-api 1.0.814

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::authentification::{Credentials, CredentialsOrApiKey};
use crate::billing::{RedirectUrl, ReturnOptions};
use crate::error::Result;
use crate::http::{client, encode, ok};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PaymentStatus {
    Pending,
    Succeeded,
    Expired,
    Refunded,
    Disputed,
}

/// A payment to a person through their payout account. Amounts are in dollars.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payment {
    pub id: String,
    pub status: PaymentStatus,
    pub amount: f64,
    /// The whole fee, taken from what the payee receives: the card cost, Fauna's cut and the
    /// app's fee.
    pub fee: f64,
    /// The app's part of `fee`, paid to the account that owns the API key that asked for the
    /// payment.
    pub app_fee: f64,
    pub refunded: f64,
    pub currency: String,
    /// The payee's email.
    pub payee: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payer: Option<String>,
    /// Your own label, to find the payment again.
    pub reference: String,
    pub description: String,
    pub created: DateTime<Utc>,
    /// Where the payer pays. Only returned by `create`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

/// What `create` needs. `amount` is in dollars; usd is the only currency for now.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentRequest {
    /// Email of the Fauna account that gets paid.
    pub payee: String,
    pub amount: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub payer: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,
    /// The app's own fee, a percent of the amount (at most 30), paid to the account that owns
    /// the API key once the payment succeeds. Only an API key can ask for one, and its account
    /// needs payouts set up.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_fee: Option<f64>,
    /// Where Checkout sends the payer back, with ?payment=paid or ?payment=cancelled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cancel_url: Option<String>,
}

/// Whether you can be paid. Payments need `charges_enabled`.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payouts {
    pub connected: bool,
    pub charges_enabled: bool,
    pub payouts_enabled: bool,
    pub details_submitted: bool,
}

/// What a payment of `amount` costs: the whole fee, the app's part of it and what the payee
/// receives.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Quote {
    pub amount: f64,
    pub fee: f64,
    pub app_fee: f64,
    pub payout: f64,
}

/// The `{ reference }` filter of `list`.
#[derive(Debug, Clone, Default)]
pub struct PaymentQuery {
    pub reference: Option<String>,
}

/// The `{ appFee }` options of `quote`.
#[derive(Debug, Clone, Copy, Default)]
pub struct QuoteOptions {
    pub app_fee: Option<f64>,
}

/// Start or continue setting up payouts. Open the returned URL; Stripe sends you
/// back with ?payouts=connected.
pub async fn connect(credentials: &Credentials, options: &ReturnOptions) -> Result<RedirectUrl> {
    let response = client()
        .post(format!("{}/payments/payouts/connect", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .json(&json!({ "returnUrl": options.return_url }))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

pub async fn payouts(credentials: &Credentials) -> Result<Payouts> {
    let response = client()
        .get(format!("{}/payments/payouts", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// A link into your payouts dashboard: balance, payouts and bank details.
pub async fn dashboard(credentials: &Credentials) -> Result<RedirectUrl> {
    let response = client()
        .post(format!("{}/payments/payouts/dashboard", crate::get_url()))
        .header("Authorization", format!("Token {}", credentials.token))
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// What a payment of `amount` would cost, with the app's fee (`app_fee`, a percent) when an
/// API key asks for one.
pub async fn quote(
    authorization: &CredentialsOrApiKey,
    amount: f64,
    options: &QuoteOptions,
) -> Result<Quote> {
    let mut query = vec![("amount", amount.to_string())];
    if let Some(app_fee) = options.app_fee {
        query.push(("appFee", app_fee.to_string()));
    }
    let response = client()
        .get(format!("{}/payments/quote", crate::get_url()))
        .query(&query)
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Ask for a payment to `payee`. Send the payer to the returned `url`. With an API
/// key, that key's webhooks hear `payment.succeeded`, `payment.expired`,
/// `payment.refunded` and `payment.disputed`.
pub async fn create(
    authorization: &CredentialsOrApiKey,
    request: &PaymentRequest,
) -> Result<Payment> {
    let response = client()
        .post(format!("{}/payments", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .json(request)
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// A payment you made, paid or are paid by.
pub async fn get(authorization: &CredentialsOrApiKey, id: &str) -> Result<Payment> {
    let response = client()
        .get(format!("{}/payments/{}", crate::get_url(), encode(id)))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}

/// Payments you asked for, newest first, optionally those with one reference.
pub async fn list(
    authorization: &CredentialsOrApiKey,
    query: &PaymentQuery,
) -> Result<Vec<Payment>> {
    let mut request = client()
        .get(format!("{}/payments", crate::get_url()))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        );
    if let Some(reference) = &query.reference {
        request = request.query(&[("reference", reference)]);
    }
    let response = request.send().await?;
    Ok(ok(response).await?.json().await?)
}

/// Refund a completed payment in full. The payee gets back the whole fee except Stripe's own
/// fee on the charge, the app's fee included. Whoever made it, or its payee, can.
pub async fn refund(authorization: &CredentialsOrApiKey, id: &str) -> Result<Payment> {
    let response = client()
        .post(format!(
            "{}/payments/{}/refund",
            crate::get_url(),
            encode(id)
        ))
        .header(
            "Authorization",
            match authorization {
                CredentialsOrApiKey::Credentials(credentials) => {
                    format!("Token {}", credentials.token)
                }
                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
            },
        )
        .send()
        .await?;
    Ok(ok(response).await?.json().await?)
}