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::ProfileResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
#[derive(Debug, Clone)]
pub struct Profiles {
inner: Arc<Inner>,
}
impl Profiles {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
pub async fn create(
&self,
account_id: &str,
params: &ProfileCreateRequest,
) -> Result<ProfileResponse> {
params.validate()?;
let path = format!("/account/{}/business-profile", encode_segment(account_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn retrieve(&self, account_id: &str, profile_id: &str) -> Result<ProfileResponse> {
let path = Self::profile_path(account_id, profile_id);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn list(&self, account_id: &str) -> Result<Vec<ProfileResponse>> {
let path = format!("/account/{}/business-profile", encode_segment(account_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
pub async fn update(
&self,
account_id: &str,
profile_id: &str,
params: &ProfileUpdateRequest,
) -> Result<ProfileResponse> {
params.validate()?;
let path = Self::profile_path(account_id, profile_id);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
pub async fn delete(&self, account_id: &str, profile_id: &str) -> Result<ProfileResponse> {
let path = Self::profile_path(account_id, profile_id);
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
pub async fn toggle_extended_card_info(
&self,
account_id: &str,
profile_id: &str,
) -> Result<ProfileResponse> {
let path = format!(
"{}/toggle-extended-card-info",
Self::profile_path(account_id, profile_id)
);
self.inner
.request(HttpMethod::Post, &path, None, &[], None)
.await
}
pub async fn toggle_connector_agnostic_mit(
&self,
account_id: &str,
profile_id: &str,
) -> Result<ProfileResponse> {
let path = format!(
"{}/toggle-connector-agnostic-mit",
Self::profile_path(account_id, profile_id)
);
self.inner
.request(HttpMethod::Post, &path, None, &[], None)
.await
}
fn profile_path(account_id: &str, profile_id: &str) -> String {
format!(
"/account/{}/business-profile/{}",
encode_segment(account_id),
encode_segment(profile_id)
)
}
}
const REDACTED: &str = "[redacted]";
#[derive(Clone, Default, Serialize)]
pub struct ProfileCreateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub enable_payment_response_hash: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_response_hash_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_to_merchant_with_http_post: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_details: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub iframe_allowed_origins: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_processor_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_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 ProfileCreateRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProfileCreateRequest")
.field("profile_name", &self.profile_name)
.field("return_url", &self.return_url)
.field(
"enable_payment_response_hash",
&self.enable_payment_response_hash,
)
.field(
"payment_response_hash_key",
&self.payment_response_hash_key.as_ref().map(|_| REDACTED),
)
.field(
"redirect_to_merchant_with_http_post",
&self.redirect_to_merchant_with_http_post,
)
.field(
"webhook_details",
&self.webhook_details.as_ref().map(|_| REDACTED),
)
.field("metadata", &self.metadata)
.field("iframe_allowed_origins", &self.iframe_allowed_origins)
.field("billing_processor_id", &self.billing_processor_id)
.field("payment_id_format", &self.payment_id_format)
.field("extra", &self.extra)
.finish()
}
}
const PROFILE_CREATE_REQUEST_NAMED: &[&str] = &[
"profile_name",
"return_url",
"enable_payment_response_hash",
"payment_response_hash_key",
"redirect_to_merchant_with_http_post",
"webhook_details",
"metadata",
"iframe_allowed_origins",
"billing_processor_id",
"payment_id_format",
];
impl ValidateRequest for ProfileCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PROFILE_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ProfileCreateRequest"
)));
}
}
Ok(())
}
}
impl ProfileCreateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn profile_name(mut self, name: impl Into<String>) -> Self {
self.profile_name = Some(name.into());
self
}
#[must_use]
pub fn return_url(mut self, url: impl Into<String>) -> Self {
self.return_url = Some(url.into());
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 billing_processor_id(mut self, id: impl Into<String>) -> Self {
self.billing_processor_id = Some(id.into());
self
}
}
#[derive(Clone, Default, Serialize)]
pub struct ProfileUpdateRequest {
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub enable_payment_response_hash: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_response_hash_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_to_merchant_with_http_post: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_details: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
#[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 billing_processor_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_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 ProfileUpdateRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProfileUpdateRequest")
.field("profile_name", &self.profile_name)
.field("return_url", &self.return_url)
.field(
"enable_payment_response_hash",
&self.enable_payment_response_hash,
)
.field(
"payment_response_hash_key",
&self.payment_response_hash_key.as_ref().map(|_| REDACTED),
)
.field(
"redirect_to_merchant_with_http_post",
&self.redirect_to_merchant_with_http_post,
)
.field(
"webhook_details",
&self.webhook_details.as_ref().map(|_| REDACTED),
)
.field("metadata", &self.metadata)
.field("payment_link_config", &self.payment_link_config)
.field("iframe_allowed_origins", &self.iframe_allowed_origins)
.field("billing_processor_id", &self.billing_processor_id)
.field("payment_id_format", &self.payment_id_format)
.field("extra", &self.extra)
.finish()
}
}
const PROFILE_UPDATE_REQUEST_NAMED: &[&str] = &[
"profile_name",
"return_url",
"enable_payment_response_hash",
"payment_response_hash_key",
"redirect_to_merchant_with_http_post",
"webhook_details",
"metadata",
"payment_link_config",
"iframe_allowed_origins",
"billing_processor_id",
"payment_id_format",
];
impl ValidateRequest for ProfileUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if PROFILE_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ProfileUpdateRequest"
)));
}
}
Ok(())
}
}
impl ProfileUpdateRequest {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn profile_name(mut self, name: impl Into<String>) -> Self {
self.profile_name = Some(name.into());
self
}
#[must_use]
pub fn return_url(mut self, url: impl Into<String>) -> Self {
self.return_url = Some(url.into());
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 billing_processor_id(mut self, id: impl Into<String>) -> Self {
self.billing_processor_id = Some(id.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const PROFILE_JSON: &str = r#"{
"profile_id": "pro_1",
"merchant_id": "mer_1",
"profile_name": "Shop",
"enable_payment_response_hash": true,
"redirect_to_merchant_with_http_post": false,
"force_3ds_challenge": false
}"#;
fn full_create_request() -> ProfileCreateRequest {
ProfileCreateRequest {
profile_name: Some("Shop".to_string()),
return_url: Some("https://shop.test/return".to_string()),
enable_payment_response_hash: Some(true),
payment_response_hash_key: Some("hashkey_supersecret".to_string()),
redirect_to_merchant_with_http_post: Some(false),
webhook_details: Some(json!({"webhook_password": "hunter2"})),
metadata: Some(json!({"tier": "gold"})),
iframe_allowed_origins: Some(vec!["https://shop.test".to_string()]),
billing_processor_id: Some("mca_billing".to_string()),
payment_id_format: Some(json!({"prefix": "ORD-"})),
extra: serde_json::Map::new(),
}
}
fn full_update_request() -> ProfileUpdateRequest {
ProfileUpdateRequest {
profile_name: Some("Shop".to_string()),
return_url: Some("https://shop.test/return".to_string()),
enable_payment_response_hash: Some(true),
payment_response_hash_key: Some("hashkey_supersecret".to_string()),
redirect_to_merchant_with_http_post: Some(false),
webhook_details: Some(json!({"webhook_password": "hunter2"})),
metadata: Some(json!({"tier": "gold"})),
payment_link_config: Some(json!({"theme": "dark"})),
iframe_allowed_origins: Some(vec!["https://shop.test".to_string()]),
billing_processor_id: Some("mca_billing".to_string()),
payment_id_format: Some(json!({"prefix": "ORD-"})),
extra: serde_json::Map::new(),
}
}
#[test]
fn profile_create_request_named_fields_are_complete() {
let value = serde_json::to_value(full_create_request()).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
PROFILE_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"PROFILE_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn profile_update_request_named_fields_are_complete() {
let value = serde_json::to_value(full_update_request()).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
PROFILE_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"PROFILE_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn validate_rejects_colliding_extra_keys() {
let mut create = ProfileCreateRequest::new().profile_name("Shop");
create
.extra
.insert("return_url".to_string(), json!("https://evil.test"));
match create.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("return_url")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
let mut update = ProfileUpdateRequest::new();
update
.extra
.insert("payment_link_config".to_string(), json!({}));
assert!(matches!(
update.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
#[test]
fn debug_redacts_the_signing_key_and_webhook_details() {
let created = format!("{:?}", full_create_request());
assert!(!created.contains("hashkey_supersecret"), "{created}");
assert!(!created.contains("hunter2"), "{created}");
assert!(
created.contains("payment_response_hash_key: Some(\"[redacted]\")"),
"{created}"
);
assert!(created.contains("Shop"), "{created}");
let updated = format!("{:?}", full_update_request());
assert!(!updated.contains("hashkey_supersecret"), "{updated}");
assert!(!updated.contains("hunter2"), "{updated}");
assert!(
updated.contains("webhook_details: Some(\"[redacted]\")"),
"{updated}"
);
}
#[test]
fn debug_shows_none_for_unset_secrets() {
let rendered = format!("{:?}", ProfileCreateRequest::new());
assert!(
rendered.contains("payment_response_hash_key: None"),
"{rendered}"
);
}
#[tokio::test]
async fn create_and_list_hit_the_business_profile_path() {
let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON), Step::ok("[]")]);
let profiles = client.profiles();
let created = profiles
.create("mer/1", &ProfileCreateRequest::new().profile_name("Shop"))
.await
.unwrap();
assert_eq!(created.profile_id, "pro_1");
assert_eq!(created.profile_name.as_deref(), Some("Shop"));
assert!(profiles.list("mer_1").await.unwrap().is_empty());
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
("POST", "https://api.test/account/mer%2F1/business-profile")
);
assert_eq!(seen[0].body_json()["profile_name"], "Shop");
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
("GET", "https://api.test/account/mer_1/business-profile")
);
}
#[tokio::test]
async fn retrieve_update_and_delete_hit_the_profile_path() {
let (client, mock) = client_with(vec![
Step::ok(PROFILE_JSON),
Step::ok(PROFILE_JSON),
Step::ok(PROFILE_JSON),
]);
let profiles = client.profiles();
let retrieved = profiles.retrieve("mer_1", "pro/1").await.unwrap();
assert_eq!(retrieved.merchant_id.as_deref(), Some("mer_1"));
assert_eq!(retrieved.force_3ds_challenge, Some(false));
profiles
.update(
"mer_1",
"pro_1",
&ProfileUpdateRequest::new().return_url("https://shop.test/r"),
)
.await
.unwrap();
profiles.delete("mer_1", "pro_1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
(
"GET",
"https://api.test/account/mer_1/business-profile/pro%2F1"
)
);
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
(
"POST",
"https://api.test/account/mer_1/business-profile/pro_1"
)
);
assert_eq!(seen[1].body_json()["return_url"], "https://shop.test/r");
assert_eq!(
(seen[2].method, seen[2].url.as_str()),
(
"DELETE",
"https://api.test/account/mer_1/business-profile/pro_1"
)
);
}
#[tokio::test]
async fn the_two_toggles_post_to_their_distinct_paths() {
let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON), Step::ok(PROFILE_JSON)]);
let profiles = client.profiles();
let toggled = profiles
.toggle_extended_card_info("mer_1", "pro_1")
.await
.unwrap();
assert_eq!(toggled.profile_id, "pro_1");
profiles
.toggle_connector_agnostic_mit("mer_1", "pro_1")
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
(
"POST",
"https://api.test/account/mer_1/business-profile/pro_1/toggle-extended-card-info"
)
);
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
(
"POST",
"https://api.test/account/mer_1/business-profile/pro_1/toggle-connector-agnostic-mit"
)
);
}
}