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, Currency, CustomerInfo, ListResponse,
SetupFutureUsage,
};
use crate::core::models::payment::{
PaymentAttemptResponse, PaymentClientContextListResponse, PaymentConnectorSettlementResponse,
PaymentResponse, PaymentStatusHistoryResponse, PaymentsDeleteResponse, ReplayPlaybackResponse,
ReplaySliceResponse,
};
use crate::core::models::payment_detail::{
BuyerRiskEvaluationsResponse, PaymentAgentSignalResponse, PaymentIntegrationTestResponse,
PaymentProductLines, PaymentRoutingDecisionsResponse,
};
use crate::core::models::payment_log::{
PaymentLogConnectorCallDetail, PaymentLogIncomingWebhookDetail,
PaymentLogOutgoingWebhookDetail, PaymentLogsResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct Payments {
inner: Arc<Inner>,
}
impl Payments {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(&self, params: &PaymentCreateRequest) -> Result<PaymentResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, "/payments", Some(&body), &[], None)
.await
}
pub async fn create_idempotent(
&self,
params: &PaymentCreateRequest,
idempotency_key: &str,
) -> Result<PaymentResponse> {
params.validate()?;
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/payments",
Some(&body),
&[],
Some(idempotency_key),
)
.await
}
pub async fn retrieve(&self, payment_id: &str) -> Result<PaymentResponse> {
let path = format!("/payments/{}", encode_segment(payment_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn retrieve_synced(&self, payment_id: &str) -> Result<PaymentResponse> {
let path = format!("/payments/{}", encode_segment(payment_id));
let query = [
("force_sync", "true".to_string()),
("all_keys_required", "true".to_string()),
];
self.inner
.request(HttpMethod::Get, &path, None, &query, None)
.await
}
pub async fn capture(
&self,
payment_id: &str,
params: Option<&PaymentCaptureRequest>,
) -> Result<PaymentResponse> {
let path = format!("/payments/{}/capture", encode_segment(payment_id));
let body: Option<Vec<u8>> = match params {
Some(p) => Some(to_json_vec(p)?),
None => None,
};
self.inner
.request(HttpMethod::Post, &path, body.as_deref(), &[], None)
.await
}
pub async fn cancel(
&self,
payment_id: &str,
params: Option<&PaymentCancelRequest>,
) -> Result<PaymentResponse> {
let path = format!("/payments/{}/cancel", encode_segment(payment_id));
let body: Option<Vec<u8>> = match params {
Some(p) => Some(to_json_vec(p)?),
None => None,
};
self.inner
.request(HttpMethod::Post, &path, body.as_deref(), &[], None)
.await
}
pub async fn list(
&self,
params: Option<&PaymentListParams>,
) -> Result<ListResponse<PaymentResponse>> {
self.list_at("/payments/list", params).await
}
pub async fn update(
&self,
payment_id: &str,
params: &PaymentUpdateRequest,
) -> Result<PaymentResponse> {
params.validate()?;
let path = format!("/payments/{}", encode_segment(payment_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn confirm(
&self,
payment_id: &str,
params: &PaymentConfirmRequest,
) -> Result<PaymentResponse> {
params.validate()?;
let path = format!("/payments/{}/confirm", encode_segment(payment_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn list_attempts(
&self,
payment_id: &str,
) -> Result<ListResponse<PaymentAttemptResponse>> {
let path = format!("/payments/{}/attempts", encode_segment(payment_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn list_status_history(
&self,
payment_id: &str,
) -> Result<PaymentStatusHistoryResponse> {
let path = format!("/payments/{}/status-history", encode_segment(payment_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn settlement(&self, payment_id: &str) -> Result<PaymentConnectorSettlementResponse> {
let path = format!("/payments/{}/settlement", encode_segment(payment_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn open_replay_playback(&self, payment_id: &str) -> Result<ReplayPlaybackResponse> {
let path = format!("/payments/{}/replay/playback", encode_segment(payment_id));
self.inner
.request(HttpMethod::Post, &path, None, &[], None)
.await
}
pub async fn replay_slice(
&self,
payment_id: &str,
playback_id: &str,
sequence: u64,
) -> Result<ReplaySliceResponse> {
let path = format!(
"/payments/{}/replay/playback/{}/slices/{}",
encode_segment(payment_id),
encode_segment(playback_id),
sequence
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn session_tokens(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/payments/session-tokens",
Some(&body),
&[],
None,
)
.await
}
pub async fn cancel_post_capture(
&self,
payment_id: &str,
params: Option<&Value>,
) -> Result<PaymentResponse> {
let path = format!(
"/payments/{}/cancel-post-capture",
encode_segment(payment_id)
);
self.post_value(&path, params).await
}
pub async fn incremental_authorization(
&self,
payment_id: &str,
params: &Value,
) -> Result<PaymentResponse> {
let path = format!(
"/payments/{}/incremental-authorization",
encode_segment(payment_id)
);
self.post_value(&path, Some(params)).await
}
pub async fn extend_authorization(
&self,
payment_id: &str,
params: Option<&Value>,
) -> Result<PaymentResponse> {
let path = format!(
"/payments/{}/extend-authorization",
encode_segment(payment_id)
);
self.post_value(&path, params).await
}
pub async fn complete_authorize(
&self,
payment_id: &str,
params: Option<&Value>,
) -> Result<PaymentResponse> {
let path = format!(
"/payments/{}/complete-authorize",
encode_segment(payment_id)
);
self.post_value(&path, params).await
}
pub async fn update_metadata(
&self,
payment_id: &str,
params: &Value,
) -> Result<PaymentResponse> {
let path = format!("/payments/{}/update-metadata", encode_segment(payment_id));
self.post_value(&path, Some(params)).await
}
pub async fn list_by_profile(
&self,
params: Option<&PaymentListParams>,
) -> Result<ListResponse<PaymentResponse>> {
self.list_at("/payments/profile/list", params).await
}
pub async fn list_by_filter(&self, params: &Value) -> Result<ListResponse<PaymentResponse>> {
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, "/payments/list", Some(&body), &[], None)
.await
}
pub async fn list_by_profile_filter(
&self,
params: &Value,
) -> Result<ListResponse<PaymentResponse>> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/payments/profile/list",
Some(&body),
&[],
None,
)
.await
}
pub async fn filters(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(HttpMethod::Get, "/payments/filter", None, query, None)
.await
}
pub async fn filters_by_profile(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/payments/profile/filter",
None,
query,
None,
)
.await
}
pub async fn list_client_context(
&self,
payment_id: &str,
) -> Result<PaymentClientContextListResponse> {
let path = format!("/payments/{}/client-context", encode_segment(payment_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn delete(&self, payment_id: &str) -> Result<PaymentsDeleteResponse> {
let path = format!("/payments/{}", encode_segment(payment_id));
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn aggregate(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(HttpMethod::Get, "/payments/aggregate", None, query, None)
.await
}
pub async fn aggregate_by_profile(&self, query: &[(&str, String)]) -> Result<Value> {
self.inner
.request(
HttpMethod::Get,
"/payments/profile/aggregate",
None,
query,
None,
)
.await
}
pub async fn manual_update(&self, payment_id: &str, params: &Value) -> Result<PaymentResponse> {
let path = format!("/payments/{}/manual-update", encode_segment(payment_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Put, &path, Some(&body), &[], None)
.await
}
pub async fn approve(
&self,
payment_id: &str,
params: Option<&Value>,
) -> Result<PaymentResponse> {
let path = format!("/payments/{}/approve", encode_segment(payment_id));
self.post_value(&path, params).await
}
pub async fn reject(
&self,
payment_id: &str,
params: Option<&Value>,
) -> Result<PaymentResponse> {
let path = format!("/payments/{}/reject", encode_segment(payment_id));
self.post_value(&path, params).await
}
pub async fn three_ds_authentication(&self, payment_id: &str, params: &Value) -> Result<Value> {
let path = format!(
"/payments/{}/3ds/authentication",
encode_segment(payment_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn abort(
&self,
payment_id: &str,
params: Option<&PaymentAbortRequest>,
) -> Result<PaymentResponse> {
let default = PaymentAbortRequest::default();
let params = params.unwrap_or(&default);
params.validate()?;
let path = payment_sub_path(payment_id, "abort");
let body = to_json_vec(params)?;
self.inner
.request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
.await
}
pub async fn set_integration_test(
&self,
payment_id: &str,
is_integration_test: bool,
) -> Result<PaymentIntegrationTestResponse> {
let path = payment_sub_path(payment_id, "integration-test");
let body = to_json_vec(&PaymentIntegrationTestBody {
is_integration_test,
})?;
self.inner
.request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
.await
}
pub async fn buyer_risk(&self, payment_id: &str) -> Result<BuyerRiskEvaluationsResponse> {
self.get_sub(payment_id, "buyer-risk").await
}
pub async fn agent_signal(&self, payment_id: &str) -> Result<PaymentAgentSignalResponse> {
self.get_sub(payment_id, "agent-signal").await
}
pub async fn product_lines(&self, payment_id: &str) -> Result<PaymentProductLines> {
self.get_sub(payment_id, "lines").await
}
pub async fn routing_decisions(
&self,
payment_id: &str,
) -> Result<PaymentRoutingDecisionsResponse> {
self.get_sub(payment_id, "routing-decisions").await
}
pub async fn list_logs(&self, payment_id: &str) -> Result<PaymentLogsResponse> {
self.get_sub(payment_id, "logs").await
}
pub async fn log_connector_call(
&self,
payment_id: &str,
call_id: &str,
) -> Result<PaymentLogConnectorCallDetail> {
let path = format!(
"{}/{}",
payment_sub_path(payment_id, "logs/connector-calls"),
encode_segment(call_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn log_incoming_webhook(
&self,
payment_id: &str,
event_id: &str,
) -> Result<PaymentLogIncomingWebhookDetail> {
let path = format!(
"{}/{}",
payment_sub_path(payment_id, "logs/incoming-webhooks"),
encode_segment(event_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn log_outgoing_webhook(
&self,
payment_id: &str,
initial_attempt_id: &str,
) -> Result<PaymentLogOutgoingWebhookDetail> {
let path = format!(
"{}/{}",
payment_sub_path(payment_id, "logs/outgoing-webhooks"),
encode_segment(initial_attempt_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
async fn get_sub<T: serde::de::DeserializeOwned>(
&self,
payment_id: &str,
suffix: &str,
) -> Result<T> {
let path = payment_sub_path(payment_id, suffix);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
async fn list_at(
&self,
path: &str,
params: Option<&PaymentListParams>,
) -> Result<ListResponse<PaymentResponse>> {
let query = params.map(PaymentListParams::to_query).unwrap_or_default();
let q: Vec<(&str, String)> = query.iter().map(|(k, v)| (*k, v.clone())).collect();
self.inner
.request(HttpMethod::Get, path, None, &q, None)
.await
}
async fn post_value(&self, path: &str, params: Option<&Value>) -> Result<PaymentResponse> {
let body: Option<Vec<u8>> = match params {
Some(p) => Some(to_json_vec(p)?),
None => None,
};
self.inner
.request(HttpMethod::Post, path, body.as_deref(), &[], None)
.await
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentCreateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<Currency>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub price_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub addons: Option<Vec<PaymentAddonChoice>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_order_reference_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_link: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub confirm: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub session_expiry: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture_method: Option<CaptureMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount_to_capture: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub authentication_type: Option<AuthenticationType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<CustomerInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub setup_future_usage: Option<SetupFutureUsage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub off_session: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mandate_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub statement_descriptor_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[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>,
}
const PAYMENT_CREATE_REQUEST_NAMED: &[&str] = &[
"amount",
"currency",
"product_id",
"price_id",
"addons",
"order_details",
"merchant_order_reference_id",
"locale",
"cancel_url",
"payment_id",
"profile_id",
"payment_link",
"confirm",
"return_url",
"session_expiry",
"description",
"capture_method",
"amount_to_capture",
"authentication_type",
"customer_id",
"customer",
"email",
"name",
"connector",
"setup_future_usage",
"off_session",
"mandate_id",
"statement_descriptor_name",
"billing",
"shipping",
"metadata",
"test_mode",
];
impl ValidateRequest for PaymentCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PAYMENT_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on PaymentCreateRequest"
)));
}
}
Ok(())
}
}
impl PaymentCreateRequest {
pub fn new(amount: i64, currency: impl Into<Currency>) -> Self {
Self {
amount: Some(amount),
currency: Some(currency.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 price(mut self, price_id: impl Into<String>) -> Self {
self.price_id = Some(price_id.into());
self
}
#[must_use]
pub fn addons(mut self, addons: Vec<PaymentAddonChoice>) -> Self {
self.addons = Some(addons);
self
}
#[must_use]
pub fn order_details(mut self, order_details: Vec<OrderDetailsWithAmount>) -> Self {
self.order_details = Some(order_details);
self
}
#[must_use]
pub fn merchant_order_reference_id(mut self, reference: impl Into<String>) -> Self {
self.merchant_order_reference_id = Some(reference.into());
self
}
#[must_use]
pub fn locale(mut self, locale: impl Into<String>) -> Self {
self.locale = Some(locale.into());
self
}
#[must_use]
pub fn cancel_url(mut self, url: impl Into<String>) -> Self {
self.cancel_url = Some(url.into());
self
}
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
pub fn payment_link(mut self, enabled: bool) -> Self {
self.payment_link = Some(enabled);
self
}
pub fn return_url(mut self, url: impl Into<String>) -> Self {
self.return_url = Some(url.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn customer_email(mut self, email: impl Into<String>) -> Self {
self.email = Some(email.into());
self
}
pub fn customer_id(mut self, customer_id: impl Into<String>) -> Self {
self.customer_id = Some(customer_id.into());
self
}
pub fn metadata(mut self, metadata: Value) -> Self {
self.metadata = Some(metadata);
self
}
pub fn test_mode(mut self, enabled: bool) -> Self {
self.test_mode = Some(enabled);
self
}
pub fn billing_address(mut self, address: Address) -> Self {
self.billing = serde_json::to_value(address).ok();
self
}
pub fn shipping_address(mut self, address: Address) -> Self {
self.shipping = serde_json::to_value(address).ok();
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentAddonChoice {
pub price_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub quantity: Option<i32>,
}
impl PaymentAddonChoice {
pub fn new(price_id: impl Into<String>) -> Self {
Self {
price_id: price_id.into(),
quantity: None,
}
}
#[must_use]
pub fn quantity(mut self, quantity: i32) -> Self {
self.quantity = Some(quantity);
self
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct OrderDetailsWithAmount {
pub product_name: String,
pub quantity: i32,
pub amount: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_img_link: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_rate: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub total_tax_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub requires_shipping: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub category: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_category: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub brand: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_tax_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sku: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub upc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commodity_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit_of_measure: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub total_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unit_discount_amount: Option<i64>,
}
impl OrderDetailsWithAmount {
pub fn new(product_name: impl Into<String>, quantity: i32, amount: i64) -> Self {
Self {
product_name: product_name.into(),
quantity,
amount,
..Default::default()
}
}
#[must_use]
pub fn product_img_link(mut self, url: impl Into<String>) -> Self {
self.product_img_link = Some(url.into());
self
}
}
#[derive(Debug, Clone, Default)]
pub struct PaymentListParams {
pub limit: Option<i64>,
pub offset: Option<i64>,
pub customer_id: Option<String>,
pub created_gte: Option<String>,
pub created_lte: Option<String>,
}
impl PaymentListParams {
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.customer_id {
q.push(("customer_id", v.clone()));
}
if let Some(v) = &self.created_gte {
q.push(("created.gte", v.clone()));
}
if let Some(v) = &self.created_lte {
q.push(("created.lte", v.clone()));
}
q
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<Currency>,
#[serde(skip_serializing_if = "Option::is_none")]
pub order_tax_amount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub amount_to_capture: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping_cost: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub routing: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector: Option<Vec<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 billing: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
pub confirm: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub statement_descriptor_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub statement_descriptor_suffix: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Address>,
#[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 payment_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub setup_future_usage: Option<SetupFutureUsage>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_country_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_url: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const PAYMENT_UPDATE_REQUEST_NAMED: &[&str] = &[
"amount",
"currency",
"order_tax_amount",
"amount_to_capture",
"shipping_cost",
"routing",
"connector",
"capture_method",
"authentication_type",
"billing",
"confirm",
"customer_id",
"description",
"return_url",
"statement_descriptor_name",
"statement_descriptor_suffix",
"metadata",
"shipping",
"payment_method",
"payment_method_type",
"payment_method_data",
"payment_token",
"setup_future_usage",
"profile_id",
"email",
"name",
"phone",
"phone_country_code",
"cancel_url",
];
impl ValidateRequest for PaymentUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PAYMENT_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on PaymentUpdateRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentConfirmRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
#[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 payment_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: 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 mandate_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub off_session: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_country_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub browser_info: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture_method: Option<CaptureMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub cancel_url: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
const PAYMENT_CONFIRM_REQUEST_NAMED: &[&str] = &[
"client_secret",
"payment_method",
"payment_method_type",
"payment_method_data",
"payment_token",
"return_url",
"billing",
"shipping",
"mandate_id",
"off_session",
"customer_id",
"email",
"name",
"phone",
"phone_country_code",
"browser_info",
"capture_method",
"metadata",
"cancel_url",
];
impl ValidateRequest for PaymentConfirmRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PAYMENT_CONFIRM_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on PaymentConfirmRequest"
)));
}
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentCaptureRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub amount_to_capture: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub statement_descriptor_name: Option<String>,
}
fn payment_sub_path(payment_id: &str, suffix: &str) -> String {
format!("/payments/{}/{suffix}", encode_segment(payment_id))
}
#[derive(Debug, Serialize)]
struct PaymentIntegrationTestBody {
is_integration_test: bool,
}
pub const MAX_ABORT_REASON_CHARS: usize = 255;
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentAbortRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl PaymentAbortRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn reason(mut self, reason: impl Into<String>) -> Self {
self.reason = Some(reason.into());
self
}
}
const PAYMENT_ABORT_REQUEST_NAMED: &[&str] = &["reason"];
impl ValidateRequest for PaymentAbortRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PAYMENT_ABORT_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on PaymentAbortRequest"
)));
}
}
if self
.reason
.as_deref()
.is_some_and(|reason| reason.chars().count() > MAX_ABORT_REASON_CHARS)
{
return Err(DelopayError::InvalidRequest(format!(
"`reason` must hold at most {MAX_ABORT_REASON_CHARS} characters"
)));
}
Ok(())
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentCancelRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub cancellation_reason: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const ABORTED_JSON: &str = r#"{
"payment_id": "pay_1", "merchant_id": "mer_1", "status": "aborted",
"amount": 1000, "currency": "EUR"
}"#;
#[tokio::test]
async fn abort_posts_the_reason_or_an_empty_object() {
let (client, mock) = client_with(vec![Step::ok(ABORTED_JSON), Step::ok(ABORTED_JSON)]);
let payments = client.payments();
let out = payments
.abort(
"pay/1",
Some(&PaymentAbortRequest::new().reason("order_cancelled")),
)
.await
.unwrap();
assert_eq!(out.status, "aborted");
payments.abort("pay/1", None).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/pay%2F1/abort");
assert_eq!(seen[0].body_json(), json!({"reason": "order_cancelled"}));
assert_eq!(seen[1].body_json(), json!({}));
}
#[tokio::test]
async fn abort_is_not_retried_on_a_server_error() {
let (client, mock) =
client_with_retries(vec![Step::status(503, "{}"), Step::ok(ABORTED_JSON)], 2);
assert!(client.payments().abort("pay_1", None).await.is_err());
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[test]
fn abort_validate_refuses_a_long_reason_and_colliding_extra() {
let long = PaymentAbortRequest::new().reason("x".repeat(MAX_ABORT_REASON_CHARS + 1));
assert!(matches!(
long.validate(),
Err(DelopayError::InvalidRequest(msg)) if msg.contains("reason")
));
assert!(
PaymentAbortRequest::new()
.reason("x".repeat(MAX_ABORT_REASON_CHARS))
.validate()
.is_ok()
);
let mut colliding = PaymentAbortRequest::new();
colliding.extra.insert("reason".to_string(), json!("other"));
assert!(matches!(
colliding.validate(),
Err(DelopayError::InvalidRequest(msg)) if msg.contains("collides")
));
}
#[test]
fn payment_abort_request_named_fields_are_complete() {
let value = serde_json::to_value(PaymentAbortRequest::new().reason("r")).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
PAYMENT_ABORT_REQUEST_NAMED.contains(&key.as_str()),
"PAYMENT_ABORT_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[tokio::test]
async fn set_integration_test_posts_the_mark() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","is_integration_test":true,"changed":false,"surprise_field":1}"#,
)]);
let out = client
.payments()
.set_integration_test("pay/1", true)
.await
.unwrap();
assert!(out.is_integration_test);
assert!(!out.changed);
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/payments/pay%2F1/integration-test"
);
assert_eq!(seen[0].body_json(), json!({"is_integration_test": true}));
}
#[tokio::test]
async fn buyer_risk_gets_the_buyer_risk_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"evaluations":[{
"score": 72, "band": "high", "action": "require_three_ds",
"applied_action": "allow", "action_reason": "merchant_initiated",
"reasons": [{"signal": "network_vpn", "points": 30, "value": 1, "threshold": 1,
"detail": {"source": "ip"}}],
"model_version": "p3.m1", "merchant_initiated": true,
"evaluated_at": "2026-09-01T00:00:00Z", "surprise_field": 1
}]}"#,
)]);
let out = client.payments().buyer_risk("pay/1").await.unwrap();
let evaluation = &out.evaluations[0];
assert_eq!(evaluation.score, 72);
assert_eq!(evaluation.applied_action, "allow");
assert_eq!(evaluation.reasons[0].signal, "network_vpn");
assert_eq!(evaluation.reasons[0].detail, Some(json!({"source": "ip"})));
assert_eq!(evaluation.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/payments/pay%2F1/buyer-risk");
}
#[tokio::test]
async fn agent_signal_gets_the_agent_signal_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","classification":"verified_agent","agent_operator":"Acme Agents",
"agent_protocol":"web_bot_auth","key_id":"thumb_1","reason":null,"stage":"confirm",
"recorded_at":"2026-09-01T00:00:00Z","surprise_field":1}"#,
)]);
let out = client.payments().agent_signal("pay/1").await.unwrap();
assert_eq!(out.classification, "verified_agent");
assert_eq!(out.agent_protocol.as_deref(), Some("web_bot_auth"));
assert!(out.reason.is_none());
assert_eq!(out.stage, "confirm");
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/payments/pay%2F1/agent-signal"
);
}
#[tokio::test]
async fn product_lines_gets_the_lines_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","currency":"EUR","lines_total":1500,"amount_difference":0,
"lines":[{"id":"pli_1","product_id":"prod_1","attributed":true,"name":"Hat",
"quantity":2,"unit_amount":750,"line_total":1500,"currency":"EUR",
"tax_rate":null,"tax_amount":null,"role":"product","addon_choice":"open",
"refunds":{"refunded_quantity":1,"refunded_amount":750,"pending_quantity":0,
"pending_amount":0,"refundable_quantity":1,"refundable_amount":750},
"line_surprise":1}],
"surprise_field":1}"#,
)]);
let out = client.payments().product_lines("pay/1").await.unwrap();
assert_eq!(out.lines_total, Some(1500));
assert!(out.tax_total.is_none());
let line = &out.lines[0];
assert_eq!(line.quantity, 2);
assert_eq!(line.role, "product");
assert_eq!(line.refunds.as_ref().unwrap().refundable_amount, 750);
assert_eq!(line.extra["line_surprise"], 1);
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/payments/pay%2F1/lines");
}
#[tokio::test]
async fn routing_decisions_gets_the_routing_decisions_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","count":2,"attempts":[
{"attempt_id":"att_1","connector":"stripe","merchant_connector_id":"mca_1",
"decision":{"decision_kind":"volume_split","algorithm_id":"algo_1",
"algorithm_version":3,"decided_at":1767225600,
"candidates":[{"connector":"stripe","origin":"routed","eliminated_by":null},
{"connector":"adyen","origin":"fallback","eliminated_by":"eligibility"}],
"volume_split":[{"connector":"stripe","split":70,"drawn":true}],
"volume_counters":[{"key":null,"window":"day","scope":"merchant","value":5000,"rules":["r1"]}],
"decision_surprise":1}},
{"attempt_id":"att_2","decision":null}
],"surprise_field":1}"#,
)]);
let out = client.payments().routing_decisions("pay/1").await.unwrap();
assert_eq!(out.count, 2);
let decision = out.attempts[0].decision.as_ref().unwrap();
assert_eq!(decision.decision_kind, "volume_split");
assert_eq!(decision.algorithm_version, Some(3));
assert_eq!(
decision.candidates[1].eliminated_by.as_deref(),
Some("eligibility")
);
assert!(decision.volume_split.as_ref().unwrap()[0].drawn);
assert_eq!(
decision.volume_counters.as_ref().unwrap()[0].value,
Some(5000)
);
assert_eq!(decision.extra["decision_surprise"], 1);
assert!(out.attempts[1].decision.is_none());
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/payments/pay%2F1/routing-decisions"
);
}
const CONNECTOR_CALL_JSON: &str = r#"{
"id": "cc_1", "started_at": "2026-09-01T00:00:00Z", "connector": "stripe",
"flow": "Authorize", "method": "POST", "url": "https://psp.test/v1/charges",
"status_code": 200, "latency_ms": 321, "attempt_id": "att_1", "refund_id": null,
"dispute_id": null, "request_id": "req_1", "test_mode": true, "has_error": false
}"#;
const INCOMING_WEBHOOK_JSON: &str = r#"{
"event_id": "iw_1", "received_at": "2026-09-01T00:00:01Z", "connector": "stripe",
"provider_event_id": "evt_1", "provider_event_type": "payment_intent.succeeded",
"mapped_event_type": "payment_succeeded", "object_type": "payment_intent",
"object_ref_id": "pi_1", "resolved_attempt_id": "att_1", "source_verified": true,
"outcome": "applied", "outcome_detail": null, "response_status": 200,
"latency_ms": 12, "test_mode": true
}"#;
#[tokio::test]
async fn list_logs_gets_the_logs_path() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{
"payment_id": "pay_1", "psp_traffic_recorded": true,
"processor_details_hidden": false, "connector_call_retention_days": 30,
"incoming_webhook_retention_days": 90,
"connector_calls": [{CONNECTOR_CALL_JSON}], "connector_calls_truncated": false,
"incoming_webhooks": [{INCOMING_WEBHOOK_JSON}], "incoming_webhooks_truncated": true,
"outgoing_webhooks": [{{
"initial_attempt_id": "ow_1", "event_type": "payment_succeeded",
"object_id": "pay_1", "created_at": "2026-09-01T00:00:02Z",
"is_delivery_successful": true, "delivery_terminal_reason": null,
"test_mode": true,
"attempts": [{{"event_id": "ow_1", "created_at": "2026-09-01T00:00:02Z",
"delivery_attempt": "initial_attempt", "is_webhook_notified": true,
"status_code": 200}}]
}}],
"outgoing_webhooks_truncated": false,
"surprise_field": 1
}}"#
))]);
let out = client.payments().list_logs("pay/1").await.unwrap();
assert!(out.psp_traffic_recorded);
assert_eq!(out.connector_calls[0].latency_ms, 321);
assert!(out.connector_calls[0].refund_id.is_none());
assert_eq!(out.incoming_webhooks[0].outcome, "applied");
assert!(out.incoming_webhooks_truncated);
assert_eq!(out.outgoing_webhooks[0].attempts[0].status_code, Some(200));
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/payments/pay%2F1/logs");
}
#[tokio::test]
async fn log_connector_call_gets_the_call_path() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"call": {CONNECTOR_CALL_JSON}, "request": {{"amount": "****"}},
"response": "not json", "error": null, "surprise_field": 1}}"#
))]);
let out = client
.payments()
.log_connector_call("pay/1", "cc/1")
.await
.unwrap();
assert_eq!(out.call.id, "cc_1");
assert_eq!(out.request, Some(json!({"amount": "****"})));
assert_eq!(out.response, Some(json!("not json")));
assert!(out.error.is_none());
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/payments/pay%2F1/logs/connector-calls/cc%2F1"
);
}
#[tokio::test]
async fn log_incoming_webhook_gets_the_webhook_path() {
let (client, mock) = client_with(vec![Step::ok(&format!(
r#"{{"webhook": {INCOMING_WEBHOOK_JSON}, "headers": {{"stripe-signature": "t=1,v1=****"}},
"body": {{"id": "evt_1"}}, "verification_detail": {{"secret": "primary"}},
"surprise_field": 1}}"#
))]);
let out = client
.payments()
.log_incoming_webhook("pay/1", "iw/1")
.await
.unwrap();
assert_eq!(out.webhook.event_id, "iw_1");
assert_eq!(out.body, Some(json!({"id": "evt_1"})));
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/payments/pay%2F1/logs/incoming-webhooks/iw%2F1"
);
}
#[tokio::test]
async fn log_outgoing_webhook_gets_the_delivery_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"initial_attempt_id":"ow_1","attempts":[{
"event_id":"ow_1","created_at":"2026-09-01T00:00:02Z",
"delivery_attempt":"automatic_retry","is_webhook_notified":false,
"request_headers":[{"name":"content-type","value":"application/json"}],
"request_body":{"type":"payment_succeeded"},"response_status_code":null,
"response_headers":[],"response_body":null,"error_message":"timed out"
}],"surprise_field":1}"#,
)]);
let out = client
.payments()
.log_outgoing_webhook("pay/1", "ow/1")
.await
.unwrap();
let delivery = &out.attempts[0];
assert_eq!(
delivery.delivery_attempt.as_deref(),
Some("automatic_retry")
);
assert_eq!(delivery.request_headers[0].name, "content-type");
assert!(delivery.response_status_code.is_none());
assert_eq!(delivery.error_message.as_deref(), Some("timed out"));
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/payments/pay%2F1/logs/outgoing-webhooks/ow%2F1"
);
}
#[tokio::test]
async fn settlement_reads_the_payment_settlement_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","count":1,"attempts":[{"attempt_id":"att_1","attempt_status":"charged","status":"available","available_on":"2026-09-14T00:00:00Z"}]}"#,
)]);
let out = client.payments().settlement("pay/1").await.unwrap();
assert_eq!(out.count, 1);
assert_eq!(out.attempts[0].status, "available");
assert_eq!(out.attempts[0].paid_out_at, None);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/payments/pay%2F1/settlement");
}
#[tokio::test]
async fn replay_playback_posts_and_slices_read_under_it() {
let (client, mock) = client_with(vec![
Step::ok(
r#"{"playback_id":"pb_1","total_events":4,"has_redirect_gap":true,"slices":[{"sequence":0,"event_count":4,"byte_size":10,"first_event_at":1,"last_event_at":2}]}"#,
),
Step::ok(r#"{"sequence":0,"events":[{"type":2}]}"#),
]);
let manifest = client
.payments()
.open_replay_playback("pay_1")
.await
.unwrap();
assert_eq!(manifest.playback_id, "pb_1");
assert!(manifest.has_redirect_gap);
let slice = client
.payments()
.replay_slice("pay_1", "pb_1", manifest.slices[0].sequence)
.await
.unwrap();
assert_eq!(slice.events.len(), 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/payments/pay_1/replay/playback"
);
assert_eq!(seen[1].method, "GET");
assert_eq!(
seen[1].url,
"https://api.test/payments/pay_1/replay/playback/pb_1/slices/0"
);
}
fn full_payment_create_request() -> PaymentCreateRequest {
PaymentCreateRequest {
amount: Some(100),
currency: Some("EUR".to_string()),
product_id: Some("prod_1".to_string()),
price_id: Some("price_1".to_string()),
addons: Some(vec![PaymentAddonChoice::new("price_2").quantity(1)]),
order_details: Some(vec![OrderDetailsWithAmount::new("Hat", 1, 100)]),
merchant_order_reference_id: Some("order_1".to_string()),
locale: Some("de".to_string()),
cancel_url: Some("https://example.com/cart".to_string()),
payment_id: Some("pay_1".to_string()),
profile_id: Some("pro_1".to_string()),
payment_link: Some(true),
confirm: Some(true),
return_url: Some("https://example.com/return".to_string()),
session_expiry: Some(900),
description: Some("a description".to_string()),
capture_method: Some(CaptureMethod::Automatic),
amount_to_capture: Some(50),
authentication_type: Some(AuthenticationType::ThreeDs),
customer_id: Some("cus_1".to_string()),
customer: Some(CustomerInfo::default()),
email: Some("ada@example.com".to_string()),
name: Some("Ada".to_string()),
connector: Some(vec!["stripe".to_string()]),
setup_future_usage: Some(SetupFutureUsage::OffSession),
off_session: Some(true),
mandate_id: Some("man_1".to_string()),
statement_descriptor_name: Some("STMT".to_string()),
billing: Some(json!({"address": {"country": "DE"}})),
shipping: Some(json!({"address": {"country": "DE"}})),
metadata: Some(json!({"order_id": "o_1"})),
test_mode: Some(true),
extra: serde_json::Map::new(),
}
}
#[tokio::test]
async fn a_product_payment_sends_the_product_and_no_amount() {
let (client, mock) = client_with(vec![Step::ok(PAYMENT_JSON)]);
let req = PaymentCreateRequest::for_product("prod_1")
.price("price_1")
.addons(vec![PaymentAddonChoice::new("price_gift").quantity(2)])
.cancel_url("https://shop.test/cart")
.locale("de")
.merchant_order_reference_id("order_9");
client.payments().create(&req).await.unwrap();
let body = mock.seen.lock().unwrap()[0].body_json();
assert_eq!(
body,
json!({
"product_id": "prod_1",
"price_id": "price_1",
"addons": [{"price_id": "price_gift", "quantity": 2}],
"cancel_url": "https://shop.test/cart",
"locale": "de",
"merchant_order_reference_id": "order_9"
})
);
assert!(body.get("amount").is_none());
assert!(body.get("currency").is_none());
}
#[test]
fn order_details_serialize_only_the_set_fields() {
let req = PaymentCreateRequest::new(1500, "EUR").order_details(vec![
OrderDetailsWithAmount::new("Hat", 2, 750).product_img_link("https://cdn.test/h.png"),
]);
let value = serde_json::to_value(&req).unwrap();
assert_eq!(value["amount"], 1500);
assert_eq!(
value["order_details"],
json!([{
"product_name": "Hat",
"quantity": 2,
"amount": 750,
"product_img_link": "https://cdn.test/h.png"
}])
);
}
#[test]
fn payment_create_request_named_fields_are_complete() {
let value = serde_json::to_value(full_payment_create_request()).unwrap();
let obj = value.as_object().expect("serializes to a JSON object");
for key in obj.keys() {
assert!(
PAYMENT_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"PAYMENT_CREATE_REQUEST_NAMED is missing wire key `{key}` -- \
add it, or PaymentCreateRequest's extra-key collision guard \
will silently stop covering this field"
);
}
}
#[test]
fn validate_rejects_extra_key_colliding_with_named_field() {
let mut req = PaymentCreateRequest::new(100, "EUR");
req.extra.insert("amount".to_string(), json!(999));
let err = req.validate().unwrap_err();
match err {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("amount")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[test]
fn validate_allows_non_colliding_extra_key() {
let mut req = PaymentCreateRequest::new(100, "EUR");
req.extra
.insert("custom_field".to_string(), json!("custom_value"));
req.validate().expect("non-colliding extra key is valid");
let value = serde_json::to_value(&req).unwrap();
assert_eq!(value["custom_field"], json!("custom_value"));
}
fn full_payment_update_request() -> PaymentUpdateRequest {
PaymentUpdateRequest {
amount: Some(100),
currency: Some("EUR".to_string()),
order_tax_amount: Some(10),
amount_to_capture: Some(50),
shipping_cost: Some(5),
routing: Some(json!({"type": "single"})),
connector: Some(vec!["stripe".to_string()]),
capture_method: Some(CaptureMethod::Manual),
authentication_type: Some(AuthenticationType::ThreeDs),
billing: Some(Address::default()),
confirm: Some(true),
customer_id: Some("cus_1".to_string()),
description: Some("desc".to_string()),
return_url: Some("https://example.com/r".to_string()),
statement_descriptor_name: Some("STMT".to_string()),
statement_descriptor_suffix: Some("SFX".to_string()),
metadata: Some(json!({"k": "v"})),
shipping: Some(Address::default()),
payment_method: Some("card".to_string()),
payment_method_type: Some("credit".to_string()),
payment_method_data: Some(json!({"card": {}})),
payment_token: Some("tok_1".to_string()),
setup_future_usage: Some(SetupFutureUsage::OffSession),
profile_id: Some("pro_1".to_string()),
email: Some("ada@example.com".to_string()),
name: Some("Ada".to_string()),
phone: Some("5551234".to_string()),
phone_country_code: Some("+49".to_string()),
cancel_url: Some("https://example.com/cart".to_string()),
extra: serde_json::Map::new(),
}
}
#[test]
fn payment_update_request_named_fields_are_complete() {
let value = serde_json::to_value(full_payment_update_request()).unwrap();
let obj = value.as_object().expect("serializes to a JSON object");
for key in obj.keys() {
assert!(
PAYMENT_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"PAYMENT_UPDATE_REQUEST_NAMED is missing wire key `{key}` -- \
add it, or PaymentUpdateRequest's extra-key collision guard \
will silently stop covering this field"
);
}
}
#[test]
fn payment_update_validate_rejects_colliding_extra_key() {
let mut req = PaymentUpdateRequest::default();
req.extra.insert("amount".to_string(), json!(1));
assert!(matches!(
req.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
fn full_payment_confirm_request() -> PaymentConfirmRequest {
PaymentConfirmRequest {
client_secret: Some("cs_1".to_string()),
payment_method: Some("card".to_string()),
payment_method_type: Some("credit".to_string()),
payment_method_data: Some(json!({"card": {}})),
payment_token: Some("tok_1".to_string()),
return_url: Some("https://example.com/r".to_string()),
billing: Some(Address::default()),
shipping: Some(Address::default()),
mandate_id: Some("man_1".to_string()),
off_session: Some(true),
customer_id: Some("cus_1".to_string()),
email: Some("ada@example.com".to_string()),
name: Some("Ada".to_string()),
phone: Some("5551234".to_string()),
phone_country_code: Some("+49".to_string()),
browser_info: Some(json!({"user_agent": "ua"})),
capture_method: Some(CaptureMethod::Automatic),
metadata: Some(json!({"k": "v"})),
cancel_url: Some("https://example.com/cart".to_string()),
extra: serde_json::Map::new(),
}
}
#[test]
fn payment_confirm_request_named_fields_are_complete() {
let value = serde_json::to_value(full_payment_confirm_request()).unwrap();
let obj = value.as_object().expect("serializes to a JSON object");
for key in obj.keys() {
assert!(
PAYMENT_CONFIRM_REQUEST_NAMED.contains(&key.as_str()),
"PAYMENT_CONFIRM_REQUEST_NAMED is missing wire key `{key}` -- \
add it, or PaymentConfirmRequest's extra-key collision guard \
will silently stop covering this field"
);
}
}
#[test]
fn payment_confirm_validate_rejects_colliding_extra_key() {
let mut req = PaymentConfirmRequest::default();
req.extra.insert("payment_token".to_string(), json!("t"));
assert!(matches!(
req.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
#[tokio::test]
async fn update_posts_to_the_payment_path() {
let (client, mock) = client_with(vec![Step::ok(PAYMENT_JSON)]);
let req = PaymentUpdateRequest {
amount: Some(700),
..Default::default()
};
client.payments().update("pay_1", &req).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/pay_1");
assert_eq!(seen[0].body_json()["amount"], 700);
}
#[tokio::test]
async fn confirm_posts_to_the_confirm_path() {
let (client, mock) = client_with(vec![Step::ok(PAYMENT_JSON)]);
let req = PaymentConfirmRequest {
payment_token: Some("tok_1".to_string()),
..Default::default()
};
client.payments().confirm("pay_1", &req).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/pay_1/confirm");
assert_eq!(seen[0].body_json()["payment_token"], "tok_1");
}
#[tokio::test]
async fn list_attempts_gets_the_attempts_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"size":1,"data":[{"attempt_id":"att_1","status":"charged"}]}"#,
)]);
let out = client.payments().list_attempts("pay_1").await.unwrap();
assert_eq!(out.data[0].attempt_id, "att_1");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/payments/pay_1/attempts");
}
#[tokio::test]
async fn list_status_history_gets_the_status_history_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","complete":true,"count":1,
"events":[{"entity_type":"payment","timestamp":"2026-08-01T10:00:00Z",
"status":"succeeded","is_creation":false,"derived":false}]}"#,
)]);
let history = client
.payments()
.list_status_history("pay_1")
.await
.unwrap();
assert!(history.complete);
assert_eq!(history.events[0].entity_type, "payment");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/payments/pay_1/status-history"
);
}
#[tokio::test]
async fn advanced_operations_hit_their_documented_paths() {
let steps = vec![
Step::ok(r#"{"token":"st_1"}"#),
Step::ok(PAYMENT_JSON),
Step::ok(PAYMENT_JSON),
Step::ok(PAYMENT_JSON),
Step::ok(PAYMENT_JSON),
Step::ok(PAYMENT_JSON),
Step::ok(r#"{"trans_status":"Y"}"#),
];
let (client, mock) = client_with(steps);
let p = client.payments();
let body = json!({"k": "v"});
p.session_tokens(&body).await.unwrap();
p.cancel_post_capture("pay_1", None).await.unwrap();
p.incremental_authorization("pay_1", &body).await.unwrap();
p.extend_authorization("pay_1", None).await.unwrap();
p.complete_authorize("pay_1", Some(&body)).await.unwrap();
p.update_metadata("pay_1", &body).await.unwrap();
p.three_ds_authentication("pay_1", &body).await.unwrap();
let expected = [
("POST", "https://api.test/payments/session-tokens"),
(
"POST",
"https://api.test/payments/pay_1/cancel-post-capture",
),
(
"POST",
"https://api.test/payments/pay_1/incremental-authorization",
),
(
"POST",
"https://api.test/payments/pay_1/extend-authorization",
),
("POST", "https://api.test/payments/pay_1/complete-authorize"),
("POST", "https://api.test/payments/pay_1/update-metadata"),
("POST", "https://api.test/payments/pay_1/3ds/authentication"),
];
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), expected.len());
for (i, (method, url)) in expected.iter().enumerate() {
assert_eq!(seen[i].method, *method, "wrong verb at call {i}");
assert_eq!(seen[i].url, *url, "wrong URL at call {i}");
}
}
#[tokio::test]
async fn list_by_profile_gets_the_profile_list_path_with_query() {
let (client, mock) = client_with(vec![Step::ok(LIST_JSON)]);
let params = PaymentListParams {
limit: Some(25),
customer_id: Some("cus_1".to_string()),
..Default::default()
};
client
.payments()
.list_by_profile(Some(¶ms))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/payments/profile/list?limit=25&customer_id=cus_1"
);
}
#[tokio::test]
async fn list_by_filter_posts_the_filter_body() {
let (client, mock) = client_with(vec![Step::ok(LIST_JSON)]);
client
.payments()
.list_by_filter(&json!({"status": ["succeeded"]}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/list");
assert_eq!(seen[0].body_json()["status"][0], "succeeded");
}
#[tokio::test]
async fn filters_gets_the_filter_path_with_query() {
let (client, mock) = client_with(vec![Step::ok(r#"{"connector":["stripe"]}"#)]);
client
.payments()
.filters(&[("profile_id", "pro_1".to_string())])
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/payments/filter?profile_id=pro_1"
);
}
#[tokio::test]
async fn aggregate_gets_the_aggregate_path_with_query() {
let (client, mock) = client_with(vec![Step::ok(r#"{"count":3}"#)]);
client
.payments()
.aggregate(&[("time_range", "7d".to_string())])
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/payments/aggregate?time_range=7d"
);
}
#[tokio::test]
async fn aggregate_by_profile_gets_the_profile_aggregate_path() {
let (client, mock) = client_with(vec![Step::ok(r#"{"count":3}"#)]);
client.payments().aggregate_by_profile(&[]).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/payments/profile/aggregate");
}
#[tokio::test]
async fn manual_update_puts_to_the_manual_update_path() {
let (client, mock) = client_with(vec![Step::ok(PAYMENT_JSON)]);
client
.payments()
.manual_update("pay/1", &json!({"status": "charged"}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(
seen[0].url,
"https://api.test/payments/pay%2F1/manual-update"
);
assert_eq!(seen[0].body_json()["status"], "charged");
}
#[tokio::test]
async fn approve_posts_to_the_approve_path_with_its_body() {
let (client, mock) = client_with(vec![Step::ok(PAYMENT_JSON)]);
client
.payments()
.approve("pay_1", Some(&json!({"reason": "manual review"})))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/pay_1/approve");
assert_eq!(seen[0].body_json()["reason"], "manual review");
}
#[tokio::test]
async fn reject_posts_to_the_reject_path_with_its_body() {
let (client, mock) = client_with(vec![Step::ok(PAYMENT_JSON)]);
client
.payments()
.reject("pay_1", Some(&json!({"reason": "fraud"})))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/pay_1/reject");
assert_eq!(seen[0].body_json()["reason"], "fraud");
}
#[tokio::test]
async fn list_by_profile_filter_posts_to_the_profile_list_path() {
let (client, mock) = client_with(vec![Step::ok(LIST_JSON)]);
client
.payments()
.list_by_profile_filter(&json!({"limit": 20}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/profile/list");
assert_eq!(seen[0].body_json()["limit"], 20);
}
#[tokio::test]
async fn filters_by_profile_uses_the_profile_scoped_path() {
let (client, mock) = client_with(vec![Step::ok("{}")]);
client.payments().filters_by_profile(&[]).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/payments/profile/filter");
}
#[tokio::test]
async fn list_client_context_decodes_the_observations() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","count":1,"data":[{"source":"checkout_open",
"device_model":"iPhone","extra":{"screen":"390x844"},
"created_at":"2026-08-01T00:00:00Z"}]}"#,
)]);
let out = client
.payments()
.list_client_context("pay/1")
.await
.unwrap();
assert_eq!(out.count, 1);
assert_eq!(out.data[0].source, "checkout_open");
assert_eq!(
out.data[0].extra_data.as_ref().unwrap()["screen"],
"390x844"
);
assert!(!out.data[0].extra.contains_key("extra"));
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payments/pay%2F1/client-context"
);
}
#[tokio::test]
async fn delete_hits_the_payment_route() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"payment_id":"pay_1","merchant_id":"mer_1","deleted":true}"#,
)]);
assert!(client.payments().delete("pay_1").await.unwrap().deleted);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/payments/pay_1");
}
const LIST_JSON: &str = r#"{"size":0,"data":[]}"#;
const PAYMENT_JSON: &str = r#"{
"payment_id": "pay_1", "merchant_id": "mer_1", "status": "succeeded",
"amount": 500, "currency": "EUR"
}"#;
#[tokio::test]
async fn abort_and_the_integration_mark_ignore_the_client_wide_key() {
let (client, mock) = client_with_retries(
vec![
Step::status(503, "{}"),
Step::status(503, "{}"),
Step::ok(ABORTED_JSON),
],
2,
);
let payments = client.with_idempotency_key("client-key").payments();
assert!(payments.abort("pay_1", None).await.is_err());
assert!(payments.set_integration_test("pay_1", true).await.is_err());
let seen = mock.seen.lock().unwrap();
assert_eq!(seen.len(), 2);
assert!(seen.iter().all(|step| !step.had_idempotency_key()));
}
}