use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::common::{Address, AuthenticationType, CaptureMethod, SetupFutureUsage};
use crate::core::models::subscription::{
AdoptSubscriptionResponse, CancelSubscriptionResponse, ConfirmSubscriptionResponse,
NativeDunningConfigResponse, NativeRecoveryMode, NativeShopConfigResponse,
PauseSubscriptionResponse, ResumeSubscriptionResponse, SubscriptionBillingProcessorResponse,
SubscriptionCapabilities, SubscriptionEstimateResponse, SubscriptionImportApplyResponse,
SubscriptionImportPreviewResponse, SubscriptionInvoiceListResponse, SubscriptionItem,
SubscriptionPaymentLookupResponse, SubscriptionResponse, SubscriptionSyncResponse,
SubscriptionSyncResult,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
pub const PAYMENT_LOOKUP_MAX_IDS: usize = 200;
#[derive(Debug, Clone)]
pub struct Subscriptions {
inner: Arc<Inner>,
profile_id: Option<String>,
}
impl Subscriptions {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self {
inner,
profile_id: None,
}
}
#[must_use]
pub fn with_profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
fn headers(&self) -> Vec<(&str, &str)> {
match &self.profile_id {
Some(id) => vec![("x-profile-id", id.as_str())],
None => Vec::new(),
}
}
async fn send<T: serde::de::DeserializeOwned>(
&self,
method: HttpMethod,
path: &str,
body: Option<&[u8]>,
query: &[(&str, String)],
) -> Result<T> {
self.inner
.request_with_headers(method, path, body, query, None, &self.headers())
.await
}
async fn send_unkeyed<T: serde::de::DeserializeOwned>(
&self,
method: HttpMethod,
path: &str,
body: Option<&[u8]>,
query: &[(&str, String)],
) -> Result<T> {
self.inner
.request_body_keyed_with_query_and_headers(
method,
path,
body,
query,
&self.headers(),
None,
)
.await
}
pub async fn create_and_confirm(
&self,
params: &CreateAndConfirmSubscriptionRequest,
) -> Result<ConfirmSubscriptionResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.send(HttpMethod::Post, "/subscriptions", Some(&body), &[])
.await
}
pub async fn create(&self, params: &CreateSubscriptionRequest) -> Result<SubscriptionResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.send(HttpMethod::Post, "/subscriptions/create", Some(&body), &[])
.await
}
pub async fn retrieve(&self, subscription_id: &str) -> Result<SubscriptionResponse> {
let path = format!("/subscriptions/{}", encode_segment(subscription_id));
self.send(HttpMethod::Get, &path, None, &[]).await
}
pub async fn confirm(
&self,
subscription_id: &str,
params: &ConfirmSubscriptionRequest,
) -> Result<ConfirmSubscriptionResponse> {
let path = format!("/subscriptions/{}/confirm", encode_segment(subscription_id));
let body = to_json_vec(params)?;
self.send(HttpMethod::Post, &path, Some(&body), &[]).await
}
pub async fn update(
&self,
subscription_id: &str,
params: &UpdateSubscriptionRequest,
) -> Result<SubscriptionResponse> {
params.validate()?;
let path = format!("/subscriptions/{}/update", encode_segment(subscription_id));
let body = to_json_vec(params)?;
self.send(HttpMethod::Put, &path, Some(&body), &[]).await
}
pub async fn list(
&self,
params: Option<&SubscriptionListParams>,
) -> Result<Vec<SubscriptionResponse>> {
let query = params
.map(SubscriptionListParams::to_query)
.unwrap_or_default();
self.send(HttpMethod::Get, "/subscriptions/list", None, &query)
.await
}
pub async fn estimate(
&self,
params: &SubscriptionEstimateParams,
) -> Result<SubscriptionEstimateResponse> {
self.send(
HttpMethod::Get,
"/subscriptions/estimate",
None,
¶ms.to_query(),
)
.await
}
pub async fn items(&self, params: &SubscriptionItemsParams) -> Result<Vec<SubscriptionItem>> {
self.send(
HttpMethod::Get,
"/subscriptions/items",
None,
¶ms.to_query(),
)
.await
}
pub async fn pause(
&self,
subscription_id: &str,
params: Option<&PauseSubscriptionRequest>,
) -> Result<PauseSubscriptionResponse> {
let path = format!("/subscriptions/{}/pause", encode_segment(subscription_id));
let body = Self::body_or_empty_object(params)?;
self.send(HttpMethod::Post, &path, Some(&body), &[]).await
}
pub async fn resume(
&self,
subscription_id: &str,
params: Option<&ResumeSubscriptionRequest>,
) -> Result<ResumeSubscriptionResponse> {
let path = format!("/subscriptions/{}/resume", encode_segment(subscription_id));
let body = Self::body_or_empty_object(params)?;
self.send(HttpMethod::Post, &path, Some(&body), &[]).await
}
pub async fn cancel(
&self,
subscription_id: &str,
params: Option<&CancelSubscriptionRequest>,
) -> Result<CancelSubscriptionResponse> {
let path = format!("/subscriptions/{}/cancel", encode_segment(subscription_id));
let body = Self::body_or_empty_object(params)?;
self.send(HttpMethod::Post, &path, Some(&body), &[]).await
}
pub async fn lookup_payments(
&self,
payment_ids: &[String],
) -> Result<SubscriptionPaymentLookupResponse> {
if payment_ids.len() > PAYMENT_LOOKUP_MAX_IDS {
return Err(DelopayError::InvalidRequest(format!(
"payment_ids accepts at most {PAYMENT_LOOKUP_MAX_IDS} entries, got {}",
payment_ids.len()
)));
}
let body = to_json_vec(&SubscriptionPaymentLookupRequest { payment_ids })?;
self.send(
HttpMethod::Post,
"/subscriptions/payments/lookup",
Some(&body),
&[],
)
.await
}
pub async fn native_config(&self) -> Result<NativeShopConfigResponse> {
self.send(HttpMethod::Get, "/subscriptions/native/config", None, &[])
.await
}
pub async fn update_native_config(
&self,
params: &NativeShopConfigRequest,
) -> Result<NativeShopConfigResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.send_unkeyed(
HttpMethod::Put,
"/subscriptions/native/config",
Some(&body),
&[],
)
.await
}
pub async fn native_dunning(&self) -> Result<NativeDunningConfigResponse> {
self.send(HttpMethod::Get, "/subscriptions/native/dunning", None, &[])
.await
}
pub async fn update_native_dunning(
&self,
params: &NativeDunningConfigRequest,
) -> Result<NativeDunningConfigResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.send_unkeyed(
HttpMethod::Put,
"/subscriptions/native/dunning",
Some(&body),
&[],
)
.await
}
pub async fn capabilities(&self, subscription_id: &str) -> Result<SubscriptionCapabilities> {
let path = format!(
"/subscriptions/{}/capabilities",
encode_segment(subscription_id)
);
self.send(HttpMethod::Get, &path, None, &[]).await
}
pub async fn adopt(
&self,
params: &AdoptSubscriptionRequest,
) -> Result<AdoptSubscriptionResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.send_unkeyed(HttpMethod::Post, "/subscriptions/adopt", Some(&body), &[])
.await
}
pub async fn sync(&self, params: &SubscriptionSyncRequest) -> Result<SubscriptionSyncResponse> {
let body = to_json_vec(params)?;
self.send_unkeyed(HttpMethod::Post, "/subscriptions/sync", Some(&body), &[])
.await
}
pub async fn sync_one(&self, subscription_id: &str) -> Result<SubscriptionSyncResult> {
let path = format!("/subscriptions/{}/sync", encode_segment(subscription_id));
self.send_unkeyed(HttpMethod::Post, &path, None, &[]).await
}
pub async fn import_preview(
&self,
params: &SubscriptionImportPreviewRequest,
) -> Result<SubscriptionImportPreviewResponse> {
let body = to_json_vec(params)?;
self.send_unkeyed(
HttpMethod::Post,
"/subscriptions/import/preview",
Some(&body),
&[],
)
.await
}
pub async fn import_apply(
&self,
params: &SubscriptionImportApplyRequest,
) -> Result<SubscriptionImportApplyResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.send_unkeyed(
HttpMethod::Post,
"/subscriptions/import/apply",
Some(&body),
&[],
)
.await
}
pub async fn list_invoices(
&self,
subscription_id: &str,
params: Option<&SubscriptionInvoiceListParams>,
) -> Result<SubscriptionInvoiceListResponse> {
let path = format!(
"/subscriptions/{}/invoices",
encode_segment(subscription_id)
);
let query = params
.map(SubscriptionInvoiceListParams::to_query)
.unwrap_or_default();
self.send(HttpMethod::Get, &path, None, &query).await
}
pub async fn billing_processor(&self) -> Result<SubscriptionBillingProcessorResponse> {
self.send(
HttpMethod::Get,
"/subscriptions/billing_processor",
None,
&[],
)
.await
}
fn body_or_empty_object<T: Serialize>(params: Option<&T>) -> Result<Vec<u8>> {
match params {
Some(p) => to_json_vec(p),
None => Ok(b"{}".to_vec()),
}
}
}
#[derive(Debug, Serialize)]
struct SubscriptionPaymentLookupRequest<'a> {
payment_ids: &'a [String],
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateSubscriptionPaymentDetails {
pub return_url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub setup_future_usage: Option<SetupFutureUsage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture_method: Option<CaptureMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication_type: Option<AuthenticationType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_type: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateSubscriptionRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub item_price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub price_id: Option<String>,
pub customer_id: String,
pub payment_details: CreateSubscriptionPaymentDetails,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_reference_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub plan_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub coupon_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Address>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const CREATE_SUBSCRIPTION_REQUEST_NAMED: &[&str] = &[
"item_price_id",
"product_id",
"price_id",
"customer_id",
"payment_details",
"merchant_reference_id",
"plan_id",
"coupon_code",
"billing",
"shipping",
];
impl ValidateRequest for CreateSubscriptionRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if CREATE_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on CreateSubscriptionRequest"
)));
}
}
check_price_source(
self.item_price_id.as_deref(),
self.product_id.as_deref(),
self.price_id.as_deref(),
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionPaymentDetails {
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub setup_future_usage: Option<SetupFutureUsage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_acceptance: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture_method: Option<CaptureMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication_type: Option<AuthenticationType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_id: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateAndConfirmSubscriptionRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub item_price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub price_id: Option<String>,
pub customer_id: String,
pub payment_details: SubscriptionPaymentDetails,
#[serde(skip_serializing_if = "Option::is_none")]
pub plan_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub coupon_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_reference_id: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED: &[&str] = &[
"item_price_id",
"product_id",
"price_id",
"customer_id",
"payment_details",
"plan_id",
"coupon_code",
"billing",
"shipping",
"merchant_reference_id",
];
impl ValidateRequest for CreateAndConfirmSubscriptionRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on \
CreateAndConfirmSubscriptionRequest"
)));
}
}
check_price_source(
self.item_price_id.as_deref(),
self.product_id.as_deref(),
self.price_id.as_deref(),
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConfirmSubscriptionPaymentDetails {
pub payment_method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_data: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_acceptance: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_token: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConfirmSubscriptionRequest {
pub payment_details: ConfirmSubscriptionPaymentDetails,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
}
fn check_price_source(
item_price_id: Option<&str>,
product_id: Option<&str>,
price_id: Option<&str>,
) -> Result<()> {
match (item_price_id, product_id) {
(Some(_), Some(_)) => Err(DelopayError::InvalidRequest(
"`item_price_id` and `product_id` are exclusive; send one".to_owned(),
)),
(None, None) => Err(DelopayError::InvalidRequest(
"a price source is required: `item_price_id` or `product_id`".to_owned(),
)),
(Some(_), None) if price_id.is_some() => Err(DelopayError::InvalidRequest(
"`price_id` is only sent with `product_id`".to_owned(),
)),
_ => Ok(()),
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateSubscriptionRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub plan_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub price_id: Option<String>,
}
impl UpdateSubscriptionRequest {
pub fn for_price(item_price_id: impl Into<String>) -> Self {
Self {
item_price_id: Some(item_price_id.into()),
..Default::default()
}
}
pub fn for_product(product_id: impl Into<String>) -> Self {
Self {
product_id: Some(product_id.into()),
..Default::default()
}
}
#[must_use]
pub fn plan_id(mut self, plan_id: impl Into<String>) -> Self {
self.plan_id = Some(plan_id.into());
self
}
#[must_use]
pub fn price_id(mut self, price_id: impl Into<String>) -> Self {
self.price_id = Some(price_id.into());
self
}
fn validate(&self) -> Result<()> {
if self.product_id.is_some() && self.plan_id.is_some() {
return Err(DelopayError::InvalidRequest(
"`plan_id` is not sent with `product_id`".to_owned(),
));
}
check_price_source(
self.item_price_id.as_deref(),
self.product_id.as_deref(),
self.price_id.as_deref(),
)
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PauseSubscriptionRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub pause_option: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pause_at: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ResumeSubscriptionRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub resume_option: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resume_date: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub charges_handling: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unpaid_invoices_handling: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CancelSubscriptionRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_option: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unbilled_charges_option: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub credit_option_for_current_term_charges: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub account_receivables_handling: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub refundable_credits_handling: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_reason_code: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct SubscriptionListParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
pub test_mode: Option<bool>,
}
impl SubscriptionListParams {
pub(crate) fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
if let Some(v) = self.test_mode {
q.push(("test_mode", v.to_string()));
}
q
}
}
#[derive(Debug, Clone, Default)]
pub struct SubscriptionItemsParams {
pub item_type: String,
pub client_secret: Option<String>,
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl SubscriptionItemsParams {
pub fn new(item_type: impl Into<String>) -> Self {
Self {
item_type: item_type.into(),
..Default::default()
}
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = vec![("item_type", self.item_type.clone())];
if let Some(v) = &self.client_secret {
q.push(("client_secret", v.clone()));
}
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
#[derive(Debug, Clone, Default)]
pub struct SubscriptionEstimateParams {
pub item_price_id: String,
pub plan_id: Option<String>,
pub coupon_code: Option<String>,
}
impl SubscriptionEstimateParams {
pub fn new(item_price_id: impl Into<String>) -> Self {
Self {
item_price_id: item_price_id.into(),
..Default::default()
}
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = vec![("item_price_id", self.item_price_id.clone())];
if let Some(v) = &self.plan_id {
q.push(("plan_id", v.clone()));
}
if let Some(v) = &self.coupon_code {
q.push(("coupon_code", v.clone()));
}
q
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct NativeShopConfigRequest {
pub enabled: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_connector_id: Option<String>,
pub test_mode: bool,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl NativeShopConfigRequest {
pub fn new(enabled: bool, test_mode: bool) -> Self {
Self {
enabled,
test_mode,
..Default::default()
}
}
#[must_use]
pub fn payment_connector_id(mut self, payment_connector_id: impl Into<String>) -> Self {
self.payment_connector_id = Some(payment_connector_id.into());
self
}
}
const NATIVE_SHOP_CONFIG_REQUEST_NAMED: &[&str] = &["enabled", "payment_connector_id", "test_mode"];
impl ValidateRequest for NativeShopConfigRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if NATIVE_SHOP_CONFIG_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on NativeShopConfigRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct NativeDunningConfigRequest {
pub enabled: bool,
pub retry_days: Vec<i32>,
pub max_attempts: i32,
pub cancel_after_exhaustion: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub recovery_mode: Option<NativeRecoveryMode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recovery_after_attempt: Option<i32>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl NativeDunningConfigRequest {
pub fn new(
enabled: bool,
retry_days: Vec<i32>,
max_attempts: i32,
cancel_after_exhaustion: bool,
) -> Self {
Self {
enabled,
retry_days,
max_attempts,
cancel_after_exhaustion,
..Default::default()
}
}
#[must_use]
pub fn recovery_mode(mut self, recovery_mode: impl Into<NativeRecoveryMode>) -> Self {
self.recovery_mode = Some(recovery_mode.into());
self
}
#[must_use]
pub fn recovery_after_attempt(mut self, recovery_after_attempt: i32) -> Self {
self.recovery_after_attempt = Some(recovery_after_attempt);
self
}
}
const NATIVE_DUNNING_CONFIG_REQUEST_NAMED: &[&str] = &[
"enabled",
"retry_days",
"max_attempts",
"cancel_after_exhaustion",
"recovery_mode",
"recovery_after_attempt",
];
impl ValidateRequest for NativeDunningConfigRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if NATIVE_DUNNING_CONFIG_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on NativeDunningConfigRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct AdoptSubscriptionRequest {
pub billing_processor: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_connector_id: Option<String>,
pub external_subscription_id: String,
pub customer_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_customer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub item_price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub plan_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_reference_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub test_mode: Option<bool>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl AdoptSubscriptionRequest {
pub fn new(
billing_processor: impl Into<String>,
external_subscription_id: impl Into<String>,
customer_id: impl Into<String>,
) -> Self {
Self {
billing_processor: billing_processor.into(),
external_subscription_id: external_subscription_id.into(),
customer_id: customer_id.into(),
..Default::default()
}
}
#[must_use]
pub fn merchant_connector_id(mut self, merchant_connector_id: impl Into<String>) -> Self {
self.merchant_connector_id = Some(merchant_connector_id.into());
self
}
#[must_use]
pub fn connector_customer_id(mut self, connector_customer_id: impl Into<String>) -> Self {
self.connector_customer_id = Some(connector_customer_id.into());
self
}
#[must_use]
pub fn item_price_id(mut self, item_price_id: impl Into<String>) -> Self {
self.item_price_id = Some(item_price_id.into());
self
}
#[must_use]
pub fn plan_id(mut self, plan_id: impl Into<String>) -> Self {
self.plan_id = Some(plan_id.into());
self
}
#[must_use]
pub fn merchant_reference_id(mut self, merchant_reference_id: impl Into<String>) -> Self {
self.merchant_reference_id = Some(merchant_reference_id.into());
self
}
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
}
const ADOPT_SUBSCRIPTION_REQUEST_NAMED: &[&str] = &[
"billing_processor",
"merchant_connector_id",
"external_subscription_id",
"customer_id",
"connector_customer_id",
"item_price_id",
"plan_id",
"merchant_reference_id",
"test_mode",
];
impl ValidateRequest for AdoptSubscriptionRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if ADOPT_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on AdoptSubscriptionRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionSyncRequest {
pub subscription_ids: Vec<String>,
}
impl SubscriptionSyncRequest {
pub fn new(subscription_ids: Vec<String>) -> Self {
Self { subscription_ids }
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionImportPreviewRequest {
pub merchant_connector_id: String,
}
impl SubscriptionImportPreviewRequest {
pub fn new(merchant_connector_id: impl Into<String>) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionImportSelection {
pub external_subscription_id: String,
pub customer_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_customer_id: Option<String>,
}
impl SubscriptionImportSelection {
pub fn new(
external_subscription_id: impl Into<String>,
customer_id: impl Into<String>,
) -> Self {
Self {
external_subscription_id: external_subscription_id.into(),
customer_id: customer_id.into(),
connector_customer_id: None,
}
}
#[must_use]
pub fn connector_customer_id(mut self, connector_customer_id: impl Into<String>) -> Self {
self.connector_customer_id = Some(connector_customer_id.into());
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionImportApplyRequest {
pub merchant_connector_id: String,
pub items: Vec<SubscriptionImportSelection>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl SubscriptionImportApplyRequest {
pub fn new(
merchant_connector_id: impl Into<String>,
items: Vec<SubscriptionImportSelection>,
) -> Self {
Self {
merchant_connector_id: merchant_connector_id.into(),
items,
extra: serde_json::Map::new(),
}
}
}
const SUBSCRIPTION_IMPORT_APPLY_REQUEST_NAMED: &[&str] = &["merchant_connector_id", "items"];
impl ValidateRequest for SubscriptionImportApplyRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SUBSCRIPTION_IMPORT_APPLY_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on SubscriptionImportApplyRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct SubscriptionInvoiceListParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
}
impl SubscriptionInvoiceListParams {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn limit(mut self, limit: i64) -> Self {
self.limit = Some(limit);
self
}
#[must_use]
pub fn offset(mut self, offset: i64) -> Self {
self.offset = Some(offset);
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
let mut q = Vec::new();
if let Some(v) = self.limit {
q.push(("limit", v.to_string()));
}
if let Some(v) = self.offset {
q.push(("offset", v.to_string()));
}
q
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const SUB_JSON: &str = r#"{"id": "sub_1", "status": "active"}"#;
const CONFIRM_JSON: &str = r#"{
"id": "sub_1", "status": "pending",
"redirect_url": "https://paypal.test/approve"
}"#;
fn create_and_confirm_request() -> CreateAndConfirmSubscriptionRequest {
CreateAndConfirmSubscriptionRequest {
item_price_id: Some("price_1".to_string()),
customer_id: "cus_1".to_string(),
payment_details: SubscriptionPaymentDetails {
payment_method: Some("card".to_string()),
..Default::default()
},
..Default::default()
}
}
#[tokio::test]
async fn lookup_payments_posts_the_batch_and_reports_only_matches() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"links":[{"payment_id":"pay_1","subscription_id":"sub_1",
"invoice_id":"inv_1","invoice_status":"paid"}]}"#,
)]);
let ids = vec!["pay_1".to_string(), "pay_2".to_string()];
let out = client
.subscriptions()
.with_profile_id("pro_1")
.lookup_payments(&ids)
.await
.unwrap();
assert_eq!(out.links.len(), 1);
assert_eq!(out.links[0].payment_id, "pay_1");
assert_eq!(out.links[0].subscription_id, "sub_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/payments/lookup"
);
assert_eq!(
seen[0].body_json()["payment_ids"],
json!(["pay_1", "pay_2"])
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn lookup_payments_rejects_an_oversized_batch_before_the_wire() {
let (client, mock) = client_with(vec![]);
let ids: Vec<String> = (0..=PAYMENT_LOOKUP_MAX_IDS)
.map(|n| format!("pay_{n}"))
.collect();
match client
.subscriptions()
.lookup_payments(&ids)
.await
.unwrap_err()
{
DelopayError::InvalidRequest(msg) => assert!(msg.contains("200"), "{msg}"),
other => panic!("expected InvalidRequest, got {other:?}"),
}
assert_eq!(mock.call_count(), 0);
}
#[tokio::test]
async fn lookup_payments_accepts_a_batch_at_the_limit() {
let (client, mock) = client_with(vec![Step::ok(r#"{"links":[]}"#)]);
let ids: Vec<String> = (0..PAYMENT_LOOKUP_MAX_IDS)
.map(|n| format!("pay_{n}"))
.collect();
client.subscriptions().lookup_payments(&ids).await.unwrap();
assert_eq!(mock.call_count(), 1);
}
#[tokio::test]
async fn sends_x_profile_id_header_when_scoped() {
let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
client
.subscriptions()
.with_profile_id("pro_1")
.retrieve("sub_1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn omits_the_profile_header_when_unscoped() {
let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
client.subscriptions().retrieve("sub_1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].header("x-profile-id"), None);
}
#[tokio::test]
async fn create_and_confirm_posts_to_subscriptions_root() {
let (client, mock) = client_with(vec![Step::ok(CONFIRM_JSON)]);
let out = client
.subscriptions()
.with_profile_id("pro_1")
.create_and_confirm(&create_and_confirm_request())
.await
.unwrap();
assert_eq!(
out.redirect_url.as_deref(),
Some("https://paypal.test/approve")
);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/subscriptions");
let body = seen[0].body_json();
assert_eq!(body["item_price_id"], "price_1");
assert_eq!(body["payment_details"]["payment_method"], "card");
}
#[tokio::test]
async fn update_puts_to_the_update_path() {
let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
let req = UpdateSubscriptionRequest::for_price("price_2").plan_id("plan_2");
client.subscriptions().update("sub_1", &req).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/subscriptions/sub_1/update");
assert_eq!(
seen[0].body_json(),
json!({"plan_id": "plan_2", "item_price_id": "price_2"})
);
}
#[tokio::test]
async fn update_to_a_product_sends_only_the_product_price() {
let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
let req = UpdateSubscriptionRequest::for_product("prod_1").price_id("prc_1");
client.subscriptions().update("sub_1", &req).await.unwrap();
assert_eq!(
mock.seen.lock().unwrap()[0].body_json(),
json!({"product_id": "prod_1", "price_id": "prc_1"})
);
}
#[tokio::test]
async fn a_bad_price_source_is_refused_before_sending() {
let (client, mock) = client_with(vec![]);
let subs = client.subscriptions();
let both = UpdateSubscriptionRequest {
item_price_id: Some("price_1".to_string()),
product_id: Some("prod_1".to_string()),
..Default::default()
};
assert!(matches!(
subs.update("sub_1", &both).await,
Err(DelopayError::InvalidRequest(_))
));
assert!(matches!(
subs.update("sub_1", &UpdateSubscriptionRequest::default())
.await,
Err(DelopayError::InvalidRequest(_))
));
let plan_with_product = UpdateSubscriptionRequest::for_product("prod_1").plan_id("plan_1");
assert!(subs.update("sub_1", &plan_with_product).await.is_err());
let price_without_product = CreateSubscriptionRequest {
item_price_id: Some("price_1".to_string()),
price_id: Some("prc_1".to_string()),
..Default::default()
};
assert!(subs.create(&price_without_product).await.is_err());
let product_create = CreateAndConfirmSubscriptionRequest {
item_price_id: None,
product_id: Some("prod_1".to_string()),
..create_and_confirm_request()
};
assert!(product_create.validate().is_ok());
assert_eq!(mock.call_count(), 0);
}
#[tokio::test]
async fn pause_resume_cancel_send_an_empty_object_body_by_default() {
let (client, mock) = client_with(vec![
Step::ok(r#"{"id":"sub_1","status":"paused"}"#),
Step::ok(r#"{"id":"sub_1","status":"active"}"#),
Step::ok(r#"{"id":"sub_1","status":"cancelled"}"#),
]);
let subs = client.subscriptions();
subs.pause("sub_1", None).await.unwrap();
subs.resume("sub_1", None).await.unwrap();
subs.cancel("sub_1", None).await.unwrap();
let seen = mock.seen.lock().unwrap();
let paths = [
"https://api.test/subscriptions/sub_1/pause",
"https://api.test/subscriptions/sub_1/resume",
"https://api.test/subscriptions/sub_1/cancel",
];
for (i, path) in paths.iter().enumerate() {
assert_eq!(seen[i].url, *path);
assert_eq!(
seen[i].body_json(),
json!({}),
"call {i} must carry an empty JSON object body"
);
}
}
#[tokio::test]
async fn cancel_serializes_scheduling_options() {
let (client, mock) = client_with(vec![Step::ok(r#"{"id":"sub_1","status":"cancelled"}"#)]);
let req = CancelSubscriptionRequest {
cancel_option: Some("end_of_term".to_string()),
cancel_reason_code: Some("too_expensive".to_string()),
..Default::default()
};
client
.subscriptions()
.cancel("sub_1", Some(&req))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
let body = seen[0].body_json();
assert_eq!(body["cancel_option"], "end_of_term");
assert_eq!(body["cancel_reason_code"], "too_expensive");
}
#[tokio::test]
async fn read_endpoints_serialize_their_queries() {
let (client, mock) = client_with(vec![
Step::ok("[]"),
Step::ok(r#"{"amount":999,"currency":"EUR","line_items":[]}"#),
Step::ok("[]"),
]);
let subs = client.subscriptions();
subs.list(Some(&SubscriptionListParams {
limit: Some(10),
offset: Some(20),
test_mode: None,
}))
.await
.unwrap();
subs.estimate(&SubscriptionEstimateParams::new("price_1"))
.await
.unwrap();
subs.items(&SubscriptionItemsParams::new("plan"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/list?limit=10&offset=20"
);
assert_eq!(
seen[1].url,
"https://api.test/subscriptions/estimate?item_price_id=price_1"
);
assert_eq!(
seen[2].url,
"https://api.test/subscriptions/items?item_type=plan"
);
}
#[test]
fn create_request_named_fields_are_complete() {
let req = CreateSubscriptionRequest {
item_price_id: Some("price_1".to_string()),
product_id: Some("prod_1".to_string()),
price_id: Some("prc_1".to_string()),
customer_id: "cus_1".to_string(),
payment_details: CreateSubscriptionPaymentDetails {
return_url: "https://example.com/r".to_string(),
setup_future_usage: Some(SetupFutureUsage::OffSession),
capture_method: Some(CaptureMethod::Automatic),
authentication_type: Some(AuthenticationType::NoThreeDs),
payment_type: Some("recurring".to_string()),
},
merchant_reference_id: Some("ref_1".to_string()),
plan_id: Some("plan_1".to_string()),
coupon_code: Some("SAVE10".to_string()),
billing: Some(Address::default()),
shipping: Some(Address::default()),
extra: serde_json::Map::new(),
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().unwrap().keys() {
assert!(
CREATE_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()),
"CREATE_SUBSCRIPTION_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn create_and_confirm_request_named_fields_are_complete() {
let req = CreateAndConfirmSubscriptionRequest {
product_id: Some("prod_1".to_string()),
price_id: Some("prc_1".to_string()),
plan_id: Some("plan_1".to_string()),
coupon_code: Some("SAVE10".to_string()),
billing: Some(Address::default()),
shipping: Some(Address::default()),
merchant_reference_id: Some("ref_1".to_string()),
..create_and_confirm_request()
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().unwrap().keys() {
assert!(
CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()),
"CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn create_validate_rejects_colliding_extra_key() {
let mut req = CreateSubscriptionRequest::default();
req.extra.insert("customer_id".to_string(), json!("cus_2"));
assert!(matches!(
req.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
#[tokio::test]
async fn native_config_gets_the_shop_settings() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"enabled":true,"payment_connector_id":"mca_1","test_mode":false,
"eligible_connectors":["stripe"],"surprise_field":1}"#,
)]);
let out = client
.subscriptions()
.with_profile_id("pro_1")
.native_config()
.await
.unwrap();
assert!(out.enabled);
assert_eq!(out.payment_connector_id.as_deref(), Some("mca_1"));
assert_eq!(out.eligible_connectors, ["stripe"]);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/subscriptions/native/config");
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn update_native_config_puts_the_settings() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"enabled":true,"test_mode":true,"eligible_connectors":[]}"#,
)]);
let params = NativeShopConfigRequest::new(true, true).payment_connector_id("mca_1");
let out = client
.subscriptions()
.with_profile_id("pro_1")
.update_native_config(¶ms)
.await
.unwrap();
assert!(out.test_mode);
assert!(out.payment_connector_id.is_none());
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/subscriptions/native/config");
assert_eq!(
seen[0].body_json(),
json!({"enabled":true,"payment_connector_id":"mca_1","test_mode":true})
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
const DUNNING_JSON: &str = r#"{"enabled":true,"retry_days":[1,3,7],"max_attempts":4,
"cancel_after_exhaustion":false,"recovery_mode":"buyer_link",
"recovery_after_attempt":2,"surprise_field":"x"}"#;
#[tokio::test]
async fn native_dunning_gets_the_recovery_settings() {
let (client, mock) = client_with(vec![Step::ok(DUNNING_JSON)]);
let out = client.subscriptions().native_dunning().await.unwrap();
assert_eq!(out.retry_days, [1, 3, 7]);
assert_eq!(out.max_attempts, 4);
assert_eq!(out.recovery_mode, "buyer_link");
assert_eq!(out.recovery_after_attempt, 2);
assert_eq!(out.extra["surprise_field"], "x");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/subscriptions/native/dunning");
}
#[tokio::test]
async fn update_native_dunning_puts_the_schedule_and_omits_unset_fields() {
let (client, mock) = client_with(vec![Step::ok(DUNNING_JSON)]);
let params = NativeDunningConfigRequest::new(true, vec![1, 3, 7], 4, false);
client
.subscriptions()
.update_native_dunning(¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/subscriptions/native/dunning");
assert_eq!(
seen[0].body_json(),
json!({"enabled":true,"retry_days":[1,3,7],"max_attempts":4,
"cancel_after_exhaustion":false})
);
}
#[tokio::test]
async fn capabilities_gets_the_encoded_subscription_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"pause_immediately":true,"resume_immediately":true,
"cancel_immediately":false,"cancel_at_period_end":true,
"change_plan":false,"pause_voids_invoices":true,"surprise_field":1}"#,
)]);
let out = client
.subscriptions()
.with_profile_id("pro_1")
.capabilities("sub/1")
.await
.unwrap();
assert!(out.pause_immediately);
assert!(!out.cancel_immediately);
assert!(out.pause_voids_invoices);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/sub%2F1/capabilities"
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
const ADOPT_JSON: &str = r#"{"subscription_id":"sub_1","adopted":true,
"billing_processor":"creem","external_subscription_id":"ext_1",
"status":"active","customer_id":"cus_1","profile_id":"pro_1",
"handoff_confirmed":false,"surprise_field":1}"#;
#[tokio::test]
async fn adopt_posts_the_adoption() {
let (client, mock) = client_with(vec![Step::ok(ADOPT_JSON)]);
let params =
AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1").item_price_id("price_1");
let out = client
.subscriptions()
.with_profile_id("pro_1")
.adopt(¶ms)
.await
.unwrap();
assert_eq!(out.subscription_id, "sub_1");
assert!(out.adopted);
assert!(!out.handoff_confirmed);
assert_eq!(out.billing_processor, "creem");
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/subscriptions/adopt");
assert_eq!(
seen[0].body_json(),
json!({"billing_processor":"creem","external_subscription_id":"ext_1",
"customer_id":"cus_1","item_price_id":"price_1"})
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
assert!(!seen[0].had_idempotency_key());
}
#[tokio::test]
async fn adopt_sends_the_environment_it_is_given() {
for test_mode in [true, false] {
let (client, mock) = client_with(vec![Step::ok(ADOPT_JSON)]);
let params =
AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1").test_mode(test_mode);
client.subscriptions().adopt(¶ms).await.unwrap();
assert_eq!(
mock.seen.lock().unwrap()[0].body_json(),
json!({"billing_processor":"creem","external_subscription_id":"ext_1",
"customer_id":"cus_1","test_mode":test_mode})
);
}
}
#[tokio::test]
async fn adopt_ignores_a_client_wide_key_and_is_not_replayed() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, r#"{"error":{"message":"down"}}"#),
Step::ok(ADOPT_JSON),
],
2,
);
let params = AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1");
assert!(
client
.with_idempotency_key("client-key")
.subscriptions()
.adopt(¶ms)
.await
.is_err()
);
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn adopt_is_not_replayed_on_a_server_error() {
let (client, mock) = client_with_retries(vec![Step::status(500, "{}")], 2);
let params = AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1");
assert!(client.subscriptions().adopt(¶ms).await.is_err());
assert_eq!(mock.call_count(), 1);
}
#[tokio::test]
async fn sync_posts_the_ids_and_decodes_each_result() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"results":[{"subscription_id":"sub_1","outcome":"updated",
"status":"active","provider":{"billing_processor_subscription_id":"ext_1",
"status":"active","read_at":"2026-01-01T00:00:00Z","surprise_field":2}},
{"subscription_id":"sub_2","outcome":"not_found"}],"surprise_field":1}"#,
)]);
let params = SubscriptionSyncRequest::new(vec!["sub_1".into(), "sub_2".into()]);
let out = client
.subscriptions()
.with_profile_id("pro_1")
.sync(¶ms)
.await
.unwrap();
assert_eq!(out.results.len(), 2);
assert_eq!(out.results[0].outcome, "updated");
let provider = out.results[0].provider.as_ref().unwrap();
assert_eq!(provider.billing_processor_subscription_id, "ext_1");
assert_eq!(provider.extra["surprise_field"], 2);
assert!(out.results[1].provider.is_none());
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/subscriptions/sync");
assert_eq!(
seen[0].body_json(),
json!({"subscription_ids":["sub_1","sub_2"]})
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn sync_one_posts_to_the_encoded_subscription_without_a_body() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"subscription_id":"sub/1","outcome":"unchanged","status":"active",
"surprise_field":1}"#,
)]);
let out = client
.subscriptions()
.with_profile_id("pro_1")
.sync_one("sub/1")
.await
.unwrap();
assert_eq!(out.outcome, "unchanged");
assert_eq!(out.status.as_deref(), Some("active"));
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/subscriptions/sub%2F1/sync");
assert!(seen[0].body.is_none());
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn import_preview_posts_the_billing_account() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"capabilities":{"connector":"creem","listing":true,"adoption":true},
"counts":{"new":1,"needs_customer":0,"held":0,"ended":0,"not_adoptable":0},
"truncated":false,
"items":[{"external_subscription_id":"ext_1","provider_status":"active",
"status":"active","customer_email":"buyer@example.com",
"classification":"new","customer_id":"cus_1"}],
"surprise_field":1}"#,
)]);
let params = SubscriptionImportPreviewRequest::new("mca_1");
let out = client
.subscriptions()
.with_profile_id("pro_1")
.import_preview(¶ms)
.await
.unwrap();
assert!(out.capabilities.listing);
assert_eq!(out.counts.new, 1);
assert_eq!(out.items[0].classification, "new");
assert_eq!(out.extra["surprise_field"], 1);
let debug = format!("{:?}", out.items[0]);
assert!(!debug.contains("buyer@example.com"), "{debug}");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/subscriptions/import/preview");
assert_eq!(
seen[0].body_json(),
json!({"merchant_connector_id":"mca_1"})
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn import_apply_posts_the_selections() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"results":[{"external_subscription_id":"ext_1","outcome":"adopted",
"subscription_id":"sub_1"},{"external_subscription_id":"ext_2",
"outcome":"failed","reason":"refused","reason_code":"adoption_refused"}],
"surprise_field":1}"#,
)]);
let params = SubscriptionImportApplyRequest::new(
"mca_1",
vec![
SubscriptionImportSelection::new("ext_1", "cus_1"),
SubscriptionImportSelection::new("ext_2", "cus_2").connector_customer_id("cc_2"),
],
);
let out = client
.subscriptions()
.with_profile_id("pro_1")
.import_apply(¶ms)
.await
.unwrap();
assert_eq!(out.results[0].subscription_id.as_deref(), Some("sub_1"));
assert_eq!(
out.results[1].reason_code.as_deref(),
Some("adoption_refused")
);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/subscriptions/import/apply");
assert_eq!(
seen[0].body_json(),
json!({"merchant_connector_id":"mca_1","items":[
{"external_subscription_id":"ext_1","customer_id":"cus_1"},
{"external_subscription_id":"ext_2","customer_id":"cus_2",
"connector_customer_id":"cc_2"}]})
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn list_invoices_gets_the_encoded_path_with_paging() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"invoices":[{"id":"inv_1","subscription_id":"sub_1","amount":1000,
"currency":"EUR","status":"paid"}],"surprise_field":1}"#,
)]);
let params = SubscriptionInvoiceListParams::new().limit(10).offset(20);
let out = client
.subscriptions()
.with_profile_id("pro_1")
.list_invoices("sub/1", Some(¶ms))
.await
.unwrap();
assert_eq!(out.invoices[0].id, "inv_1");
assert_eq!(out.invoices[0].amount, 1000);
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/sub%2F1/invoices?limit=10&offset=20"
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[tokio::test]
async fn billing_processor_gets_the_shop_processor() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"merchant_connector_id":"mca_1","connector_name":"paypal","surprise_field":1}"#,
)]);
let out = client
.subscriptions()
.with_profile_id("pro_1")
.billing_processor()
.await
.unwrap();
assert_eq!(out.merchant_connector_id, "mca_1");
assert_eq!(out.connector_name, "paypal");
assert_eq!(out.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/billing_processor"
);
assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
}
#[test]
fn native_shop_config_request_named_fields_are_complete() {
let req = NativeShopConfigRequest::new(true, false).payment_connector_id("mca_1");
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().unwrap().keys() {
assert!(
NATIVE_SHOP_CONFIG_REQUEST_NAMED.contains(&key.as_str()),
"NATIVE_SHOP_CONFIG_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn native_dunning_config_request_named_fields_are_complete() {
let req = NativeDunningConfigRequest::new(true, vec![1], 2, true)
.recovery_mode("buyer_link")
.recovery_after_attempt(1);
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().unwrap().keys() {
assert!(
NATIVE_DUNNING_CONFIG_REQUEST_NAMED.contains(&key.as_str()),
"NATIVE_DUNNING_CONFIG_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn adopt_subscription_request_named_fields_are_complete() {
let req = AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1")
.merchant_connector_id("mca_1")
.connector_customer_id("cc_1")
.item_price_id("price_1")
.plan_id("plan_1")
.merchant_reference_id("ref_1")
.test_mode(true);
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().unwrap().keys() {
assert!(
ADOPT_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()),
"ADOPT_SUBSCRIPTION_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn subscription_import_apply_request_named_fields_are_complete() {
let req = SubscriptionImportApplyRequest::new(
"mca_1",
vec![SubscriptionImportSelection::new("ext_1", "cus_1")],
);
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().unwrap().keys() {
assert!(
SUBSCRIPTION_IMPORT_APPLY_REQUEST_NAMED.contains(&key.as_str()),
"SUBSCRIPTION_IMPORT_APPLY_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn adopt_validate_rejects_colliding_extra_key() {
let mut req = AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1");
req.extra.insert("customer_id".to_string(), json!("cus_2"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("customer_id")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
}