glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Stripe's API, through `glacier::client`: in tests, stub
//! `https://api.stripe.com/v1/…`.

use serde_json::Value as Json;

use super::{Checkout, CheckoutSession, Pending, Processor, checkout_params};
use crate::client::Client;
use crate::error::Error;

/// Stripe, with a secret key.
pub struct Stripe {
    client: Client,
}

impl Stripe {
    pub fn new(secret_key: &str) -> Self {
        Self::at("https://api.stripe.com/v1", secret_key)
    }

    /// Stripe's API at another address: a local stand-in.
    pub fn at(base: &str, secret_key: &str) -> Self {
        Self {
            client: Client::new(base).bearer(secret_key).retries(2),
        }
    }
}

impl Processor for Stripe {
    fn create_customer<'a>(&'a self, email: &'a str) -> Pending<'a, String> {
        Box::pin(async move {
            let customer: Json = self
                .client
                .post("customers")
                .form(&[("email", email)])
                .send()
                .await?
                .json()?;
            id(&customer)
        })
    }

    fn create_checkout<'a>(
        &'a self,
        customer: &'a str,
        checkout: &'a Checkout,
    ) -> Pending<'a, CheckoutSession> {
        Box::pin(async move {
            let session: Json = self
                .client
                .post("checkout/sessions")
                .form(&checkout_params(customer, checkout))
                .send()
                .await?
                .json()?;
            Ok(CheckoutSession {
                id: id(&session)?,
                url: session["url"].as_str().unwrap_or_default().to_owned(),
            })
        })
    }

    fn checkout_session<'a>(&'a self, id: &'a str) -> Pending<'a, Json> {
        Box::pin(async move {
            self.client
                .get(format!("checkout/sessions/{id}"))
                .query(&[
                    ("expand[]", "subscription"),
                    ("expand[]", "payment_intent.latest_charge"),
                ])
                .send()
                .await?
                .json()
        })
    }

    fn subscription<'a>(&'a self, id: &'a str) -> Pending<'a, Json> {
        Box::pin(async move {
            self.client
                .get(format!("subscriptions/{id}"))
                .send()
                .await?
                .json()
        })
    }

    fn charge<'a>(&'a self, id: &'a str) -> Pending<'a, Json> {
        Box::pin(async move {
            self.client
                .get(format!("charges/{id}"))
                .send()
                .await?
                .json()
        })
    }
}

fn id(object: &Json) -> crate::Result<String> {
    object["id"]
        .as_str()
        .map(str::to_owned)
        .ok_or_else(|| Error::internal("Stripe's answer had no id"))
}