use std::sync::Arc;
use serde::Serialize;
use crate::core::credentials::{ClientSecret, PublishableKey};
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::checkout::{
CheckoutDataResponse, EpayoutsMethodsResponse, RecordCheckoutEventResponse,
SubscriptionCheckoutResponse, SubscriptionMethodOptionsResponse,
SubscriptionReturnStatusResponse, VaultCollectSessionResponse, VaultPaymentMethodResponse,
};
use crate::core::models::payment::{
PaymentAbandonAttemptResponse, PaymentPostSessionTokensResponse, PaymentReopenAttemptResponse,
PaymentResponse, ReplayIngestResponse,
};
use crate::core::models::payment_method::PaymentMethodListResponse;
use crate::core::models::subscription::SubscriptionResponse;
use crate::http::client::{ClientParts, DelopayBuilder, Inner};
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::payments::{PaymentConfirmRequest, PaymentUpdateRequest};
#[derive(Debug, Clone, Default)]
pub struct CheckoutSessionOptions {
pub base_url: Option<String>,
pub sandbox: bool,
pub timeout: Option<std::time::Duration>,
pub max_retries: Option<u32>,
}
impl CheckoutSessionOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn sandbox(mut self, sandbox: bool) -> Self {
self.sandbox = sandbox;
self
}
#[must_use]
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = Some(base_url.into());
self
}
#[must_use]
pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
self.timeout = Some(timeout);
self
}
#[must_use]
pub fn max_retries(mut self, max_retries: u32) -> Self {
self.max_retries = Some(max_retries);
self
}
fn into_parts(self) -> ClientParts {
let mut builder = DelopayBuilder::for_checkout_session();
if let Some(base_url) = self.base_url {
builder = builder.base_url(base_url);
}
builder = builder.sandbox(self.sandbox);
if let Some(timeout) = self.timeout {
builder = builder.timeout(timeout);
}
if let Some(max_retries) = self.max_retries {
builder = builder.max_retries(max_retries);
}
builder.into_parts()
}
}
#[derive(Debug, Clone)]
pub struct PaymentLinkSession {
inner: Arc<Inner>,
link_base: String,
ids: String,
client_secret: ClientSecret,
}
impl PaymentLinkSession {
pub fn new(
merchant_id: &str,
payment_id: &str,
client_secret: impl Into<ClientSecret>,
) -> Self {
Self::with_options(
merchant_id,
payment_id,
client_secret,
CheckoutSessionOptions::new(),
)
}
pub fn with_options(
merchant_id: &str,
payment_id: &str,
client_secret: impl Into<ClientSecret>,
options: CheckoutSessionOptions,
) -> Self {
Self::from_parts(
&options.into_parts(),
merchant_id,
payment_id,
client_secret.into(),
)
}
fn from_parts(
parts: &ClientParts,
merchant_id: &str,
payment_id: &str,
client_secret: ClientSecret,
) -> Self {
let ids = format!(
"{}/{}",
encode_segment(merchant_id),
encode_segment(payment_id)
);
Self {
inner: Arc::new(parts.inner_with_key(String::new())),
link_base: format!("/payment-link/{ids}"),
ids,
client_secret,
}
}
fn bearer(&self) -> String {
format!("Bearer {}", self.client_secret.as_str())
}
async fn send<T: serde::de::DeserializeOwned>(
&self,
method: HttpMethod,
path: &str,
body: Option<&[u8]>,
query: &[(&str, String)],
) -> Result<T> {
self.send_with_locale(method, path, body, query, None).await
}
async fn send_with_locale<T: serde::de::DeserializeOwned>(
&self,
method: HttpMethod,
path: &str,
body: Option<&[u8]>,
query: &[(&str, String)],
locale: Option<&str>,
) -> Result<T> {
let authorization = self.bearer();
let mut headers = vec![("authorization", authorization.as_str())];
if let Some(locale) = locale {
headers.push(("accept-language", locale));
}
self.inner
.request_with_headers(method, path, body, query, None, &headers)
.await
}
pub async fn checkout_data(&self, params: &CheckoutDataParams) -> Result<CheckoutDataResponse> {
let path = format!("/payment-link/data/{}", self.ids);
let mut headers = Vec::new();
if let Some(locale) = params.locale.as_deref() {
headers.push(("accept-language", locale));
}
self.inner
.request_with_headers(
HttpMethod::Get,
&path,
None,
¶ms.to_query(),
None,
&headers,
)
.await
}
pub async fn subscription_data(
&self,
params: &SubscriptionDataParams,
) -> Result<SubscriptionCheckoutResponse> {
let path = format!("/subscriptions/data/{}", self.ids);
let mut query = Vec::new();
if let Some(theme) = params.theme.as_deref() {
query.push(("theme", theme.to_string()));
}
self.send_with_locale(
HttpMethod::Get,
&path,
None,
&query,
params.locale.as_deref(),
)
.await
}
pub async fn subscription_method_options(&self) -> Result<SubscriptionMethodOptionsResponse> {
let path = format!("/subscriptions/method-options/{}", self.ids);
self.send(HttpMethod::Get, &path, None, &[]).await
}
pub async fn select_subscription_method(
&self,
method: SubscriptionCheckoutMethod,
) -> Result<SubscriptionResponse> {
let body = to_json_vec(&SelectSubscriptionMethodBody { method })?;
let path = format!("/subscriptions/select-method/{}", self.ids);
self.send(HttpMethod::Post, &path, Some(&body), &[]).await
}
pub async fn epayouts_methods(&self, country: &str) -> Result<EpayoutsMethodsResponse> {
let path = format!("{}/epayouts/methods", self.link_base);
self.send(HttpMethod::Get, &path, None, &[("cc", country.to_string())])
.await
}
pub async fn record_event(
&self,
event: &str,
method: &str,
) -> Option<RecordCheckoutEventResponse> {
let body = to_json_vec(&RecordCheckoutEventRequest { event, method }).ok()?;
let path = format!("{}/checkout-events", self.link_base);
self.send(HttpMethod::Post, &path, Some(&body), &[])
.await
.ok()
}
pub async fn vault_collect_session(&self) -> Result<VaultCollectSessionResponse> {
let path = format!("{}/vault/collect-session", self.link_base);
self.send(HttpMethod::Get, &path, None, &[]).await
}
pub async fn register_vault_payment_method(
&self,
params: &VaultPaymentMethodRequest,
) -> Result<VaultPaymentMethodResponse> {
let body = to_json_vec(params)?;
let path = format!("{}/vault/payment-method", self.link_base);
self.send(HttpMethod::Post, &path, Some(&body), &[]).await
}
}
#[derive(Debug, Clone)]
pub struct CheckoutSession {
link: PaymentLinkSession,
pk_inner: Arc<Inner>,
payment_path: String,
client_secret: ClientSecret,
}
impl CheckoutSession {
pub fn new(
merchant_id: &str,
payment_id: &str,
publishable_key: PublishableKey,
client_secret: impl Into<ClientSecret>,
) -> Self {
Self::with_options(
merchant_id,
payment_id,
publishable_key,
client_secret,
CheckoutSessionOptions::new(),
)
}
pub fn with_options(
merchant_id: &str,
payment_id: &str,
publishable_key: PublishableKey,
client_secret: impl Into<ClientSecret>,
options: CheckoutSessionOptions,
) -> Self {
let parts = options.into_parts();
let client_secret = client_secret.into();
Self {
link: PaymentLinkSession::from_parts(
&parts,
merchant_id,
payment_id,
client_secret.clone(),
),
pk_inner: Arc::new(parts.inner_with_key(publishable_key.into_string())),
payment_path: format!("/payments/{}", encode_segment(payment_id)),
client_secret,
}
}
#[must_use]
pub fn payment_link(&self) -> &PaymentLinkSession {
&self.link
}
pub async fn retrieve_payment(&self) -> Result<PaymentResponse> {
self.pk_inner
.request(
HttpMethod::Get,
&self.payment_path,
None,
&[("client_secret", self.client_secret.as_str().to_string())],
None,
)
.await
}
pub async fn update_payment(&self, params: &PaymentUpdateRequest) -> Result<PaymentResponse> {
let body = self.body_with_client_secret(params)?;
self.pk_inner
.request(HttpMethod::Post, &self.payment_path, Some(&body), &[], None)
.await
}
pub async fn confirm_payment(&self, params: &PaymentConfirmRequest) -> Result<PaymentResponse> {
self.confirm_with_key(params, None).await
}
pub async fn confirm_payment_idempotent(
&self,
params: &PaymentConfirmRequest,
idempotency_key: &str,
) -> Result<PaymentResponse> {
self.confirm_with_key(params, Some(idempotency_key)).await
}
async fn confirm_with_key(
&self,
params: &PaymentConfirmRequest,
idempotency_key: Option<&str>,
) -> Result<PaymentResponse> {
let body = self.body_with_client_secret(params)?;
let path = format!("{}/confirm", self.payment_path);
self.pk_inner
.request(HttpMethod::Post, &path, Some(&body), &[], idempotency_key)
.await
}
pub async fn abandon_attempt(&self) -> Result<PaymentAbandonAttemptResponse> {
let body = self.body_with_client_secret(&EmptyCheckoutBody {})?;
let path = format!("{}/abandon-attempt", self.payment_path);
self.pk_inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn reopen_attempt(&self, attempt_id: &str) -> Result<PaymentReopenAttemptResponse> {
let body = self.body_with_client_secret(&ReopenAttemptBody { attempt_id })?;
let path = format!("{}/reopen-attempt", self.payment_path);
self.pk_inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn post_session_tokens(
&self,
params: &PostSessionTokensRequest,
) -> Result<PaymentPostSessionTokensResponse> {
self.post_session_tokens_with_key(params, None).await
}
pub async fn post_session_tokens_idempotent(
&self,
params: &PostSessionTokensRequest,
idempotency_key: &str,
) -> Result<PaymentPostSessionTokensResponse> {
self.post_session_tokens_with_key(params, Some(idempotency_key))
.await
}
async fn post_session_tokens_with_key(
&self,
params: &PostSessionTokensRequest,
idempotency_key: Option<&str>,
) -> Result<PaymentPostSessionTokensResponse> {
let body = self.body_with_client_secret(params)?;
let path = format!("{}/post-session-tokens", self.payment_path);
self.pk_inner
.request(HttpMethod::Post, &path, Some(&body), &[], idempotency_key)
.await
}
pub async fn store_replay_slice(
&self,
params: &ReplayIngestRequest,
) -> Result<ReplayIngestResponse> {
let body = self.body_with_client_secret(params)?;
let path = format!("{}/replay/slice", self.payment_path);
self.pk_inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn list_payment_methods(
&self,
country: Option<&str>,
) -> Result<PaymentMethodListResponse> {
let mut query = vec![("client_secret", self.client_secret.as_str().to_string())];
if let Some(country) = country {
query.push(("country", country.to_string()));
}
self.pk_inner
.request(HttpMethod::Get, "/payment-methods", None, &query, None)
.await
}
fn body_with_client_secret<T: Serialize + ValidateRequest>(
&self,
params: &T,
) -> Result<Vec<u8>> {
params.validate()?;
let mut value = serde_json::to_value(params)
.map_err(|e| crate::core::error::DelopayError::Decode(e.to_string()))?;
match value.as_object_mut() {
Some(map) => {
map.insert(
"client_secret".to_string(),
serde_json::Value::String(self.client_secret.as_str().to_string()),
);
}
None => {
return Err(crate::core::error::DelopayError::InvalidRequest(
"checkout request body must serialize to a JSON object".to_string(),
));
}
}
to_json_vec(&value)
}
pub async fn epayouts_methods(&self, country: &str) -> Result<EpayoutsMethodsResponse> {
self.link.epayouts_methods(country).await
}
pub async fn record_event(
&self,
event: &str,
method: &str,
) -> Option<RecordCheckoutEventResponse> {
self.link.record_event(event, method).await
}
pub async fn vault_collect_session(&self) -> Result<VaultCollectSessionResponse> {
self.link.vault_collect_session().await
}
pub async fn register_vault_payment_method(
&self,
params: &VaultPaymentMethodRequest,
) -> Result<VaultPaymentMethodResponse> {
self.link.register_vault_payment_method(params).await
}
pub async fn checkout_data(&self, params: &CheckoutDataParams) -> Result<CheckoutDataResponse> {
self.link.checkout_data(params).await
}
pub async fn subscription_data(
&self,
params: &SubscriptionDataParams,
) -> Result<SubscriptionCheckoutResponse> {
self.link.subscription_data(params).await
}
pub async fn subscription_method_options(&self) -> Result<SubscriptionMethodOptionsResponse> {
self.link.subscription_method_options().await
}
pub async fn select_subscription_method(
&self,
method: SubscriptionCheckoutMethod,
) -> Result<SubscriptionResponse> {
self.link.select_subscription_method(method).await
}
}
#[derive(Debug, Clone)]
pub struct SubscriptionReturnSession {
inner: Arc<Inner>,
path: String,
}
impl SubscriptionReturnSession {
pub fn new(merchant_id: &str, subscription_id: &str) -> Self {
Self::with_options(merchant_id, subscription_id, CheckoutSessionOptions::new())
}
pub fn with_options(
merchant_id: &str,
subscription_id: &str,
options: CheckoutSessionOptions,
) -> Self {
Self::from_parts(&options.into_parts(), merchant_id, subscription_id)
}
fn from_parts(parts: &ClientParts, merchant_id: &str, subscription_id: &str) -> Self {
Self {
inner: Arc::new(parts.inner_with_key(String::new())),
path: format!(
"/subscriptions/return-status/{}/{}",
encode_segment(merchant_id),
encode_segment(subscription_id)
),
}
}
pub async fn status(&self, return_token: &str) -> Result<SubscriptionReturnStatusResponse> {
if return_token.is_empty() {
return Err(crate::core::error::DelopayError::InvalidRequest(
"the return-status call needs the return token (rt) from the return URL"
.to_string(),
));
}
let authorization = format!("Bearer {return_token}");
self.inner
.request_with_headers(
HttpMethod::Get,
&self.path,
None,
&[],
None,
&[("authorization", authorization.as_str())],
)
.await
}
}
#[derive(Debug, Clone, Default)]
pub struct CheckoutDataParams {
pub locale: Option<String>,
pub theme: Option<String>,
pub country: Option<String>,
pub card_only: bool,
pub card_provider: Option<String>,
pub card_account: Option<String>,
pub entry: Option<String>,
}
impl CheckoutDataParams {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn locale(mut self, locale: impl Into<String>) -> Self {
self.locale = Some(locale.into());
self
}
#[must_use]
pub fn theme(mut self, theme: impl Into<String>) -> Self {
self.theme = Some(theme.into());
self
}
#[must_use]
pub fn country(mut self, country: impl Into<String>) -> Self {
self.country = Some(country.into());
self
}
#[must_use]
pub fn card_only(mut self, card_only: bool) -> Self {
self.card_only = card_only;
self
}
#[must_use]
pub fn card_provider(mut self, card_provider: impl Into<String>) -> Self {
self.card_provider = Some(card_provider.into());
self
}
#[must_use]
pub fn card_account(mut self, card_account: impl Into<String>) -> Self {
self.card_account = Some(card_account.into());
self
}
#[must_use]
pub fn entry(mut self, entry: impl Into<String>) -> Self {
self.entry = Some(entry.into());
self
}
fn to_query(&self) -> Vec<(&'static str, String)> {
fn non_blank(value: Option<&str>) -> Option<String> {
value
.map(str::trim)
.filter(|v| !v.is_empty())
.map(str::to_string)
}
let mut query = Vec::new();
if let Some(theme) = &self.theme {
query.push(("theme", theme.clone()));
}
if let Some(country) = non_blank(self.country.as_deref()) {
query.push(("country", country.to_uppercase()));
}
if self.card_only {
query.push(("card_only", "true".to_string()));
if let Some(provider) = non_blank(self.card_provider.as_deref()) {
query.push(("card_provider", provider));
}
if let Some(account) = non_blank(self.card_account.as_deref()) {
query.push(("card_account", account));
}
}
if let Some(entry) = non_blank(self.entry.as_deref()) {
query.push(("entry", entry));
}
query
}
}
#[derive(Debug, Clone, Default)]
pub struct SubscriptionDataParams {
pub locale: Option<String>,
pub theme: Option<String>,
}
impl SubscriptionDataParams {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn locale(mut self, locale: impl Into<String>) -> Self {
self.locale = Some(locale.into());
self
}
#[must_use]
pub fn theme(mut self, theme: impl Into<String>) -> Self {
self.theme = Some(theme.into());
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SubscriptionCheckoutMethod {
Card,
Paypal,
ProcessorPage,
}
#[derive(Debug, Serialize)]
struct SelectSubscriptionMethodBody {
method: SubscriptionCheckoutMethod,
}
#[derive(Debug, Serialize)]
struct ReopenAttemptBody<'a> {
attempt_id: &'a str,
}
impl ValidateRequest for ReopenAttemptBody<'_> {
fn validate(&self) -> Result<()> {
Ok(())
}
}
#[derive(Debug, Serialize)]
struct RecordCheckoutEventRequest<'a> {
event: &'a str,
method: &'a str,
}
#[derive(Debug, Clone, Serialize)]
pub struct VaultPaymentMethodRequest {
pub card_number_alias: String,
pub card_exp_month: String,
pub card_exp_year: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_holder_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub nick_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_network: Option<String>,
}
impl VaultPaymentMethodRequest {
#[must_use]
pub fn new(
card_number_alias: impl Into<String>,
card_exp_month: impl Into<String>,
card_exp_year: impl Into<String>,
) -> Self {
Self {
card_number_alias: card_number_alias.into(),
card_exp_month: card_exp_month.into(),
card_exp_year: card_exp_year.into(),
card_holder_name: None,
nick_name: None,
card_network: None,
}
}
#[must_use]
pub fn card_holder_name(mut self, name: impl Into<String>) -> Self {
self.card_holder_name = Some(name.into());
self
}
#[must_use]
pub fn nick_name(mut self, nick_name: impl Into<String>) -> Self {
self.nick_name = Some(nick_name.into());
self
}
#[must_use]
pub fn card_network(mut self, card_network: impl Into<String>) -> Self {
self.card_network = Some(card_network.into());
self
}
}
#[derive(Debug, Serialize)]
struct EmptyCheckoutBody {}
impl ValidateRequest for EmptyCheckoutBody {
fn validate(&self) -> Result<()> {
Ok(())
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PostSessionTokensRequest {
pub payment_method: String,
pub payment_method_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_connector_id: Option<String>,
}
impl PostSessionTokensRequest {
pub fn new(payment_method: impl Into<String>, payment_method_type: impl Into<String>) -> Self {
Self {
payment_method: payment_method.into(),
payment_method_type: payment_method_type.into(),
merchant_connector_id: None,
}
}
#[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
}
}
impl ValidateRequest for PostSessionTokensRequest {
fn validate(&self) -> Result<()> {
Ok(())
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ReplayIngestRequest {
pub session_id: String,
pub sequence: u64,
#[serde(skip_serializing_if = "Option::is_none")]
pub events: Option<Vec<serde_json::Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub compressed_events: Option<String>,
}
impl ReplayIngestRequest {
pub fn new(
session_id: impl Into<String>,
sequence: u64,
events: Vec<serde_json::Value>,
) -> Self {
Self {
session_id: session_id.into(),
sequence,
events: Some(events),
compressed_events: None,
}
}
pub fn compressed(
session_id: impl Into<String>,
sequence: u64,
compressed_events: impl Into<String>,
) -> Self {
Self {
session_id: session_id.into(),
sequence,
events: None,
compressed_events: Some(compressed_events.into()),
}
}
}
impl ValidateRequest for ReplayIngestRequest {
fn validate(&self) -> Result<()> {
if self.events.is_some() == self.compressed_events.is_some() {
return Err(DelopayError::InvalidRequest(
"a replay slice carries exactly one of `events` and `compressed_events`".to_owned(),
));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{MockTransport, Step};
const PAYMENT_JSON: &str = r#"{
"payment_id": "pay_456", "merchant_id": "mer_123", "status": "requires_confirmation",
"amount": 1999, "currency": "EUR"
}"#;
fn session_with(steps: Vec<Step>) -> (CheckoutSession, Arc<MockTransport>) {
let mock = Arc::new(MockTransport::new(steps));
let parts = ClientParts::for_test(mock.clone(), "https://api.test");
let client_secret = ClientSecret::new("pay_456_secret_xyz");
let session = CheckoutSession {
link: PaymentLinkSession::from_parts(
&parts,
"mer_123",
"pay_456",
client_secret.clone(),
),
pk_inner: Arc::new(parts.inner_with_key("pk_snd_abc".to_string())),
payment_path: "/payments/pay_456".to_string(),
client_secret,
};
(session, mock)
}
#[tokio::test]
async fn link_routes_send_a_bearer_and_no_api_key() {
let (session, mock) = session_with(vec![Step::ok(
r#"{"country":"de","currency":"EUR","methods":[],"supported_countries":["de"]}"#,
)]);
session.epayouts_methods("de").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payment-link/mer_123/pay_456/epayouts/methods?cc=de"
);
assert_eq!(
seen[0].header("authorization"),
Some("Bearer pay_456_secret_xyz")
);
assert_eq!(seen[0].header("api-key"), None);
}
#[tokio::test]
async fn keyed_session_tokens_carry_the_idempotency_key() {
let (session, mock) = session_with(vec![Step::ok(
r#"{"payment_id":"pay_456","status":"requires_customer_action"}"#,
)]);
session
.post_session_tokens_idempotent(
&PostSessionTokensRequest::new("card", "credit").merchant_connector_id("mca_1"),
"session-pay_456-1",
)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/payments/pay_456/post-session-tokens"
);
assert_eq!(seen[0].header("idempotency-key"), Some("session-pay_456-1"));
assert_eq!(seen[0].body_json()["client_secret"], "pay_456_secret_xyz");
assert_eq!(seen[0].body_json()["merchant_connector_id"], "mca_1");
}
#[tokio::test]
async fn unkeyed_session_tokens_send_no_idempotency_key() {
let (session, mock) = session_with(vec![Step::ok(
r#"{"payment_id":"pay_456","status":"requires_customer_action"}"#,
)]);
session
.post_session_tokens(&PostSessionTokensRequest::new("wallet", "paypal"))
.await
.unwrap();
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
#[tokio::test]
async fn publishable_key_routes_send_the_key_and_no_bearer() {
let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
session.retrieve_payment().await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payments/pay_456?client_secret=pay_456_secret_xyz"
);
assert_eq!(seen[0].header("api-key"), Some("pk_snd_abc"));
assert_eq!(seen[0].header("authorization"), None);
}
#[tokio::test]
async fn confirm_merges_the_client_secret_into_the_body() {
let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
let params = PaymentConfirmRequest {
payment_method: Some("card".to_string()),
..Default::default()
};
session.confirm_payment(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/pay_456/confirm");
let body = seen[0].body_json();
assert_eq!(body["client_secret"], "pay_456_secret_xyz");
assert_eq!(body["payment_method"], "card");
assert!(!seen[0].had_idempotency_key());
}
#[tokio::test]
async fn the_idempotent_confirm_sends_a_key() {
let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
let params = PaymentConfirmRequest {
payment_method: Some("card".to_string()),
..Default::default()
};
session
.confirm_payment_idempotent(¶ms, "confirm-pay_456")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].header("idempotency-key"), Some("confirm-pay_456"));
}
#[tokio::test]
async fn update_payment_carries_the_client_secret_too() {
let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
let params = PaymentUpdateRequest {
metadata: Some(serde_json::json!({"gift": "yes"})),
..Default::default()
};
session.update_payment(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/payments/pay_456");
let body = seen[0].body_json();
assert_eq!(body["client_secret"], "pay_456_secret_xyz");
assert_eq!(body["metadata"]["gift"], "yes");
}
#[tokio::test]
async fn the_checkout_paths_run_the_extra_key_collision_guard() {
let (session, mock) = session_with(vec![]);
let mut confirm = PaymentConfirmRequest::default();
confirm
.extra
.insert("payment_method".to_string(), serde_json::json!("card"));
match session.confirm_payment(&confirm).await.unwrap_err() {
crate::DelopayError::InvalidRequest(msg) => {
assert!(msg.contains("payment_method"), "{msg}");
}
other => panic!("expected InvalidRequest, got {other:?}"),
}
let mut update = PaymentUpdateRequest::default();
update
.extra
.insert("amount".to_string(), serde_json::json!(1));
match session.update_payment(&update).await.unwrap_err() {
crate::DelopayError::InvalidRequest(msg) => assert!(msg.contains("amount"), "{msg}"),
other => panic!("expected InvalidRequest, got {other:?}"),
}
assert_eq!(mock.call_count(), 0);
}
#[tokio::test]
async fn list_payment_methods_sends_the_secret_and_an_optional_country() {
let (session, mock) = session_with(vec![
Step::ok(r#"{"payment_methods":[]}"#),
Step::ok(r#"{"payment_methods":[]}"#),
]);
session.list_payment_methods(None).await.unwrap();
session.list_payment_methods(Some("de")).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payment-methods?client_secret=pay_456_secret_xyz"
);
assert_eq!(
seen[1].url,
"https://api.test/payment-methods?client_secret=pay_456_secret_xyz&country=de"
);
}
#[tokio::test]
async fn record_event_swallows_a_server_error() {
let (session, mock) = session_with(vec![Step::status(500, "boom")]);
assert!(
session
.record_event("native_pane_selected", "apple_pay")
.await
.is_none()
);
assert_eq!(mock.call_count(), 1);
}
#[tokio::test]
async fn record_event_returns_the_receipt_on_success() {
let (session, mock) = session_with(vec![Step::ok(r#"{"recorded":true}"#)]);
let receipt = session
.record_event("native_pane_tab_opened", "klarna")
.await
.unwrap();
assert!(receipt.recorded);
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payment-link/mer_123/pay_456/checkout-events"
);
let body = seen[0].body_json();
assert_eq!(body["event"], "native_pane_tab_opened");
assert_eq!(body["method"], "klarna");
}
#[tokio::test]
async fn the_vault_handshake_posts_only_the_set_fields() {
let (session, mock) = session_with(vec![
Step::ok(
r#"{"vault_id":"tnt_1","environment":"sandbox","access_token":"tok",
"expires_in":900}"#,
),
Step::ok(r#"{"last4":"4242","payment_token":"pt_1"}"#),
]);
session.vault_collect_session().await.unwrap();
session
.register_vault_payment_method(&VaultPaymentMethodRequest::new("alias_1", "12", "2030"))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payment-link/mer_123/pay_456/vault/collect-session"
);
assert_eq!(
seen[1].url,
"https://api.test/payment-link/mer_123/pay_456/vault/payment-method"
);
let body = seen[1].body_json();
assert_eq!(body["card_number_alias"], "alias_1");
assert!(body.get("nick_name").is_none());
}
const CHECKOUT_DATA_JSON: &str = r#"{
"type": "checkout", "payment_id": "pay_456", "amount": "19.99", "currency": "EUR",
"status": "requires_payment_method", "merchant_name": "Shop", "merchant_logo": "",
"theme": "light", "sdk_layout": "tabs", "pub_key": "pk_snd_abc",
"client_secret": "pay_456_secret_xyz", "session_expiry": "2026-11-03T10:00:00Z",
"attempt_count": 0, "surprise_field": 7
}"#;
#[tokio::test]
async fn checkout_data_sends_no_credential_and_normalises_the_query() {
let (session, mock) = session_with(vec![Step::ok(CHECKOUT_DATA_JSON)]);
let params = CheckoutDataParams::new()
.locale("de-DE")
.theme("dark")
.country(" de ")
.card_only(true)
.card_provider(" stripe ")
.card_account(" ")
.entry(" e1 ");
let data = session.checkout_data(¶ms).await.unwrap();
assert_eq!(data.kind, "checkout");
assert_eq!(data.payment_id, "pay_456");
assert_eq!(data.amount, "19.99");
assert_eq!(data.client_secret.as_deref(), Some("pay_456_secret_xyz"));
assert_eq!(data.extra["surprise_field"], 7);
assert!(!format!("{data:?}").contains("pay_456_secret_xyz"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/payment-link/data/mer_123/pay_456\
?theme=dark&country=DE&card_only=true&card_provider=stripe&entry=e1"
);
assert_eq!(seen[0].header("accept-language"), Some("de-DE"));
assert_eq!(seen[0].header("authorization"), None);
assert_eq!(seen[0].header("api-key"), None);
}
#[tokio::test]
async fn checkout_data_omits_the_card_form_names_without_card_only() {
let (session, mock) = session_with(vec![Step::ok(CHECKOUT_DATA_JSON)]);
let params = CheckoutDataParams::new()
.card_provider("stripe")
.card_account("mca_1");
session.checkout_data(¶ms).await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payment-link/data/mer_123/pay_456"
);
assert_eq!(seen[0].header("accept-language"), None);
}
#[tokio::test]
async fn checkout_data_decodes_the_status_and_addon_choice_shapes() {
let (session, _mock) = session_with(vec![
Step::ok(
r#"{"type":"status","payment_id":"pay_456","amount":"38.02","currency":"EUR",
"merchant_logo":"","merchant_name":"Shop","created":"2026-11-01T00:00:00Z",
"status":"succeeded","redirect":false,"theme":"light",
"replay_masking_rules":[],"sdk_layout":"tabs","pub_key":null,
"client_secret":null,"session_expiry":null,"surprise_field":1}"#,
),
Step::ok(
r#"{"type":"addon_choice","payment_id":"pay_456","amount":"38.02",
"currency":"EUR","client_secret":"pay_456_secret_xyz",
"pub_key":"pk_snd_abc","session_expiry":"2026-11-03T10:00:00Z",
"product":{"name":"Plan"},"groups":[],"selection":[],
"merchant_name":"Shop","merchant_logo":"","theme":"light",
"replay_masking_rules":[],"sdk_layout":"tabs"}"#,
),
]);
let status = session
.checkout_data(&CheckoutDataParams::new())
.await
.unwrap();
assert_eq!(status.kind, "status");
assert_eq!(status.amount, "38.02");
assert_eq!(status.status.as_deref(), Some("succeeded"));
assert_eq!(status.client_secret, None);
assert_eq!(status.extra["redirect"], false);
assert_eq!(status.extra["surprise_field"], 1);
let addons = session
.checkout_data(&CheckoutDataParams::new())
.await
.unwrap();
assert_eq!(addons.kind, "addon_choice");
assert_eq!(addons.amount, "38.02");
assert_eq!(addons.status, None);
assert_eq!(addons.extra["product"]["name"], "Plan");
assert!(!format!("{addons:?}").contains("pay_456_secret_xyz"));
}
#[tokio::test]
async fn subscription_data_sends_the_bearer_locale_and_theme() {
let (session, mock) = session_with(vec![Step::ok(
r#"{"type":"subscription","subscription_id":"sub_1","status":"active",
"profile_id":"pro_1","pub_key":"pk_snd_abc","client_secret":"sub_1_secret",
"connector_client_secret":"pi_secret","amount":990,"currency":"EUR",
"amount_source":"invoice","method_choice_pending":false,
"merchant_name":"Shop","theme":"light","sdk_layout":"tabs",
"surprise_field":true}"#,
)]);
let params = SubscriptionDataParams::new().locale("fr").theme("dark");
let data = session.subscription_data(¶ms).await.unwrap();
assert_eq!(data.kind, "subscription");
assert_eq!(data.subscription_id, "sub_1");
assert!(!data.method_choice_pending);
assert_eq!(data.extra["surprise_field"], true);
let rendered = format!("{data:?}");
assert!(!rendered.contains("sub_1_secret"), "{rendered}");
assert!(!rendered.contains("pi_secret"), "{rendered}");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/data/mer_123/pay_456?theme=dark"
);
assert_eq!(
seen[0].header("authorization"),
Some("Bearer pay_456_secret_xyz")
);
assert_eq!(seen[0].header("accept-language"), Some("fr"));
assert_eq!(seen[0].header("api-key"), None);
}
#[tokio::test]
async fn subscription_method_options_reads_with_the_bearer() {
let (session, mock) = session_with(vec![Step::ok(
r#"{"subscription_id":"sub_1","options":[{"method":"card",
"billing_connector":"stripe_billing"}],"buyer_country":"DE",
"surprise_field":1}"#,
)]);
let out = session.subscription_method_options().await.unwrap();
assert_eq!(out.options[0].method, "card");
assert_eq!(out.options[0].billing_connector, "stripe_billing");
assert_eq!(out.no_method_reason, None);
assert_eq!(out.buyer_country, "DE");
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/method-options/mer_123/pay_456"
);
assert_eq!(
seen[0].header("authorization"),
Some("Bearer pay_456_secret_xyz")
);
}
#[tokio::test]
async fn select_subscription_method_posts_the_method() {
let (session, mock) = session_with(vec![Step::ok(
r#"{"id":"sub_1","status":"pending","surprise_field":"x"}"#,
)]);
let sub = session
.select_subscription_method(SubscriptionCheckoutMethod::ProcessorPage)
.await
.unwrap();
assert_eq!(sub.id, "sub_1");
assert_eq!(sub.extra["surprise_field"], "x");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/select-method/mer_123/pay_456"
);
assert_eq!(
seen[0].body_json(),
serde_json::json!({"method": "processor_page"})
);
assert_eq!(
seen[0].header("authorization"),
Some("Bearer pay_456_secret_xyz")
);
assert!(!seen[0].had_idempotency_key());
}
#[tokio::test]
async fn reopen_attempt_posts_the_attempt_with_the_client_secret() {
let (session, mock) = session_with(vec![Step::ok(
r#"{"payment_id":"pay_456","status":"requires_customer_action",
"attempt_id":"att_1","redirect_url":"https://psp.example/r",
"surprise_field":2}"#,
)]);
let out = session.reopen_attempt("att_1").await.unwrap();
assert_eq!(out.attempt_id, "att_1");
assert_eq!(out.redirect_url, "https://psp.example/r");
assert_eq!(out.extra["surprise_field"], 2);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/payments/pay_456/reopen-attempt"
);
assert_eq!(
seen[0].body_json(),
serde_json::json!({"attempt_id": "att_1", "client_secret": "pay_456_secret_xyz"})
);
assert_eq!(seen[0].header("api-key"), Some("pk_snd_abc"));
assert_eq!(seen[0].header("authorization"), None);
assert!(!seen[0].had_idempotency_key());
}
#[tokio::test]
async fn the_return_status_sends_the_return_token_as_the_bearer() {
let mock = Arc::new(MockTransport::new(vec![Step::ok(
r#"{"subscription_id":"sub_1","status":"active","awaiting_processor":true,
"surprise_field":0}"#,
)]));
let parts = ClientParts::for_test(mock.clone(), "https://api.test");
let reader = SubscriptionReturnSession::from_parts(&parts, "mer/1", "sub_1");
let out = reader.status("rt_abc").await.unwrap();
assert!(out.awaiting_processor);
assert_eq!(out.extra["surprise_field"], 0);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/subscriptions/return-status/mer%2F1/sub_1"
);
assert_eq!(seen[0].header("authorization"), Some("Bearer rt_abc"));
assert_eq!(seen[0].header("api-key"), None);
}
#[tokio::test]
async fn the_return_status_refuses_an_empty_token_before_sending() {
let mock = Arc::new(MockTransport::new(vec![]));
let parts = ClientParts::for_test(mock.clone(), "https://api.test");
let reader = SubscriptionReturnSession::from_parts(&parts, "mer_1", "sub_1");
match reader.status("").await.unwrap_err() {
crate::DelopayError::InvalidRequest(msg) => assert!(msg.contains("return token")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
assert_eq!(mock.call_count(), 0);
}
#[tokio::test]
async fn store_replay_slice_sends_one_event_form() {
let (session, mock) = session_with(vec![
Step::ok(r#"{"sequence":0,"duplicate":false,"full":false}"#),
Step::ok(r#"{"sequence":1,"duplicate":false,"full":true}"#),
]);
session
.store_replay_slice(&ReplayIngestRequest::new(
"rs_1",
0,
vec![serde_json::json!({"type": 2})],
))
.await
.unwrap();
let out = session
.store_replay_slice(&ReplayIngestRequest::compressed("rs_1", 1, "H4sIAAAA"))
.await
.unwrap();
assert!(out.full);
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payments/pay_456/replay/slice"
);
let first = seen[0].body_json();
assert_eq!(first["events"], serde_json::json!([{"type": 2}]));
assert!(first.get("compressed_events").is_none());
let second = seen[1].body_json();
assert_eq!(second["compressed_events"], "H4sIAAAA");
assert!(second.get("events").is_none());
assert_eq!(second["client_secret"], "pay_456_secret_xyz");
}
#[tokio::test]
async fn a_replay_slice_with_both_or_no_event_forms_is_refused() {
let (session, mock) = session_with(vec![]);
let mut both = ReplayIngestRequest::new("rs_1", 0, Vec::new());
both.compressed_events = Some("H4sIAAAA".to_string());
assert!(session.store_replay_slice(&both).await.is_err());
let mut neither = ReplayIngestRequest::compressed("rs_1", 0, "x");
neither.compressed_events = None;
assert!(session.store_replay_slice(&neither).await.is_err());
assert_eq!(mock.call_count(), 0);
}
#[tokio::test]
async fn the_link_base_percent_encodes_both_ids() {
let mock = Arc::new(MockTransport::new(vec![Step::ok(
r#"{"country":"de","currency":"EUR","methods":[],"supported_countries":[]}"#,
)]));
let parts = ClientParts::for_test(mock.clone(), "https://api.test");
let link =
PaymentLinkSession::from_parts(&parts, "mer/1", "pay/2", ClientSecret::new("cs"));
link.epayouts_methods("de").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payment-link/mer%2F1/pay%2F2/epayouts/methods?cc=de"
);
}
}