use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use renox::Config;
use renox::axum::http::HeaderMap;
use renox::prelude::*;
use crate::payment::{
ChargeRequest, DisputeUpdate, PaymentPage, PaymentState, PaymentUpdate, Refund, RefundResult,
RefundUpdate,
};
use crate::{BillingPayment, Owner, Plan, Subscription, SubscriptionStatus, Unsupported};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub trait Gateway: Send + Sync + 'static {
fn name(&self) -> &str;
fn label(&self) -> &str;
fn configured(&self, config: &Config) -> bool;
fn prorates(&self) -> bool {
false
}
fn resumes(&self) -> bool {
false
}
fn pauses(&self) -> bool {
false
}
fn create_customer<'a>(
&'a self,
state: &'a AppState,
owner: &'a Owner,
) -> BoxFuture<'a, Result<String>>;
fn checkout<'a>(
&'a self,
state: &'a AppState,
request: &'a CheckoutRequest,
) -> BoxFuture<'a, Result<Checkout>>;
fn swap<'a>(
&'a self,
state: &'a AppState,
subscription: &'a Subscription,
plan: &'a Plan,
prorate: bool,
) -> BoxFuture<'a, Result<Remote>>;
fn cancel<'a>(
&'a self,
state: &'a AppState,
subscription: &'a Subscription,
at_period_end: bool,
) -> BoxFuture<'a, Result<Remote>>;
fn resume<'a>(
&'a self,
_state: &'a AppState,
_subscription: &'a Subscription,
) -> BoxFuture<'a, Result<Remote>> {
let label = self.label().to_owned();
Box::pin(async move {
Err(Error::BadRequest(format!(
"{label} can't resume a canceled subscription: subscribe again"
)))
})
}
fn pause<'a>(
&'a self,
_state: &'a AppState,
_subscription: &'a Subscription,
_resumes_at: Option<DateTime>,
) -> BoxFuture<'a, Result<Remote>> {
let label = self.label().to_owned();
Box::pin(async move {
Err(Error::BadRequest(format!(
"{label} can't pause a subscription: cancel it instead"
)))
})
}
fn unpause<'a>(
&'a self,
_state: &'a AppState,
_subscription: &'a Subscription,
) -> BoxFuture<'a, Result<Remote>> {
let label = self.label().to_owned();
Box::pin(async move {
Err(Error::BadRequest(format!(
"{label} can't pause a subscription, so there is nothing to take up again"
)))
})
}
fn verify_webhook(&self, config: &Config, headers: &HeaderMap, body: &[u8]) -> Result;
fn verify_webhook_with(&self, state: &AppState, headers: &HeaderMap, body: &[u8]) -> Result {
self.verify_webhook(&state.config, headers, body)
}
fn has_account(&self, _state: &AppState, _account: &str) -> bool {
false
}
fn verify_webhook_account(
&self,
state: &AppState,
_account: Option<&str>,
headers: &HeaderMap,
body: &[u8],
) -> Result {
self.verify_webhook_with(state, headers, body)
}
fn parse_webhook_account(
&self,
state: &AppState,
_account: Option<&str>,
body: &[u8],
) -> Result<Vec<Notice>> {
self.parse_webhook_with(state, body)
}
fn webhook_event_id(&self, headers: &HeaderMap, body: &[u8]) -> Result<String> {
if let Some(id) = headers
.get("webhook-id")
.and_then(|v| v.to_str().ok())
.filter(|id| !id.trim().is_empty())
{
return Ok(id.trim().to_owned());
}
let json: renox::serde_json::Value = renox::serde_json::from_slice(body)
.map_err(|err| Error::BadRequest(format!("the webhook isn't JSON: {err}")))?;
Ok(match json.get("id").and_then(|id| id.as_str()) {
Some(id) if !id.is_empty() => id.to_owned(),
_ => format!("sha256:{}", renox::webhook::sha256_hex(body)),
})
}
fn parse_webhook(&self, body: &[u8]) -> Result<Vec<Notice>>;
fn parse_webhook_with(&self, _state: &AppState, body: &[u8]) -> Result<Vec<Notice>> {
self.parse_webhook(body)
}
fn charge<'a>(
&'a self,
_state: &'a AppState,
_request: &'a ChargeRequest,
) -> BoxFuture<'a, Result<PaymentPage>> {
unsupported(self.name(), "charge")
}
fn payment_link<'a>(
&'a self,
_state: &'a AppState,
_request: &'a ChargeRequest,
) -> BoxFuture<'a, Result<PaymentPage>> {
unsupported(self.name(), "payment_link")
}
fn refund<'a>(
&'a self,
_state: &'a AppState,
_payment: &'a BillingPayment,
_refund: &'a Refund,
) -> BoxFuture<'a, Result<RefundResult>> {
unsupported(self.name(), "refund")
}
fn payment_status<'a>(
&'a self,
_state: &'a AppState,
_payment: &'a BillingPayment,
) -> BoxFuture<'a, Result<PaymentState>> {
unsupported(self.name(), "payment_status")
}
fn accept_dispute<'a>(
&'a self,
_state: &'a AppState,
_payment: &'a BillingPayment,
) -> BoxFuture<'a, Result> {
unsupported(self.name(), "accept_dispute")
}
}
pub(crate) fn unsupported<'a, T: Send + 'a>(
gateway: &str,
operation: &str,
) -> BoxFuture<'a, Result<T>> {
let refusal = Unsupported::new(gateway, operation);
Box::pin(async move { Err(refusal.into()) })
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CheckoutRequest {
pub owner: Owner,
pub customer_id: String,
pub name: String,
pub plan: Plan,
pub price_id: Option<String>,
pub trial_ends_at: Option<DateTime>,
pub success_url: String,
pub cancel_url: String,
}
impl CheckoutRequest {
pub fn metadata(&self) -> Vec<(&'static str, String)> {
vec![
("renox_billable", self.owner.key()),
("renox_name", self.name.clone()),
("renox_plan", self.plan.key.clone()),
]
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Checkout {
pub url: String,
}
impl Checkout {
pub fn redirect(url: impl Into<String>) -> Self {
Self { url: url.into() }
}
}
#[derive(Debug, Clone, Default)]
pub struct Remote {
pub(crate) id: String,
pub(crate) customer_id: Option<String>,
pub(crate) status: Option<SubscriptionStatus>,
pub(crate) plan: Option<String>,
pub(crate) price_id: Option<String>,
pub(crate) owner: Option<String>,
pub(crate) name: Option<String>,
pub(crate) trial_ends_at: Option<Option<DateTime>>,
pub(crate) current_period_end: Option<Option<DateTime>>,
pub(crate) ends_at: Option<Option<DateTime>>,
pub(crate) at: Option<i64>,
}
impl Remote {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
..Self::default()
}
}
pub fn id(&self) -> &str {
&self.id
}
pub fn customer(mut self, id: impl Into<String>) -> Self {
self.customer_id = Some(id.into());
self
}
pub fn status(mut self, status: SubscriptionStatus) -> Self {
self.status = Some(status);
self
}
pub fn plan(mut self, key: impl Into<String>) -> Self {
self.plan = Some(key.into());
self
}
pub fn price_id(mut self, id: impl Into<String>) -> Self {
self.price_id = Some(id.into());
self
}
pub fn owner(mut self, key: impl Into<String>) -> Self {
self.owner = Some(key.into());
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn trial_ends_at(mut self, at: Option<DateTime>) -> Self {
self.trial_ends_at = Some(at);
self
}
pub fn current_period_end(mut self, at: Option<DateTime>) -> Self {
self.current_period_end = Some(at);
self
}
pub fn ends_at(mut self, at: Option<DateTime>) -> Self {
self.ends_at = Some(at);
self
}
pub fn at(mut self, unix_seconds: i64) -> Self {
self.at = Some(unix_seconds);
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Payment {
pub id: String,
pub subscription_id: Option<String>,
pub customer_id: Option<String>,
pub amount: i64,
pub currency: String,
pub succeeded: bool,
}
impl Payment {
pub fn new(id: impl Into<String>, amount: i64, currency: &str, succeeded: bool) -> Self {
Self {
id: id.into(),
subscription_id: None,
customer_id: None,
amount,
currency: currency.to_ascii_uppercase(),
succeeded,
}
}
pub fn subscription(mut self, id: impl Into<String>) -> Self {
self.subscription_id = Some(id.into());
self
}
pub fn customer(mut self, id: impl Into<String>) -> Self {
self.customer_id = Some(id.into());
self
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Notice {
Subscription(Remote),
Payment(Payment),
OneOff(PaymentUpdate),
Refund(RefundUpdate),
Dispute(DisputeUpdate),
}
pub(crate) const DEFAULT_ACCOUNT: &str = "default";
pub(crate) fn account_suffix(account: &str) -> Option<String> {
let valid = !account.is_empty()
&& account.len() <= 64
&& account
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
valid.then(|| account.to_ascii_uppercase().replace('-', "_"))
}
pub(crate) type Resolver =
Arc<dyn Fn(&AppState, &str) -> BoxFuture<'static, Result<Option<String>>> + Send + Sync>;
#[derive(Clone)]
pub(crate) enum Secret {
Given(String),
Config(&'static str),
Resolved(Resolver),
}
impl Secret {
pub(crate) fn resolved<F, Fut>(resolver: F) -> Self
where
F: Fn(&AppState) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Option<String>>> + Send + 'static,
{
Self::Resolved(Arc::new(move |state, _account| Box::pin(resolver(state))))
}
pub(crate) fn resolved_accounts<F, Fut>(resolver: F) -> Self
where
F: Fn(&AppState, &str) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Option<String>>> + Send + 'static,
{
Self::Resolved(Arc::new(move |state, account| {
Box::pin(resolver(state, account))
}))
}
pub(crate) fn resolve(&self, config: &Config) -> Option<String> {
match self {
Self::Given(value) => Some(value.clone()).filter(|v| !v.is_empty()),
Self::Config(name) => config.var(name),
Self::Resolved(_) => None,
}
}
pub(crate) fn resolve_account(&self, config: &Config, account: Option<&str>) -> Option<String> {
let Some(account) = account else {
return self.resolve(config);
};
match self {
Self::Config(name) => config
.var(&format!("{name}_{}", account_suffix(account)?))
.filter(|v| !v.is_empty()),
_ => None,
}
}
pub(crate) fn is_set(&self, config: &Config) -> bool {
matches!(self, Self::Resolved(_)) || self.resolve(config).is_some()
}
pub(crate) fn require(&self, config: &Config, what: &str) -> Result<String> {
self.resolve(config).ok_or_else(|| self.missing(what))
}
pub(crate) async fn require_async(&self, state: &AppState, what: &str) -> Result<String> {
match self {
Self::Resolved(resolver) => resolver(state, DEFAULT_ACCOUNT)
.await?
.filter(|key| !key.is_empty())
.ok_or_else(|| self.missing(what)),
_ => self.require(&state.config, what),
}
}
pub(crate) async fn require_account(
&self,
state: &AppState,
account: Option<&str>,
what: &str,
) -> Result<String> {
let Some(name) = account else {
return self.require_async(state, what).await;
};
match self {
Self::Resolved(resolver) => resolver(state, name)
.await?
.filter(|key| !key.is_empty())
.ok_or_else(|| self.missing(what)),
_ => self
.resolve_account(&state.config, account)
.ok_or_else(|| self.missing(what)),
}
}
fn missing(&self, what: &str) -> Error {
let hint = match self {
Self::Config(name) => format!("set {name} in .env"),
Self::Given(_) => "it was given empty".into(),
Self::Resolved(_) => "the key resolver answered none".into(),
};
renox::anyhow::anyhow!("{what} is missing: {hint}").into()
}
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Given(_) | Self::Resolved(_) => f.write_str("(hidden)"),
Self::Config(name) => write!(f, "from {name}"),
}
}
}
pub(crate) fn from_unix(seconds: i64) -> Option<DateTime> {
renox::chrono::DateTime::from_timestamp(seconds, 0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_keys_say_where_to_set_them() {
let config = Config::default();
let err = Secret::Config("STRIPE_SECRET")
.require(&config, "Stripe's secret key")
.unwrap_err();
assert!(
format!("{err:?}")
.contains("Stripe's secret key is missing: set STRIPE_SECRET in .env"),
"{err:?}"
);
let err = Secret::Given(String::new())
.require(&config, "Xendit's secret key")
.unwrap_err();
assert!(format!("{err:?}").contains("it was given empty"), "{err:?}");
let mut config = Config::default();
config.vars.insert("STRIPE_SECRET".into(), "sk_1".into());
assert_eq!(
Secret::Config("STRIPE_SECRET")
.require(&config, "x")
.unwrap(),
"sk_1"
);
assert_eq!(format!("{:?}", Secret::Given("sk".into())), "(hidden)");
let resolved = Secret::resolved(|_| async { Ok(Some("sk_2".to_string())) });
assert_eq!(format!("{resolved:?}"), "(hidden)");
assert!(resolved.is_set(&Config::default()));
assert!(!Secret::Config("X").is_set(&Config::default()));
}
#[test]
fn payments_keep_their_id_and_an_upper_case_currency() {
let payment = Payment::new("in_1", 900, "usd", false)
.subscription("sub_1")
.customer("cus_1");
assert_eq!(payment.id, "in_1");
assert_eq!(payment.currency, "USD");
assert_eq!(payment.subscription_id.as_deref(), Some("sub_1"));
assert_eq!(payment.customer_id.as_deref(), Some("cus_1"));
assert!(!payment.succeeded);
}
}