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::Result;
use crate::core::models::checkout::{
EpayoutsMethodsResponse, PayseproMethodsResponse, RecordCheckoutEventResponse,
VaultCollectSessionResponse, VaultPaymentMethodResponse,
};
use crate::core::models::payment::PaymentResponse;
use crate::core::models::payment_method::PaymentMethodListResponse;
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,
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 {
Self {
inner: Arc::new(parts.inner_with_key(String::new())),
link_base: format!(
"/payment-link/{}/{}",
encode_segment(merchant_id),
encode_segment(payment_id)
),
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> {
let authorization = self.bearer();
self.inner
.request_with_headers(
method,
path,
body,
query,
None,
&[("authorization", authorization.as_str())],
)
.await
}
pub async fn paysepro_methods(&self, country: &str) -> Result<PayseproMethodsResponse> {
let path = format!("{}/paysepro/methods", self.link_base);
self.send(HttpMethod::Get, &path, None, &[("cc", country.to_string())])
.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 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 paysepro_methods(&self, country: &str) -> Result<PayseproMethodsResponse> {
self.link.paysepro_methods(country).await
}
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
}
}
#[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
}
}
#[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":[]}"#,
)]);
session.paysepro_methods("de").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
seen[0].url,
"https://api.test/payment-link/mer_123/pay_456/paysepro/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 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());
}
#[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"
);
}
}