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::profile::CheckoutBrandingResponse;
use crate::core::models::shop::{
GatewayResponse, ProfileLogoUploadResponse, ShopResponse, ShopStatsResponse,
};
use crate::http::client::Inner;
use crate::http::multipart::{FilePart, encode_file};
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::projects::StatsPeriod;
#[derive(Debug, Clone)]
pub struct Shops {
inner: Arc<Inner>,
}
impl Shops {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub fn gateways(&self) -> ShopGateways {
ShopGateways::new(self.inner.clone())
}
pub async fn create(
&self,
merchant_id: &str,
params: &ShopCreateRequest,
) -> Result<ShopResponse> {
params.validate()?;
let path = format!("/shops/{}", encode_segment(merchant_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn retrieve(&self, merchant_id: &str, shop_id: &str) -> Result<ShopResponse> {
let path = shop_path(merchant_id, shop_id);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn update(
&self,
merchant_id: &str,
shop_id: &str,
params: &ShopUpdateRequest,
) -> Result<ShopResponse> {
params.validate()?;
let path = shop_path(merchant_id, shop_id);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Put, &path, Some(&body), &[], None)
.await
}
pub async fn delete(&self, merchant_id: &str, shop_id: &str) -> Result<ShopResponse> {
let path = shop_path(merchant_id, shop_id);
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn list(&self, merchant_id: &str) -> Result<Vec<ShopResponse>> {
let path = format!("/shops/{}", encode_segment(merchant_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn stats(
&self,
merchant_id: &str,
shop_id: &str,
period: Option<StatsPeriod>,
) -> Result<ShopStatsResponse> {
let path = format!("{}/stats", shop_path(merchant_id, shop_id));
let query = match period {
Some(p) => vec![("period", p.to_query_value())],
None => Vec::new(),
};
self.inner
.request(HttpMethod::Get, &path, None, &query, None)
.await
}
pub async fn update_checkout_branding(
&self,
merchant_id: &str,
shop_id: &str,
payment_link_config: &Value,
) -> Result<CheckoutBrandingResponse> {
let path = format!("{}/checkout-branding", shop_path(merchant_id, shop_id));
let body = to_json_vec(&CheckoutBrandingUpdate {
payment_link_config,
})?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn retrieve_checkout_branding(
&self,
merchant_id: &str,
shop_id: &str,
) -> Result<CheckoutBrandingResponse> {
let path = format!("{}/checkout-branding", shop_path(merchant_id, shop_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn retrieve_test_checkout_branding(
&self,
merchant_id: &str,
shop_id: &str,
) -> Result<CheckoutBrandingResponse> {
let path = format!("{}/checkout-branding/test", shop_path(merchant_id, shop_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn update_test_checkout_branding(
&self,
merchant_id: &str,
shop_id: &str,
payment_link_config: &Value,
) -> Result<CheckoutBrandingResponse> {
let path = format!("{}/checkout-branding/test", shop_path(merchant_id, shop_id));
let body = to_json_vec(&CheckoutBrandingUpdate {
payment_link_config,
})?;
self.inner
.request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
.await
}
pub async fn upload_logo(
&self,
merchant_id: &str,
shop_id: &str,
file_name: &str,
content_type: &str,
bytes: &[u8],
) -> Result<ProfileLogoUploadResponse> {
let path = format!("{}/logo", shop_path(merchant_id, shop_id));
let form = encode_file(&FilePart {
field: "file",
file_name,
content_type,
bytes,
});
self.inner
.request_with_content_type(HttpMethod::Post, &path, &form.body, &form.content_type)
.await
}
}
#[derive(Debug, Serialize)]
struct CheckoutBrandingUpdate<'a> {
payment_link_config: &'a Value,
}
fn shop_path(merchant_id: &str, shop_id: &str) -> String {
format!(
"/shops/{}/{}",
encode_segment(merchant_id),
encode_segment(shop_id)
)
}
#[derive(Debug, Clone)]
pub struct ShopGateways {
inner: Arc<Inner>,
}
impl ShopGateways {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn connect(
&self,
merchant_id: &str,
shop_id: &str,
params: &GatewayConnectRequest,
) -> Result<GatewayResponse> {
params.validate()?;
let path = format!("{}/gateways", shop_path(merchant_id, shop_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn list(&self, merchant_id: &str, shop_id: &str) -> Result<Vec<GatewayResponse>> {
let path = format!("{}/gateways", shop_path(merchant_id, shop_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn disconnect(
&self,
merchant_id: &str,
shop_id: &str,
gateway_id: &str,
) -> Result<GatewayResponse> {
let path = format!(
"{}/gateways/{}",
shop_path(merchant_id, shop_id),
encode_segment(gateway_id)
);
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct ShopCreateRequest {
pub shop_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub project_id: Option<String>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl ShopCreateRequest {
pub fn new(shop_name: impl Into<String>) -> Self {
Self {
shop_name: shop_name.into(),
..Default::default()
}
}
#[must_use]
pub fn return_url(mut self, return_url: impl Into<String>) -> Self {
self.return_url = Some(return_url.into());
self
}
#[must_use]
pub fn webhook_url(mut self, webhook_url: impl Into<String>) -> Self {
self.webhook_url = Some(webhook_url.into());
self
}
#[must_use]
pub fn project_id(mut self, project_id: impl Into<String>) -> Self {
self.project_id = Some(project_id.into());
self
}
}
const SHOP_CREATE_REQUEST_NAMED: &[&str] =
&["shop_name", "return_url", "webhook_url", "project_id"];
impl ValidateRequest for ShopCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SHOP_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ShopCreateRequest"
)));
}
}
Ok(())
}
}
#[derive(Clone, Default, Serialize)]
pub struct ShopUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub shop_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_active: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_response_hash_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_link_config: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub iframe_allowed_origins: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_id_format: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub product_id_format: Option<Value>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl std::fmt::Debug for ShopUpdateRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ShopUpdateRequest")
.field("shop_name", &self.shop_name)
.field("return_url", &self.return_url)
.field("webhook_url", &self.webhook_url)
.field("is_active", &self.is_active)
.field(
"payment_response_hash_key",
&self
.payment_response_hash_key
.as_ref()
.map(|_| "<redacted>"),
)
.field("payment_link_config", &self.payment_link_config)
.field("iframe_allowed_origins", &self.iframe_allowed_origins)
.field("payment_id_format", &self.payment_id_format)
.field("product_id_format", &self.product_id_format)
.field("extra", &self.extra)
.finish()
}
}
impl ShopUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn shop_name(mut self, shop_name: impl Into<String>) -> Self {
self.shop_name = Some(shop_name.into());
self
}
#[must_use]
pub fn return_url(mut self, return_url: impl Into<String>) -> Self {
self.return_url = Some(return_url.into());
self
}
#[must_use]
pub fn webhook_url(mut self, webhook_url: impl Into<String>) -> Self {
self.webhook_url = Some(webhook_url.into());
self
}
#[must_use]
pub fn is_active(mut self, is_active: bool) -> Self {
self.is_active = Some(is_active);
self
}
#[must_use]
pub fn payment_response_hash_key(mut self, key: impl Into<String>) -> Self {
self.payment_response_hash_key = Some(key.into());
self
}
#[must_use]
pub fn payment_link_config(mut self, config: Value) -> Self {
self.payment_link_config = Some(config);
self
}
#[must_use]
pub fn iframe_allowed_origins(mut self, origins: Vec<String>) -> Self {
self.iframe_allowed_origins = Some(origins);
self
}
#[must_use]
pub fn payment_id_format(mut self, format: Value) -> Self {
self.payment_id_format = Some(format);
self
}
#[must_use]
pub fn product_id_format(mut self, format: Value) -> Self {
self.product_id_format = Some(format);
self
}
}
const SHOP_UPDATE_REQUEST_NAMED: &[&str] = &[
"shop_name",
"return_url",
"webhook_url",
"is_active",
"payment_response_hash_key",
"payment_link_config",
"iframe_allowed_origins",
"payment_id_format",
"product_id_format",
];
impl ValidateRequest for ShopUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if SHOP_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ShopUpdateRequest"
)));
}
}
Ok(())
}
}
#[derive(Clone, Default, Serialize)]
pub struct GatewayConnectRequest {
pub connector_type: String,
pub connector_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_label: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_account_details: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_methods_enabled: Option<Vec<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(skip_serializing_if = "Option::is_none")]
pub disabled: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_webhook_details: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_merchant_data: Option<Value>,
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
impl std::fmt::Debug for GatewayConnectRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GatewayConnectRequest")
.field("connector_type", &self.connector_type)
.field("connector_name", &self.connector_name)
.field("connector_label", &self.connector_label)
.field("profile_id", &self.profile_id)
.field(
"connector_account_details",
&self
.connector_account_details
.as_ref()
.map(|_| "<redacted>"),
)
.field("payment_methods_enabled", &self.payment_methods_enabled)
.field("metadata", &self.metadata)
.field("test_mode", &self.test_mode)
.field("disabled", &self.disabled)
.field(
"connector_webhook_details",
&self
.connector_webhook_details
.as_ref()
.map(|_| "<redacted>"),
)
.field(
"additional_merchant_data",
&self.additional_merchant_data.as_ref().map(|_| "<redacted>"),
)
.field("extra", &self.extra)
.finish()
}
}
impl GatewayConnectRequest {
pub fn new(connector_type: impl Into<String>, connector_name: impl Into<String>) -> Self {
Self {
connector_type: connector_type.into(),
connector_name: connector_name.into(),
..Default::default()
}
}
#[must_use]
pub fn connector_label(mut self, label: impl Into<String>) -> Self {
self.connector_label = Some(label.into());
self
}
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
#[must_use]
pub fn connector_account_details(mut self, details: Value) -> Self {
self.connector_account_details = Some(details);
self
}
#[must_use]
pub fn payment_methods_enabled(mut self, methods: Vec<Value>) -> Self {
self.payment_methods_enabled = Some(methods);
self
}
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
}
const GATEWAY_CONNECT_REQUEST_NAMED: &[&str] = &[
"connector_type",
"connector_name",
"connector_label",
"profile_id",
"connector_account_details",
"payment_methods_enabled",
"metadata",
"test_mode",
"disabled",
"connector_webhook_details",
"additional_merchant_data",
];
impl ValidateRequest for GatewayConnectRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if GATEWAY_CONNECT_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on GatewayConnectRequest"
)));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with, client_with_retries};
use serde_json::json;
const SHOP_JSON: &str = r#"{
"shop_id": "pro_1",
"shop_name": "EU Store",
"is_active": true,
"created_at": "2024-01-01T00:00:00Z",
"modified_at": "2024-01-02T00:00:00Z",
"return_url": "https://acme.test/return",
"webhook_url": "https://acme.test/hook",
"project_id": "prj_1",
"iframe_allowed_origins": ["https://shop.acme.com"],
"payment_id_format": {"prefix": "ORD-", "style": "numeric", "length": 8},
"product_id_format": {"prefix": "PRD-"},
"surprise_field": 1
}"#;
#[tokio::test]
async fn update_checkout_branding_posts_the_config_under_its_own_key() {
let (client, mock) = client_with(vec![Step::ok(
r##"{"profile_id":"pro_1","profile_name":"EU Store","payment_link_config":{"theme":"#0a0a0a"}}"##,
)]);
let config = json!({"theme": "#0a0a0a", "logo": "https://cdn.test/l.png"});
let saved = client
.shops()
.update_checkout_branding("mer_1", "pro/1", &config)
.await
.unwrap();
assert_eq!(saved.profile_id, "pro_1");
assert_eq!(saved.profile_name, "EU Store");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/shops/mer_1/pro%2F1/checkout-branding"
);
assert_eq!(seen[0].body_json()["payment_link_config"], config);
}
#[tokio::test]
async fn a_branding_save_cannot_carry_the_signing_key() {
let (client, _mock) = client_with(vec![Step::ok(
r##"{
"profile_id": "pro_1",
"profile_name": "EU Store",
"payment_link_config": {"theme": "#0a0a0a"},
"payment_response_hash_key": "whsec_leak_me"
}"##,
)]);
let saved = client
.shops()
.update_checkout_branding("mer_1", "pro_1", &json!({"theme": "#0a0a0a"}))
.await
.unwrap();
assert_eq!(
saved.extra.get("payment_response_hash_key"),
Some(&Value::from("whsec_leak_me"))
);
assert!(!format!("{saved:?}").contains("whsec_leak_me"));
}
#[tokio::test]
async fn a_never_styled_shop_reads_back_as_none() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"profile_id":"pro_1","profile_name":"EU Store","payment_link_config":null}"#,
)]);
let branding = client
.shops()
.retrieve_checkout_branding("mer_1", "pro/1")
.await
.unwrap();
assert!(branding.payment_link_config.is_none());
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/shops/mer_1/pro%2F1/checkout-branding"
);
}
#[tokio::test]
async fn retrieve_test_checkout_branding_gets_the_test_sub_path() {
let (client, mock) = client_with(vec![Step::ok(
r##"{"profile_id":"pro_1","profile_name":"EU Store","payment_link_config":{"theme":"#111111"},"test_mode":true,"follows_live":true,"surprise_field":1}"##,
)]);
let branding = client
.shops()
.retrieve_test_checkout_branding("mer_1", "pro/1")
.await
.unwrap();
assert_eq!(branding.profile_id, "pro_1");
assert_eq!(
branding.payment_link_config,
Some(json!({"theme": "#111111"}))
);
assert!(branding.test_mode);
assert!(branding.follows_live);
assert_eq!(branding.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/shops/mer_1/pro%2F1/checkout-branding/test"
);
assert!(seen[0].body.is_none());
}
#[tokio::test]
async fn update_test_checkout_branding_posts_the_config_to_the_test_sub_path() {
let (client, mock) = client_with(vec![Step::ok(
r##"{"profile_id":"pro_1","profile_name":"EU Store","payment_link_config":{"theme":"#222222"},"test_mode":true,"follows_live":false}"##,
)]);
let config = json!({"theme": "#222222"});
let saved = client
.shops()
.update_test_checkout_branding("mer/1", "pro_1", &config)
.await
.unwrap();
assert!(saved.test_mode);
assert!(!saved.follows_live);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/shops/mer%2F1/pro_1/checkout-branding/test"
);
assert_eq!(
seen[0].body_json(),
json!({"payment_link_config": {"theme": "#222222"}})
);
}
const SHOP_WITH_SECRET_JSON: &str = r#"{
"shop_id": "pro_1",
"shop_name": "EU Store",
"is_active": true,
"created_at": "2024-01-01T00:00:00Z",
"modified_at": "2024-01-02T00:00:00Z",
"payment_response_hash_key": "whsec_response_leak_me"
}"#;
const GATEWAY_JSON: &str = r#"{
"connector_type": "payment_processor",
"connector_name": "stripe",
"merchant_connector_id": "mca_1",
"profile_id": "pro_1",
"status": "active",
"connector_label": "primary",
"connector_account_details": {"api_key": "sk_live_response_leak_me"},
"connector_webhook_details": {"merchant_secret": "whsec_response_leak_me"},
"test_mode": false,
"created_at": "2024-01-01T00:00:00Z"
}"#;
const SHOP_STATS_JSON: &str = r#"{
"shop_id": "pro_1",
"shop_name": "EU Store",
"project_id": null,
"orders": 4,
"revenue": 5000,
"revenue_usd": 54.5,
"revenue_by_currency": [{"currency": "EUR", "amount_minor": 5000, "orders": 4}],
"unconverted_orders": 1,
"period_days": 90,
"analytics_exclusions_active": true
}"#;
#[tokio::test]
async fn create_posts_to_the_merchant_path() {
let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
let shop = client
.shops()
.create("merch_123", &ShopCreateRequest::new("EU Store"))
.await
.unwrap();
assert_eq!(shop.shop_id, "pro_1");
assert_eq!(shop.project_id.as_deref(), Some("prj_1"));
assert!(shop.is_active);
assert_eq!(
shop.iframe_allowed_origins.as_deref().unwrap()[0],
"https://shop.acme.com"
);
let format = shop.payment_id_format.as_ref().expect("a custom id format");
assert_eq!(format.prefix.as_deref(), Some("ORD-"));
assert_eq!(format.style.as_deref(), Some("numeric"));
assert_eq!(format.length, Some(8));
assert_eq!(
shop.product_id_format.as_ref().unwrap().prefix.as_deref(),
Some("PRD-")
);
assert_eq!(shop.extra["surprise_field"], 1);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/shops/merch_123");
assert_eq!(seen[0].body_json()["shop_name"], "EU Store");
}
#[tokio::test]
async fn retrieve_encodes_both_id_segments() {
let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
client.shops().retrieve("merch/1", "pro 1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/shops/merch%2F1/pro%201");
}
#[tokio::test]
async fn update_puts_the_shop_path_with_a_body() {
let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
let params = ShopUpdateRequest::new()
.shop_name("EU Store 2")
.iframe_allowed_origins(vec!["https://shop.acme.com".to_string()]);
client
.shops()
.update("merch_123", "pro_1", ¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "PUT");
assert_eq!(seen[0].url, "https://api.test/shops/merch_123/pro_1");
let body = seen[0].body_json();
assert_eq!(body["shop_name"], "EU Store 2");
assert_eq!(body["iframe_allowed_origins"][0], "https://shop.acme.com");
}
#[tokio::test]
async fn delete_deletes_the_shop_path() {
let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
client.shops().delete("merch_123", "pro_1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(seen[0].url, "https://api.test/shops/merch_123/pro_1");
}
#[tokio::test]
async fn list_gets_the_merchant_path() {
let (client, mock) = client_with(vec![Step::ok(&format!("[{SHOP_JSON}]"))]);
let shops = client.shops().list("merch_123").await.unwrap();
assert_eq!(shops[0].shop_name, "EU Store");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(seen[0].url, "https://api.test/shops/merch_123");
}
#[tokio::test]
async fn stats_serializes_both_period_forms_and_omits_an_absent_period() {
let (client, mock) = client_with(vec![
Step::ok(SHOP_STATS_JSON),
Step::ok(SHOP_STATS_JSON),
Step::ok(SHOP_STATS_JSON),
]);
let shops = client.shops();
shops.stats("merch_123", "pro_1", None).await.unwrap();
shops
.stats("merch_123", "pro_1", Some(StatsPeriod::All))
.await
.unwrap();
shops
.stats("merch_123", "pro_1", Some(StatsPeriod::Days(90)))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].url, "https://api.test/shops/merch_123/pro_1/stats");
assert_eq!(
seen[1].url,
"https://api.test/shops/merch_123/pro_1/stats?period=all"
);
assert_eq!(
seen[2].url,
"https://api.test/shops/merch_123/pro_1/stats?period=90"
);
}
#[tokio::test]
async fn gateways_connect_posts_credentials_to_the_gateways_path() {
let (client, mock) = client_with(vec![Step::ok(GATEWAY_JSON)]);
let params = GatewayConnectRequest::new("payment_processor", "stripe")
.connector_account_details(json!({"auth_type": "HeaderKey", "api_key": "sk_test"}));
client
.shops()
.gateways()
.connect("merch_123", "pro_1", ¶ms)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/shops/merch_123/pro_1/gateways"
);
let body = seen[0].body_json();
assert_eq!(body["connector_name"], "stripe");
assert_eq!(body["connector_account_details"]["api_key"], "sk_test");
}
#[tokio::test]
async fn gateways_list_gets_the_gateways_path() {
let (client, mock) = client_with(vec![Step::ok(&format!("[{GATEWAY_JSON}]"))]);
let gateways = client
.shops()
.gateways()
.list("merch_123", "pro_1")
.await
.unwrap();
assert_eq!(gateways[0].merchant_connector_id, "mca_1");
assert_eq!(gateways[0].status, "active");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/shops/merch_123/pro_1/gateways"
);
}
#[tokio::test]
async fn gateways_disconnect_deletes_the_encoded_gateway_id() {
let (client, mock) = client_with(vec![Step::ok(GATEWAY_JSON)]);
client
.shops()
.gateways()
.disconnect("merch_123", "pro_1", "mca/1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "DELETE");
assert_eq!(
seen[0].url,
"https://api.test/shops/merch_123/pro_1/gateways/mca%2F1"
);
}
#[test]
fn shop_update_debug_redacts_the_webhook_signing_secret() {
let req = ShopUpdateRequest::new().payment_response_hash_key("whsec_super_secret");
let rendered = format!("{req:?}");
assert!(
!rendered.contains("whsec_super_secret"),
"the signing secret leaked into Debug output: {rendered}"
);
assert!(rendered.contains("<redacted>"));
}
#[test]
fn gateway_connect_debug_redacts_credential_fields() {
let req = GatewayConnectRequest::new("payment_processor", "stripe")
.connector_account_details(json!({"api_key": "sk_live_leak_me"}));
let rendered = format!("{req:?}");
assert!(
!rendered.contains("sk_live_leak_me"),
"connector credentials leaked into Debug output: {rendered}"
);
assert!(rendered.contains("<redacted>"));
assert!(rendered.contains("stripe"));
}
#[test]
fn shop_create_request_named_fields_are_complete() {
let req = ShopCreateRequest::new("EU Store")
.return_url("https://acme.test/return")
.webhook_url("https://acme.test/hook")
.project_id("prj_1");
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
SHOP_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"SHOP_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn shop_update_request_named_fields_are_complete() {
let req = ShopUpdateRequest::new()
.shop_name("EU Store")
.return_url("https://acme.test/return")
.webhook_url("https://acme.test/hook")
.is_active(true)
.payment_response_hash_key("whsec_1")
.payment_link_config(json!({"allowed_domains": ["acme.test"]}))
.iframe_allowed_origins(vec!["https://acme.test".to_string()])
.payment_id_format(json!({"prefix": "ORD-", "style": "numeric", "length": 8}))
.product_id_format(json!({"prefix": "PRD-"}));
let value = serde_json::to_value(req).unwrap();
assert_eq!(value["product_id_format"], json!({"prefix": "PRD-"}));
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
SHOP_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"SHOP_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn gateway_connect_request_named_fields_are_complete() {
let req = GatewayConnectRequest {
connector_label: Some("primary".to_string()),
profile_id: Some("pro_1".to_string()),
connector_account_details: Some(json!({"api_key": "sk"})),
payment_methods_enabled: Some(vec![json!({"payment_method": "card"})]),
metadata: Some(json!({"team": "eu"})),
test_mode: Some(true),
disabled: Some(false),
connector_webhook_details: Some(json!({"merchant_secret": "whsec"})),
additional_merchant_data: Some(json!({"open_banking": {}})),
..GatewayConnectRequest::new("payment_processor", "stripe")
};
let value = serde_json::to_value(req).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
GATEWAY_CONNECT_REQUEST_NAMED.contains(&key.as_str()),
"GATEWAY_CONNECT_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn shop_create_validate_rejects_colliding_extra_key() {
let mut req = ShopCreateRequest::new("EU Store");
req.extra.insert("shop_name".to_string(), json!("other"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("shop_name")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[test]
fn shop_update_validate_rejects_colliding_extra_key() {
let mut req = ShopUpdateRequest::new();
req.extra
.insert("payment_link_config".to_string(), json!({}));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("payment_link_config")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[test]
fn gateway_connect_validate_rejects_colliding_extra_key() {
let mut req = GatewayConnectRequest::new("payment_processor", "stripe");
req.extra.insert("test_mode".to_string(), json!(true));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("test_mode")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[tokio::test]
async fn upload_logo_posts_a_multipart_body_with_a_matching_boundary() {
let (client, mock) = client_with(vec![Step::ok(r#"{"logo_url":"https://cdn/x.png"}"#)]);
let uploaded = client
.shops()
.upload_logo("mer/1", "pro_1", "logo.png", "image/png", b"PNGDATA")
.await
.unwrap();
assert_eq!(uploaded.logo_url, "https://cdn/x.png");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/shops/mer%2F1/pro_1/logo");
let content_type = seen[0]
.content_type
.as_deref()
.expect("upload sets its own content type");
let boundary = content_type
.strip_prefix("multipart/form-data; boundary=")
.expect("multipart content type");
let body = String::from_utf8(seen[0].body.clone().unwrap()).unwrap();
assert!(body.starts_with(&format!("--{boundary}\r\n")));
assert!(body.ends_with(&format!("\r\n--{boundary}--\r\n")));
assert!(body.contains("name=\"file\"; filename=\"logo.png\""));
assert!(body.contains("Content-Type: image/png\r\n\r\nPNGDATA"));
}
#[tokio::test]
async fn stats_decodes_the_shop_aggregate() {
let (client, _mock) = client_with(vec![Step::ok(SHOP_STATS_JSON)]);
let stats = client
.shops()
.stats("merch_123", "pro_1", Some(StatsPeriod::Days(90)))
.await
.unwrap();
assert_eq!(stats.shop_id, "pro_1");
assert_eq!(stats.orders, 4);
assert_eq!(stats.revenue, 5000);
assert_eq!(stats.revenue_usd, 54.5);
assert_eq!(stats.revenue_by_currency[0].currency, "EUR");
assert_eq!(stats.revenue_by_currency[0].amount_minor, 5000);
assert_eq!(stats.revenue_by_currency[0].orders, 4);
assert_eq!(stats.unconverted_orders, 1);
assert_eq!(stats.period_days, Some(90));
assert!(stats.analytics_exclusions_active);
assert_eq!(stats.project_id, None);
}
#[tokio::test]
async fn shop_response_debug_redacts_an_echoed_webhook_signing_secret() {
let (client, _mock) = client_with(vec![Step::ok(SHOP_WITH_SECRET_JSON)]);
let shop = client.shops().retrieve("merch_123", "pro_1").await.unwrap();
assert_eq!(
shop.payment_response_hash_key.as_deref(),
Some("whsec_response_leak_me")
);
let rendered = format!("{shop:?}");
assert!(
!rendered.contains("whsec_response_leak_me"),
"the signing secret leaked into Debug output: {rendered}"
);
assert!(rendered.contains("<redacted>"));
assert!(rendered.contains("EU Store"));
}
#[tokio::test]
async fn gateway_response_debug_redacts_echoed_credentials() {
let (client, _mock) = client_with(vec![Step::ok(GATEWAY_JSON)]);
let gateway = client
.shops()
.gateways()
.connect(
"merch_123",
"pro_1",
&GatewayConnectRequest::new("payment_processor", "stripe"),
)
.await
.unwrap();
assert_eq!(
gateway.connector_account_details.as_ref().unwrap()["api_key"],
"sk_live_response_leak_me"
);
let rendered = format!("{gateway:?}");
assert!(
!rendered.contains("sk_live_response_leak_me"),
"connector credentials leaked into Debug output: {rendered}"
);
assert!(
!rendered.contains("whsec_response_leak_me"),
"connector webhook secret leaked into Debug output: {rendered}"
);
assert!(rendered.contains("<redacted>"));
assert!(rendered.contains("mca_1"));
}
#[tokio::test]
async fn test_branding_save_ignores_the_client_wide_idempotency_key() {
let (client, mock) = client_with_retries(vec![Step::status(503, "{}"), Step::ok("{}")], 2);
let out = client
.with_idempotency_key("client-key")
.shops()
.update_test_checkout_branding("mer_1", "pro_1", &json!({}))
.await;
assert!(out.is_err());
assert_eq!(mock.call_count(), 1);
assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
}
}