Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(card-issuers): implement card issuer management with CRUD operations and database migration (#11570)

Ayush Anand0faf8f2a546d
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 89264104af..4c773ae0ec 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -8224,6 +8224,155 @@
}
]
}
+ },
+ "/card_issuers": {
+ "post": {
+ "tags": [
+ "Card Issuer"
+ ],
+ "summary": "Card Issuer - Create",
+ "description": "Creates a new card issuer entry",
+ "operationId": "Create Card Issuer",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CardIssuerRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Card issuer created",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CardIssuerResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Missing or invalid fields"
+ },
+ "409": {
+ "description": "Card issuer already exists"
+ }
+ },
+ "security": [
+ {
+ "admin_api_key": []
+ }
+ ]
+ },
+ "get": {
+ "tags": [
+ "Card Issuer"
+ ],
+ "summary": "Card Issuer - List",
+ "description": "Lists card issuers with optional search filter",
+ "operationId": "List Card Issuers",
+ "parameters": [
+ {
+ "name": "query",
+ "in": "query",
+ "description": "Optional search term to filter issuers by name",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "nullable": true
+ }
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "description": "Maximum number of results to return",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int32",
+ "nullable": true,
+ "minimum": 0
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Card issuers listed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CardIssuerListResponse"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ },
+ {
+ "jwt_key": []
+ }
+ ]
+ }
+ },
+ "/card_issuers/{id}": {
+ "put": {
+ "tags": [
+ "Card Issuer"
+ ],
+ "summary": "Card Issuer - Update",
+ "description": "Updates an existing card issuer entry",
+ "operationId": "Update Card Issuer",
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "description": "The unique identifier for the card issuer",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CardIssuerUpdateRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Card issuer updated",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CardIssuerResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Card issuer not found"
+ },
+ "409": {
+ "description": "Card issuer with this name already exists"
+ }
+ },
+ "security": [
+ {
+ "admin_api_key": []
+ }
+ ]
+ }
}
},
"components": {
@@ -13994,7 +14143,7 @@
"items": {
"type": "string"
},
- "description": "Set of card issuers to block (e.g., [\"HDFC Bank\", \"ICICI Bank\"])",
+ "description": "Set of card issuer IDs to block",
"uniqueItems": true,
"nullable": true
},
@@ -14219,6 +14368,81 @@
"click_to_pay"
]
},
+ "CardIssuerListQuery": {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Optional search term to filter issuers by name (case-insensitive prefix match)",
+ "example": "hdfc",
+ "nullable": true
+ },
+ "limit": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Maximum number of results to return (default: 30, max: 255)",
+ "default": 30,
+ "example": 30,
+ "maximum": 255,
+ "minimum": 0
+ }
+ }
+ },
+ "CardIssuerListResponse": {
+ "type": "object",
+ "required": [
+ "issuers"
+ ],
+ "properties": {
+ "issuers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CardIssuerResponse"
+ }
+ }
+ }
+ },
+ "CardIssuerRequest": {
+ "type": "object",
+ "required": [
+ "issuer_name"
+ ],
+ "properties": {
+ "issuer_name": {
+ "type": "string",
+ "description": "The name of the card issuer to add",
+ "example": "STATE BANK OF INDIA"
+ }
+ }
+ },
+ "CardIssuerResponse": {
+ "type": "object",
+ "required": [
+ "id",
+ "issuer_name"
+ ],
+ "properties": {
+ "id": {
+ "type": "string"
+ },
+ "issuer_name": {
+ "type": "string"
+ }
+ }
+ },
+ "CardIssuerUpdateRequest": {
+ "type": "object",
+ "required": [
+ "issuer_name"
+ ],
+ "properties": {
+ "issuer_name": {
+ "type": "string",
+ "description": "The new name for the card issuer",
+ "example": "STATE BANK OF INDIA UPDATED"
+ }
+ }
+ },
"CardNetwork": {
"type": "string",
"description": "Indicates the card network.",
@@ -41815,6 +42039,10 @@
{
"name": "Subscriptions",
"description": "Subscription management and billing endpoints"
+ },
+ {
+ "name": "Card Issuer",
+ "description": "Create and manage card issuers"
}
]
}
\ No newline at end of file
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index e98d131aa9..f621e06a92 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -288,7 +288,7 @@ pub struct CardBlockingConfig {
/// Set of card subtypes to block
#[schema(value_type = Option<Vec<CardSubtype>>)]
pub card_subtypes: Option<HashSet<common_enums::CardSubtype>>,
- /// Set of card issuers to block (e.g., ["HDFC Bank", "ICICI Bank"])
+ /// Set of card issuer IDs to block
pub issuers: Option<HashSet<String>>,
/// Whether to block if BIN is provided but no matching record found in cards_info table.
/// Defaults to false (allow payment if BIN not found in database).
diff --git a/crates/api_models/src/card_issuer.rs b/crates/api_models/src/card_issuer.rs
new file mode 100644
index 0000000000..b6c704905a
--- /dev/null
+++ b/crates/api_models/src/card_issuer.rs
@@ -0,0 +1,70 @@
+use common_utils::{events::ApiEventMetric, id_type::CardIssuerId, new_type::CardIssuerName};
+use utoipa::ToSchema;
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct CardIssuerRequest {
+ /// The name of the card issuer to add
+ #[schema(example = "STATE BANK OF INDIA", value_type = String)]
+ pub issuer_name: CardIssuerName,
+}
+
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct CardIssuerResponse {
+ #[schema(value_type = String)]
+ pub id: CardIssuerId,
+ #[schema(value_type = String)]
+ pub issuer_name: CardIssuerName,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct CardIssuerListQuery {
+ /// Optional search term to filter issuers by name (case-insensitive prefix match)
+ #[schema(example = "hdfc")]
+ pub query: Option<String>,
+ /// Maximum number of results to return (default: 30, max: 255)
+ #[schema(example = 30, default = 30, maximum = 255, value_type = u8)]
+ #[serde(default = "default_card_issuer_list_limit")]
+ pub limit: u8,
+}
+
+fn default_card_issuer_list_limit() -> u8 {
+ common_utils::consts::DEFAULT_CARD_ISSUER_LIST_LIMIT
+}
+
+#[derive(Debug, serde::Serialize, ToSchema)]
+pub struct CardIssuerListResponse {
+ pub issuers: Vec<CardIssuerResponse>,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
+pub struct CardIssuerUpdateRequest {
+ /// The new name for the card issuer
+ #[schema(example = "STATE BANK OF INDIA UPDATED", value_type = String)]
+ pub issuer_name: CardIssuerName,
+}
+
+impl ApiEventMetric for CardIssuerUpdateRequest {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::CardIssuers)
+ }
+}
+impl ApiEventMetric for CardIssuerRequest {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::CardIssuers)
+ }
+}
+impl ApiEventMetric for CardIssuerResponse {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::CardIssuers)
+ }
+}
+impl ApiEventMetric for CardIssuerListResponse {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::CardIssuers)
+ }
+}
+impl ApiEventMetric for CardIssuerListQuery {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ Some(common_utils::events::ApiEventsType::CardIssuers)
+ }
+}
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index b7142624dc..6d9243df1e 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -4,6 +4,7 @@ pub mod api_keys;
pub mod apple_pay_certificates_migration;
pub mod authentication;
pub mod blocklist;
+pub mod card_issuer;
pub mod cards_info;
pub mod chat;
pub mod conditional_configs;
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 02a5d68654..cd27d7ea59 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -127,6 +127,9 @@ pub const WILDCARD_DOMAIN_REGEX: &str = r"^((\*|https?)?://)?((\*\.|[A-Za-z0-9][
/// Maximum allowed length for MerchantName
pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64;
+/// Maximum allowed length for CardIssuerName
+pub const MAX_ALLOWED_CARD_ISSUER_NAME_LENGTH: usize = 255;
+
/// Default locale
pub const DEFAULT_LOCALE: &str = "en";
@@ -229,3 +232,9 @@ pub const DEFAULT_LIST_LIMIT: i64 = 100;
/// Default offset for list operations (can be used across different entities)
pub const DEFAULT_LIST_OFFSET: i64 = 0;
+
+/// Default number of card issuers returned in a list request
+pub const DEFAULT_CARD_ISSUER_LIST_LIMIT: u8 = 30;
+
+/// Length of a generated card issuer ID
+pub const CARD_ISSUER_ID_LENGTH: u8 = 5;
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index f8f902cd3d..280636104a 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -143,6 +143,7 @@ pub enum ApiEventsType {
ThreeDsDecisionRule,
Chat,
Oidc,
+ CardIssuers,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs
index f6fa569d6e..2722e246b6 100644
--- a/crates/common_utils/src/id_type.rs
+++ b/crates/common_utils/src/id_type.rs
@@ -3,6 +3,7 @@
mod api_key;
mod authentication;
+mod card_issuer;
mod client_secret;
mod customer;
#[cfg(feature = "v2")]
@@ -47,6 +48,7 @@ pub use self::global_id::{
pub use self::{
api_key::ApiKeyId,
authentication::AuthenticationId,
+ card_issuer::CardIssuerId,
client_secret::ClientSecretId,
customer::CustomerId,
invoice::InvoiceId,
diff --git a/crates/common_utils/src/id_type/card_issuer.rs b/crates/common_utils/src/id_type/card_issuer.rs
new file mode 100644
index 0000000000..39fa961928
--- /dev/null
+++ b/crates/common_utils/src/id_type/card_issuer.rs
@@ -0,0 +1,40 @@
+use crate::{
+ consts,
+ errors::{CustomResult, ValidationError},
+ generate_id_with_len,
+};
+
+crate::id_type!(
+ CardIssuerId,
+ "A type for card_issuer_id that can be used for unique identifier for a card issuer",
+ diesel::sql_types::Text,
+ { consts::CARD_ISSUER_ID_LENGTH },
+ { consts::CARD_ISSUER_ID_LENGTH }
+);
+crate::impl_id_type_methods!(CardIssuerId, "card_issuer_id");
+
+// This is to display the `CardIssuerId` as CardIssuerId(abcd)
+crate::impl_debug_id_type!(CardIssuerId);
+crate::impl_try_from_cow_str_id_type!(CardIssuerId, "card_issuer_id");
+
+crate::impl_serializable_secret_id_type!(CardIssuerId);
+crate::impl_queryable_id_type!(CardIssuerId);
+crate::impl_to_sql_from_sql_id_type!(
+ CardIssuerId,
+ diesel::sql_types::Text,
+ { consts::CARD_ISSUER_ID_LENGTH },
+ { consts::CARD_ISSUER_ID_LENGTH }
+);
+
+impl CardIssuerId {
+ /// Get card issuer id from String
+ pub fn try_from_string(card_issuer_id: String) -> CustomResult<Self, ValidationError> {
+ Self::try_from(std::borrow::Cow::from(card_issuer_id))
+ }
+
+ /// Generate a new unique card issuer ID of length [`consts::CARD_ISSUER_ID_LENGTH`]
+ pub fn generate() -> CustomResult<Self, ValidationError> {
+ let id = generate_id_with_len(consts::CARD_ISSUER_ID_LENGTH.into());
+ Self::try_from_string(id)
+ }
+}
diff --git a/crates/common_utils/src/new_type.rs b/crates/common_utils/src/new_type.rs
index b7d293e994..6be9260f47 100644
--- a/crates/common_utils/src/new_type.rs
+++ b/crates/common_utils/src/new_type.rs
@@ -2,7 +2,7 @@
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
- consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH,
+ consts::{MAX_ALLOWED_CARD_ISSUER_NAME_LENGTH, MAX_ALLOWED_MERCHANT_NAME_LENGTH},
pii::{Email, UpiVpaMaskingStrategy},
transformers::ForeignFrom,
};
@@ -15,6 +15,14 @@ pub struct MerchantName(String);
impl hyperswitch_masking::SerializableSecret for MerchantName {}
+#[nutype::nutype(
+ derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq, Hash),
+ validate(len_char_min = 1, len_char_max = MAX_ALLOWED_CARD_ISSUER_NAME_LENGTH)
+)]
+pub struct CardIssuerName(String);
+
+impl hyperswitch_masking::SerializableSecret for CardIssuerName {}
+
/// Function for masking alphanumeric characters in a string.
///
/// # Arguments
diff --git a/crates/diesel_models/src/card_issuer.rs b/crates/diesel_models/src/card_issuer.rs
new file mode 100644
index 0000000000..24adf2999f
--- /dev/null
+++ b/crates/diesel_models/src/card_issuer.rs
@@ -0,0 +1,32 @@
+use common_utils::id_type;
+use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
+use time::PrimitiveDateTime;
+
+use crate::schema::card_issuers;
+
+#[derive(
+ Clone, Debug, Queryable, Identifiable, Selectable, serde::Serialize, serde::Deserialize,
+)]
+#[diesel(table_name = card_issuers, check_for_backend(diesel::pg::Pg))]
+pub struct CardIssuer {
+ pub id: id_type::CardIssuerId,
+ pub issuer_name: String,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified_at: PrimitiveDateTime,
+}
+
+#[derive(Clone, Debug, AsChangeset, serde::Serialize, serde::Deserialize)]
+#[diesel(table_name = card_issuers)]
+pub struct UpdateCardIssuer {
+ pub issuer_name: String,
+ pub last_modified_at: PrimitiveDateTime,
+}
+
+#[derive(Clone, Debug, Insertable, serde::Serialize, serde::Deserialize)]
+#[diesel(table_name = card_issuers)]
+pub struct NewCardIssuer {
+ pub id: id_type::CardIssuerId,
+ pub issuer_name: String,
+ pub created_at: PrimitiveDateTime,
+ pub last_modified_at: PrimitiveDateTime,
+}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index d29eeac41c..c2bb2a09da 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -3,6 +3,7 @@ pub mod api_keys;
pub mod blocklist_lookup;
pub mod business_profile;
pub mod capture;
+pub mod card_issuer;
pub mod cards_info;
pub mod configs;
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index 9bf6adc40b..5f28a0019e 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -3,6 +3,7 @@ pub mod api_keys;
pub mod blocklist_lookup;
pub mod business_profile;
mod capture;
+pub mod card_issuer;
pub mod cards_info;
pub mod configs;
diff --git a/crates/diesel_models/src/query/card_issuer.rs b/crates/diesel_models/src/query/card_issuer.rs
new file mode 100644
index 0000000000..e7181b82a3
--- /dev/null
+++ b/crates/diesel_models/src/query/card_issuer.rs
@@ -0,0 +1,54 @@
+use common_utils::id_type;
+use diesel::{associations::HasTable, ExpressionMethods, PgTextExpressionMethods};
+
+use super::generics;
+use crate::{
+ card_issuer::{CardIssuer, NewCardIssuer, UpdateCardIssuer},
+ schema::card_issuers::dsl,
+ PgPooledConn, StorageResult,
+};
+
+impl CardIssuer {
+ pub async fn list_filtered(
+ conn: &PgPooledConn,
+ query: Option<String>,
+ limit: Option<i64>,
+ ) -> StorageResult<Vec<Self>> {
+ let pattern = query.map_or("%".to_string(), |q| format!("{}%", q));
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
+ conn,
+ dsl::issuer_name.ilike(pattern),
+ limit,
+ None,
+ Some(dsl::issuer_name.asc()),
+ )
+ .await
+ }
+
+ pub async fn find_by_ids(
+ conn: &PgPooledConn,
+ ids: Vec<id_type::CardIssuerId>,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<
+ <Self as HasTable>::Table,
+ _,
+ <<Self as HasTable>::Table as diesel::Table>::PrimaryKey,
+ Self,
+ >(conn, dsl::id.eq_any(ids), None, None, None)
+ .await
+ }
+
+ pub async fn update(
+ conn: &PgPooledConn,
+ id: id_type::CardIssuerId,
+ data: UpdateCardIssuer,
+ ) -> StorageResult<Self> {
+ generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(conn, id, data).await
+ }
+}
+
+impl NewCardIssuer {
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<CardIssuer> {
+ generics::generic_insert(conn, self).await
+ }
+}
diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rs
index 0aff6997b2..b33d37d157 100644
--- a/crates/diesel_models/src/query/utils.rs
+++ b/crates/diesel_models/src/query/utils.rs
@@ -86,6 +86,7 @@ macro_rules! impl_get_primary_key {
}
impl_get_primary_key!(
// v1 tables
+ schema::card_issuers::table,
schema::dashboard_metadata::table,
schema::merchant_connector_account::table,
schema::merchant_key_store::table,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 44357afe0d..6bb1ea41c1 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -357,6 +357,19 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ card_issuers (id) {
+ #[max_length = 64]
+ id -> Varchar,
+ issuer_name -> Varchar,
+ created_at -> Timestamp,
+ last_modified_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1866,6 +1879,7 @@ diesel::allow_tables_to_appear_in_same_query!(
business_profile,
callback_mapper,
captures,
+ card_issuers,
cards_info,
configs,
customers,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 6b59b5f654..3c01144a2f 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -365,6 +365,19 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ card_issuers (id) {
+ #[max_length = 64]
+ id -> Varchar,
+ issuer_name -> Varchar,
+ created_at -> Timestamp,
+ last_modified_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1824,6 +1837,7 @@ diesel::allow_tables_to_appear_in_same_query!(
business_profile,
callback_mapper,
captures,
+ card_issuers,
cards_info,
configs,
customers,
diff --git a/crates/hyperswitch_domain_models/src/card_issuer.rs b/crates/hyperswitch_domain_models/src/card_issuer.rs
new file mode 100644
index 0000000000..4abb07f454
--- /dev/null
+++ b/crates/hyperswitch_domain_models/src/card_issuer.rs
@@ -0,0 +1,28 @@
+use common_utils::{errors, id_type};
+use diesel_models::card_issuer;
+
+#[async_trait::async_trait]
+pub trait CardIssuersInterface {
+ type Error;
+ async fn insert_card_issuer(
+ &self,
+ new: card_issuer::NewCardIssuer,
+ ) -> errors::CustomResult<card_issuer::CardIssuer, Self::Error>;
+
+ async fn update_card_issuer(
+ &self,
+ id: id_type::CardIssuerId,
+ update: card_issuer::UpdateCardIssuer,
+ ) -> errors::CustomResult<card_issuer::CardIssuer, Self::Error>;
+
+ async fn list_card_issuers(
+ &self,
+ query: Option<String>,
+ limit: Option<u8>,
+ ) -> errors::CustomResult<Vec<card_issuer::CardIssuer>, Self::Error>;
+
+ async fn get_card_issuers_by_ids(
+ &self,
+ ids: Vec<id_type::CardIssuerId>,
+ ) -> errors::CustomResult<Vec<card_issuer::CardIssuer>, Self::Error>;
+}
diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs
index be50bd2c9b..6d8dbdcc74 100644
--- a/crates/hyperswitch_domain_models/src/lib.rs
+++ b/crates/hyperswitch_domain_models/src/lib.rs
@@ -5,6 +5,7 @@ pub mod behaviour;
pub mod bulk_tokenization;
pub mod business_profile;
pub mod callback_mapper;
+pub mod card_issuer;
pub mod card_testing_guard_data;
pub mod cards_info;
pub mod chat;
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index f92375c126..649d5429d7 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -67,7 +67,8 @@ Never share your secret api keys. Keep them guarded and secure.
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
(name = "Authentication", description = "Create and manage authentication"),
- (name = "Subscriptions", description = "Subscription management and billing endpoints")
+ (name = "Subscriptions", description = "Subscription management and billing endpoints"),
+ (name = "Card Issuer", description = "Create and manage card issuers")
),
// The paths will be displayed in the same order as they are registered here
paths(
@@ -247,6 +248,11 @@ Never share your secret api keys. Keep them guarded and secure.
routes::subscriptions::pause_subscription,
routes::subscriptions::resume_subscription,
routes::subscriptions::cancel_subscription,
+
+ // Routes for card issuers
+ routes::card_issuer::add_card_issuer,
+ routes::card_issuer::update_card_issuer,
+ routes::card_issuer::list_card_issuers,
),
components(schemas(
common_utils::types::MinorUnit,
@@ -488,6 +494,11 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
+ api_models::card_issuer::CardIssuerRequest,
+ api_models::card_issuer::CardIssuerResponse,
+ api_models::card_issuer::CardIssuerUpdateRequest,
+ api_models::card_issuer::CardIssuerListQuery,
+ api_models::card_issuer::CardIssuerListResponse,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
diff --git a/crates/openapi/src/routes.rs b/crates/openapi/src/routes.rs
index 07a979984d..6801bf9c9d 100644
--- a/crates/openapi/src/routes.rs
+++ b/crates/openapi/src/routes.rs
@@ -3,6 +3,7 @@
pub mod api_keys;
pub mod authentication;
pub mod blocklist;
+pub mod card_issuer;
pub mod customers;
pub mod disputes;
pub mod gsm;
diff --git a/crates/openapi/src/routes/card_issuer.rs b/crates/openapi/src/routes/card_issuer.rs
new file mode 100644
index 0000000000..67c7450cc6
--- /dev/null
+++ b/crates/openapi/src/routes/card_issuer.rs
@@ -0,0 +1,61 @@
+/// Card Issuer - Create
+///
+/// Creates a new card issuer entry
+#[utoipa::path(
+ post,
+ path = "/card_issuers",
+ request_body(
+ content = CardIssuerRequest,
+ ),
+ responses(
+ (status = 200, description = "Card issuer created", body = CardIssuerResponse),
+ (status = 400, description = "Missing or invalid fields"),
+ (status = 409, description = "Card issuer already exists"),
+ ),
+ tag = "Card Issuer",
+ operation_id = "Create Card Issuer",
+ security(("admin_api_key" = [])),
+)]
+pub async fn add_card_issuer() {}
+
+/// Card Issuer - Update
+///
+/// Updates an existing card issuer entry
+#[utoipa::path(
+ put,
+ path = "/card_issuers/{id}",
+ params(
+ ("id" = String, Path, description = "The unique identifier for the card issuer"),
+ ),
+ request_body(
+ content = CardIssuerUpdateRequest,
+ ),
+ responses(
+ (status = 200, description = "Card issuer updated", body = CardIssuerResponse),
+ (status = 404, description = "Card issuer not found"),
+ (status = 409, description = "Card issuer with this name already exists"),
+ ),
+ tag = "Card Issuer",
+ operation_id = "Update Card Issuer",
+ security(("admin_api_key" = [])),
+)]
+pub async fn update_card_issuer() {}
+
+/// Card Issuer - List
+///
+/// Lists card issuers with optional search filter
+#[utoipa::path(
+ get,
+ path = "/card_issuers",
+ params(
+ ("query" = Option<String>, Query, description = "Optional search term to filter issuers by name"),
+ ("limit" = Option<u8>, Query, description = "Maximum number of results to return"),
+ ),
+ responses(
+ (status = 200, description = "Card issuers listed", body = CardIssuerListResponse),
+ ),
+ tag = "Card Issuer",
+ operation_id = "List Card Issuers",
+ security(("api_key" = []), ("jwt_key" = [])),
+)]
+pub async fn list_card_issuers() {}
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index 5341c50117..a5569d5425 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -7,6 +7,7 @@ pub mod authentication;
#[cfg(feature = "v1")]
pub mod blocklist;
pub mod cache;
+pub mod card_issuer;
pub mod card_testing_guard;
pub mod cards_info;
pub mod chat;
diff --git a/crates/router/src/core/card_issuer.rs b/crates/router/src/core/card_issuer.rs
new file mode 100644
index 0000000000..05cf778ae9
--- /dev/null
+++ b/crates/router/src/core/card_issuer.rs
@@ -0,0 +1,82 @@
+use api_models::card_issuer as api_types;
+use common_utils::{date_time, id_type};
+use diesel_models::card_issuer::{NewCardIssuer, UpdateCardIssuer};
+use router_env::{instrument, tracing};
+
+use crate::{
+ core::errors::{self, RouterResponse, StorageErrorExt},
+ routes::SessionState,
+ services::ApplicationResponse,
+ types::transformers::ForeignTryInto,
+};
+
+#[instrument(skip_all)]
+pub async fn add_card_issuer(
+ state: SessionState,
+ body: api_types::CardIssuerRequest,
+) -> RouterResponse<api_types::CardIssuerResponse> {
+ let now = date_time::now();
+ let new = NewCardIssuer {
+ id: id_type::CardIssuerId::generate()
+ .map_err(|_| errors::ApiErrorResponse::InternalServerError)?,
+ issuer_name: body.issuer_name.into_inner(),
+ created_at: now,
+ last_modified_at: now,
+ };
+
+ let issuer = state
+ .store
+ .insert_card_issuer(new)
+ .await
+ .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
+ message: "A card issuer with this name already exists".to_string(),
+ })?;
+
+ Ok(ApplicationResponse::Json(issuer.foreign_try_into()?))
+}
+
+#[instrument(skip_all)]
+pub async fn update_card_issuer(
+ state: SessionState,
+ id: id_type::CardIssuerId,
+ body: api_types::CardIssuerUpdateRequest,
+) -> RouterResponse<api_types::CardIssuerResponse> {
+ let update = UpdateCardIssuer {
+ issuer_name: body.issuer_name.into_inner(),
+ last_modified_at: date_time::now(),
+ };
+
+ let issuer = state
+ .store
+ .update_card_issuer(id.clone(), update)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
+ message: format!("Card issuer with id {} not found", id.get_string_repr()),
+ })?;
+
+ Ok(ApplicationResponse::Json(issuer.foreign_try_into()?))
+}
+
+#[instrument(skip_all)]
+pub async fn list_card_issuers(
+ state: SessionState,
+ query: api_types::CardIssuerListQuery,
+) -> RouterResponse<api_types::CardIssuerListResponse> {
+ let issuers = state
+ .store
+ .list_card_issuers(query.query, Some(query.limit))
+ .await
+ .map_err(|error| error.change_context(errors::ApiErrorResponse::InternalServerError))?;
+
+ Ok(ApplicationResponse::Json(
+ api_types::CardIssuerListResponse {
+ issuers: issuers
+ .into_iter()
+ .map(ForeignTryInto::foreign_try_into)
+ .collect::<Result<Vec<_>, _>>()
+ .map_err(|_| errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "issuer_name",
+ })?,
+ },
+ ))
+}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 5dad313938..fa618b0300 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -8,6 +8,7 @@ pub mod blocklist_lookup;
pub mod business_profile;
pub mod callback_mapper;
pub mod capture;
+pub mod card_issuer;
pub mod configs;
pub mod customers;
pub mod dashboard_metadata;
@@ -53,6 +54,7 @@ use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,
};
use hyperswitch_domain_models::{
+ card_issuer::CardIssuersInterface,
cards_info::CardsInfoInterface,
master_key::MasterKeyInterface,
payment_methods::PaymentMethodInterface,
@@ -117,6 +119,7 @@ pub trait StorageInterface:
+ PaymentMethodInterface<Error = StorageError>
+ blocklist::BlocklistInterface
+ blocklist_fingerprint::BlocklistFingerprintInterface
+ + CardIssuersInterface<Error = StorageError>
+ dynamic_routing_stats::DynamicRoutingStatsInterface
+ scheduler::SchedulerInterface
+ PayoutAttemptInterface<Error = StorageError>
diff --git a/crates/router/src/db/card_issuer.rs b/crates/router/src/db/card_issuer.rs
new file mode 100644
index 0000000000..d677b2e5b0
--- /dev/null
+++ b/crates/router/src/db/card_issuer.rs
@@ -0,0 +1,48 @@
+use common_utils::id_type;
+use hyperswitch_domain_models::card_issuer::CardIssuersInterface;
+use router_env::{instrument, tracing};
+
+use crate::{
+ core::errors::{self, CustomResult},
+ db::kafka_store::KafkaStore,
+ types::storage,
+};
+
+#[async_trait::async_trait]
+impl CardIssuersInterface for KafkaStore {
+ type Error = errors::StorageError;
+
+ #[instrument(skip_all)]
+ async fn insert_card_issuer(
+ &self,
+ new: storage::NewCardIssuer,
+ ) -> CustomResult<storage::CardIssuer, errors::StorageError> {
+ self.diesel_store.insert_card_issuer(new).await
+ }
+
+ #[instrument(skip_all)]
+ async fn update_card_issuer(
+ &self,
+ id: id_type::CardIssuerId,
+ update: storage::UpdateCardIssuer,
+ ) -> CustomResult<storage::CardIssuer, errors::StorageError> {
+ self.diesel_store.update_card_issuer(id, update).await
+ }
+
+ #[instrument(skip_all)]
+ async fn list_card_issuers(
+ &self,
+ query: Option<String>,
+ limit: Option<u8>,
+ ) -> CustomResult<Vec<storage::CardIssuer>, errors::StorageError> {
+ self.diesel_store.list_card_issuers(query, limit).await
+ }
+
+ #[instrument(skip_all)]
+ async fn get_card_issuers_by_ids(
+ &self,
+ ids: Vec<id_type::CardIssuerId>,
+ ) -> CustomResult<Vec<storage::CardIssuer>, errors::StorageError> {
+ self.diesel_store.get_card_issuers_by_ids(ids).await
+ }
+}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index ba672646e2..9eeab32c42 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -216,6 +216,7 @@ pub fn mk_app(
.service(routes::Files::server(state.clone()))
.service(routes::Disputes::server(state.clone()))
.service(routes::Blocklist::server(state.clone()))
+ .service(routes::CardIssuers::server(state.clone()))
.service(routes::Subscription::server(state.clone()))
.service(routes::Gsm::server(state.clone()))
.service(routes::ApplePayCertificatesMigration::server(state.clone()))
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index fc39516933..356deb80a5 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -7,6 +7,7 @@ pub mod authentication;
#[cfg(all(feature = "olap", feature = "v1"))]
pub mod blocklist;
pub mod cache;
+pub mod card_issuer;
pub mod cards_info;
pub mod configs;
#[cfg(feature = "olap")]
@@ -93,12 +94,12 @@ pub use self::app::Proxy;
#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]
pub use self::app::Recon;
pub use self::app::{
- ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, Cards, Chat, Configs,
- ConnectorOnboarding, Customers, Disputes, Embedded, EphemeralKey, FeatureMatrix, Files, Forex,
- Gsm, Health, Hypersense, Mandates, MerchantAccount, MerchantConnectorAccount, Oidc,
- PaymentLink, PaymentMethods, Payments, Poll, ProcessTracker, ProcessTrackerDeprecated, Profile,
- ProfileAcquirer, ProfileNew, Refunds, Relay, RelayWebhooks, SessionState, ThreeDsDecisionRule,
- User, UserDeprecated, Webhooks,
+ ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, CardIssuers, Cards,
+ Chat, Configs, ConnectorOnboarding, Customers, Disputes, Embedded, EphemeralKey, FeatureMatrix,
+ Files, Forex, Gsm, Health, Hypersense, Mandates, MerchantAccount, MerchantConnectorAccount,
+ Oidc, PaymentLink, PaymentMethods, Payments, Poll, ProcessTracker, ProcessTrackerDeprecated,
+ Profile, ProfileAcquirer, ProfileNew, Refunds, Relay, RelayWebhooks, SessionState,
+ ThreeDsDecisionRule, User, UserDeprecated, Webhooks,
};
#[cfg(feature = "olap")]
pub use self::app::{Blocklist, Organization, Routing, Subscription, Verify, WebhookEvents};
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ed9208a716..be8729418d 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -67,8 +67,8 @@ use super::verification::{apple_pay_merchant_registration, retrieve_apple_pay_ve
#[cfg(feature = "oltp")]
use super::webhooks::*;
use super::{
- admin, api_keys, cache::*, chat, connector_onboarding, disputes, files, gsm, health::*, oidc,
- profiles, relay, user, user_role,
+ admin, api_keys, cache::*, card_issuer, chat, connector_onboarding, disputes, files, gsm,
+ health::*, oidc, profiles, relay, user, user_role,
};
#[cfg(feature = "v1")]
use super::{
@@ -1887,6 +1887,22 @@ impl Blocklist {
}
}
+pub struct CardIssuers;
+
+#[cfg(feature = "v1")]
+impl CardIssuers {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("/card_issuers")
+ .app_data(web::Data::new(state))
+ .service(
+ web::resource("")
+ .route(web::post().to(card_issuer::add_card_issuer))
+ .route(web::get().to(card_issuer::list_card_issuers)),
+ )
+ .service(web::resource("/{id}").route(web::put().to(card_issuer::update_card_issuer)))
+ }
+}
+
#[cfg(feature = "olap")]
pub struct Organization;
diff --git a/crates/router/src/routes/card_issuer.rs b/crates/router/src/routes/card_issuer.rs
new file mode 100644
index 0000000000..b5949f6283
--- /dev/null
+++ b/crates/router/src/routes/card_issuer.rs
@@ -0,0 +1,83 @@
+use actix_web::{web, HttpRequest, HttpResponse};
+use api_models::card_issuer as api_types;
+use common_utils::id_type;
+use router_env::{instrument, tracing, Flow};
+
+use super::app::AppState;
+use crate::{
+ core::{api_locking, card_issuer},
+ services::{api, authentication as auth, authorization::permissions::Permission},
+};
+
+#[instrument(skip_all, fields(flow = ?Flow::AddCardIssuer))]
+pub async fn add_card_issuer(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<api_types::CardIssuerRequest>,
+) -> HttpResponse {
+ let flow = Flow::AddCardIssuer;
+ let payload = json_payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, _, body, _| card_issuer::add_card_issuer(state, body),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[instrument(skip_all, fields(flow = ?Flow::UpdateCardIssuer))]
+pub async fn update_card_issuer(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<id_type::CardIssuerId>,
+ json_payload: web::Json<api_types::CardIssuerUpdateRequest>,
+) -> HttpResponse {
+ let flow = Flow::UpdateCardIssuer;
+ let id = path.into_inner();
+ let payload = json_payload.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ move |state, _, body, _| card_issuer::update_card_issuer(state, id.clone(), body),
+ &auth::AdminApiAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[instrument(skip_all, fields(flow = ?Flow::ListCardIssuers))]
+pub async fn list_card_issuers(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<api_types::CardIssuerListQuery>,
+) -> HttpResponse {
+ let flow = Flow::ListCardIssuers;
+ let query = query.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query,
+ |state, _, query, _| card_issuer::list_card_issuers(state, query),
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ allow_connected_scope_operation: false,
+ allow_platform_self_operation: false,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountRead,
+ allow_connected: false,
+ allow_platform: false,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 1b28b1f8b6..67d7e1e009 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -52,6 +52,7 @@ pub enum ApiIdentifier {
ThreeDsDecisionRule,
GenericTokenization,
RecoveryRecovery,
+ CardIssuers,
}
impl From<Flow> for ApiIdentifier {
@@ -386,6 +387,9 @@ impl From<Flow> for ApiIdentifier {
Flow::MerchantConnectorWebhookRegister | Flow::MerchantConnectorWebhookList => {
Self::MerchantConnectorWebhookManagement
}
+ Flow::AddCardIssuer | Flow::UpdateCardIssuer | Flow::ListCardIssuers => {
+ Self::CardIssuers
+ }
}
}
}
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index a151be33bc..cbe8b81d0d 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -8,6 +8,7 @@ pub mod blocklist_lookup;
pub mod business_profile;
pub mod callback_mapper;
pub mod capture;
+pub mod card_issuer;
pub mod cards_info;
pub mod configs;
pub mod customers;
@@ -71,8 +72,8 @@ pub use scheduler::db::process_tracker;
pub use self::{
address::*, api_keys::*, authentication::*, authorization::*, blocklist::*,
blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*,
- capture::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*, dispute::*,
- dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*,
+ capture::*, card_issuer::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*,
+ dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*,
generic_link::*, gsm::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*,
merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*,
payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*,
diff --git a/crates/router/src/types/storage/card_issuer.rs b/crates/router/src/types/storage/card_issuer.rs
new file mode 100644
index 0000000000..a7b3d779c0
--- /dev/null
+++ b/crates/router/src/types/storage/card_issuer.rs
@@ -0,0 +1 @@
+pub use diesel_models::card_issuer::{CardIssuer, NewCardIssuer, UpdateCardIssuer};
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 86eed8b41f..415e8b1335 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1,6 +1,7 @@
use actix_web::http::header::HeaderMap;
use api_models::{
- cards_info as card_info_types, enums as api_enums, gsm as gsm_api_types, payment_methods,
+ card_issuer as card_issuer_types, cards_info as card_info_types, enums as api_enums,
+ gsm as gsm_api_types, payment_methods,
payments::{self, CustomerDetails},
routing::ConnectorSelection,
};
@@ -9,6 +10,7 @@ use common_utils::{
crypto::Encryptable,
ext_traits::{Encode, StringExt, ValueExt},
fp_utils::when,
+ new_type::CardIssuerName,
pii,
types::ConnectorTransactionIdTrait,
};
@@ -2561,3 +2563,19 @@ impl ForeignFrom<&revenue_recovery_redis_operation::PaymentProcessorTokenStatus>
}
}
}
+
+impl ForeignTryFrom<storage::CardIssuer> for card_issuer_types::CardIssuerResponse {
+ type Error = error_stack::Report<errors::ApiErrorResponse>;
+
+ fn foreign_try_from(from: storage::CardIssuer) -> Result<Self, Self::Error> {
+ let issuer_name = CardIssuerName::try_new(from.issuer_name).change_context(
+ errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "issuer_name",
+ },
+ )?;
+ Ok(Self {
+ id: from.id,
+ issuer_name,
+ })
+ }
+}
diff --git a/crates/router/tests/card_issuer.rs b/crates/router/tests/card_issuer.rs
new file mode 100644
index 0000000000..c167bc222a
--- /dev/null
+++ b/crates/router/tests/card_issuer.rs
@@ -0,0 +1,144 @@
+mod utils;
+
+#[actix_web::test]
+#[ignore]
+async fn card_issuer_success() {
+ Box::pin(utils::setup()).await;
+
+ let admin_api_key = ("api-key", "test_admin");
+ let issuer_name = "STATE BANK OF INDIA";
+ let updated_name = "STATE BANK OF INDIA UPDATED";
+
+ let create_request = serde_json::json!({
+ "issuer_name": issuer_name,
+ });
+
+ let update_request = serde_json::json!({
+ "issuer_name": updated_name,
+ });
+
+ let client = awc::Client::default();
+ let mut response;
+ let mut response_body;
+
+ // create card issuer
+ response = client
+ .post("http://127.0.0.1:8080/card_issuers")
+ .insert_header(admin_api_key)
+ .send_json(&create_request)
+ .await
+ .unwrap();
+ response_body = response.json::<serde_json::Value>().await.unwrap();
+ println!("card-issuer-create: {response:?} : {response_body:?}");
+ assert_eq!(response.status(), awc::http::StatusCode::OK);
+
+ let issuer_id = response_body
+ .get("id")
+ .and_then(|v| v.as_str())
+ .unwrap()
+ .to_string();
+
+ // update card issuer
+ response = client
+ .put(format!("http://127.0.0.1:8080/card_issuers/{issuer_id}"))
+ .insert_header(admin_api_key)
+ .send_json(&update_request)
+ .await
+ .unwrap();
+ response_body = response.json::<serde_json::Value>().await.unwrap();
+ println!("card-issuer-update: {response:?} : {response_body:?}");
+ assert_eq!(response.status(), awc::http::StatusCode::OK);
+ assert_eq!(
+ response_body.get("issuer_name").and_then(|v| v.as_str()),
+ Some(updated_name)
+ );
+
+ // list card issuers
+ response = client
+ .get("http://127.0.0.1:8080/card_issuers")
+ .insert_header(admin_api_key)
+ .send()
+ .await
+ .unwrap();
+ response_body = response.json::<serde_json::Value>().await.unwrap();
+ println!("card-issuer-list: {response:?} : {response_body:?}");
+ assert_eq!(response.status(), awc::http::StatusCode::OK);
+
+ // list with query filter
+ response = client
+ .get("http://127.0.0.1:8080/card_issuers?query=STATE")
+ .insert_header(admin_api_key)
+ .send()
+ .await
+ .unwrap();
+ response_body = response.json::<serde_json::Value>().await.unwrap();
+ println!("card-issuer-list-filtered: {response:?} : {response_body:?}");
+ assert_eq!(response.status(), awc::http::StatusCode::OK);
+ assert!(!response_body
+ .get("issuers")
+ .and_then(|v| v.as_array())
+ .unwrap()
+ .is_empty());
+}
+
+#[actix_web::test]
+#[ignore]
+async fn card_issuer_failure() {
+ Box::pin(utils::setup()).await;
+
+ let admin_api_key = ("api-key", "test_admin");
+ let issuer_name = "HDFC BANK";
+
+ let create_request = serde_json::json!({
+ "issuer_name": issuer_name,
+ });
+
+ let client = awc::Client::default();
+ let mut response;
+ let mut response_body;
+
+ // create card issuer
+ response = client
+ .post("http://127.0.0.1:8080/card_issuers")
+ .insert_header(admin_api_key)
+ .send_json(&create_request)
+ .await
+ .unwrap();
+ assert_eq!(response.status(), awc::http::StatusCode::OK);
+
+ // duplicate insert should fail
+ response = client
+ .post("http://127.0.0.1:8080/card_issuers")
+ .insert_header(admin_api_key)
+ .send_json(&create_request)
+ .await
+ .unwrap();
+ response_body = response.json::<serde_json::Value>().await.unwrap();
+ println!("card-issuer-duplicate: {response:?} : {response_body:?}");
+ assert_eq!(response.status(), awc::http::StatusCode::BAD_REQUEST);
+
+ // update with non-existent id should fail
+ response = client
+ .put("http://127.0.0.1:8080/card_issuers/non_existent_id")
+ .insert_header(admin_api_key)
+ .send_json(&serde_json::json!({ "issuer_name": "NEW NAME" }))
+ .await
+ .unwrap();
+ response_body = response.json::<serde_json::Value>().await.unwrap();
+ println!("card-issuer-update-not-found: {response:?} : {response_body:?}");
+ assert_eq!(response.status(), awc::http::StatusCode::NOT_FOUND);
+
+ // create with empty name should fail
+ response = client
+ .post("http://127.0.0.1:8080/card_issuers")
+ .insert_header(admin_api_key)
+ .send_json(&serde_json::json!({ "issuer_name": "" }))
+ .await
+ .unwrap();
+ response_body = response.json::<serde_json::Value>().await.unwrap();
+ println!("card-issuer-empty-name: {response:?} : {response_body:?}");
+ assert_eq!(
+ response.status(),
+ awc::http::StatusCode::UNPROCESSABLE_ENTITY
+ );
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index d4bc1c53dc..dd890e5df0 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -311,6 +311,12 @@ pub enum Flow {
ToggleDynamicRouting,
/// Update dynamic routing config
UpdateDynamicRoutingConfigs,
+ /// Add a card issuer to the catalog
+ AddCardIssuer,
+ /// Update a card issuer in the catalog
+ UpdateCardIssuer,
+ /// List card issuers from the catalog
+ ListCardIssuers,
/// Add record to blocklist
AddToBlocklist,
/// Delete record from blocklist
diff --git a/crates/storage_impl/src/card_issuer.rs b/crates/storage_impl/src/card_issuer.rs
new file mode 100644
index 0000000000..8a181b9ed8
--- /dev/null
+++ b/crates/storage_impl/src/card_issuer.rs
@@ -0,0 +1,183 @@
+use common_utils::id_type;
+pub use diesel_models::card_issuer::{CardIssuer, NewCardIssuer, UpdateCardIssuer};
+use error_stack::report;
+use hyperswitch_domain_models::card_issuer::CardIssuersInterface;
+use router_env::{instrument, tracing};
+
+use crate::{
+ errors::StorageError,
+ kv_router_store::KVRouterStore,
+ utils::{pg_connection_read, pg_connection_write},
+ CustomResult, DatabaseStore, MockDb, RouterStore,
+};
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> CardIssuersInterface for RouterStore<T> {
+ type Error = StorageError;
+
+ #[instrument(skip_all)]
+ async fn insert_card_issuer(
+ &self,
+ new: NewCardIssuer,
+ ) -> CustomResult<CardIssuer, StorageError> {
+ let conn = pg_connection_write(self).await?;
+ new.insert(&conn)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn update_card_issuer(
+ &self,
+ id: id_type::CardIssuerId,
+ update: UpdateCardIssuer,
+ ) -> CustomResult<CardIssuer, StorageError> {
+ let conn = pg_connection_write(self).await?;
+ CardIssuer::update(&conn, id, update)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn list_card_issuers(
+ &self,
+ query: Option<String>,
+ limit: Option<u8>,
+ ) -> CustomResult<Vec<CardIssuer>, StorageError> {
+ let conn = pg_connection_read(self).await?;
+ CardIssuer::list_filtered(&conn, query, limit.map(i64::from))
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn get_card_issuers_by_ids(
+ &self,
+ ids: Vec<id_type::CardIssuerId>,
+ ) -> CustomResult<Vec<CardIssuer>, StorageError> {
+ let conn = pg_connection_read(self).await?;
+ CardIssuer::find_by_ids(&conn, ids)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+}
+
+#[async_trait::async_trait]
+impl<T: DatabaseStore> CardIssuersInterface for KVRouterStore<T> {
+ type Error = StorageError;
+
+ #[instrument(skip_all)]
+ async fn insert_card_issuer(
+ &self,
+ new: NewCardIssuer,
+ ) -> CustomResult<CardIssuer, StorageError> {
+ let conn = pg_connection_write(self).await?;
+ new.insert(&conn)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn update_card_issuer(
+ &self,
+ id: id_type::CardIssuerId,
+ update: UpdateCardIssuer,
+ ) -> CustomResult<CardIssuer, StorageError> {
+ let conn = pg_connection_write(self).await?;
+ CardIssuer::update(&conn, id, update)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn list_card_issuers(
+ &self,
+ query: Option<String>,
+ limit: Option<u8>,
+ ) -> CustomResult<Vec<CardIssuer>, StorageError> {
+ let conn = pg_connection_read(self).await?;
+ CardIssuer::list_filtered(&conn, query, limit.map(i64::from))
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn get_card_issuers_by_ids(
+ &self,
+ ids: Vec<id_type::CardIssuerId>,
+ ) -> CustomResult<Vec<CardIssuer>, StorageError> {
+ let conn = pg_connection_read(self).await?;
+ CardIssuer::find_by_ids(&conn, ids)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ }
+}
+
+#[async_trait::async_trait]
+impl CardIssuersInterface for MockDb {
+ type Error = StorageError;
+
+ async fn insert_card_issuer(
+ &self,
+ new: NewCardIssuer,
+ ) -> CustomResult<CardIssuer, StorageError> {
+ let card_issuer = CardIssuer {
+ id: new.id,
+ issuer_name: new.issuer_name,
+ created_at: new.created_at,
+ last_modified_at: new.last_modified_at,
+ };
+ self.card_issuers.lock().await.push(card_issuer.clone());
+ Ok(card_issuer)
+ }
+
+ async fn update_card_issuer(
+ &self,
+ id: id_type::CardIssuerId,
+ update: UpdateCardIssuer,
+ ) -> CustomResult<CardIssuer, StorageError> {
+ let mut card_issuers = self.card_issuers.lock().await;
+ let card_issuer =
+ card_issuers
+ .iter_mut()
+ .find(|ci| ci.id == id)
+ .ok_or(StorageError::ValueNotFound(format!(
+ "No card issuer found for id = {id:?}"
+ )))?;
+ card_issuer.issuer_name = update.issuer_name;
+ card_issuer.last_modified_at = update.last_modified_at;
+ Ok(card_issuer.clone())
+ }
+
+ async fn list_card_issuers(
+ &self,
+ query: Option<String>,
+ limit: Option<u8>,
+ ) -> CustomResult<Vec<CardIssuer>, StorageError> {
+ let card_issuers = self.card_issuers.lock().await;
+ let filtered: Vec<CardIssuer> = card_issuers
+ .iter()
+ .filter(|ci| {
+ query
+ .as_ref()
+ .is_none_or(|q| ci.issuer_name.contains(q.as_str()))
+ })
+ .take(limit.map_or(usize::MAX, usize::from))
+ .cloned()
+ .collect();
+ Ok(filtered)
+ }
+
+ async fn get_card_issuers_by_ids(
+ &self,
+ ids: Vec<id_type::CardIssuerId>,
+ ) -> CustomResult<Vec<CardIssuer>, StorageError> {
+ let card_issuers = self.card_issuers.lock().await;
+ let filtered = card_issuers
+ .iter()
+ .filter(|ci| ids.contains(&ci.id))
+ .cloned()
+ .collect();
+ Ok(filtered)
+ }
+}
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index 149be3048c..7238a5cf69 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -12,6 +12,7 @@ use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore};
mod address;
pub mod business_profile;
pub mod callback_mapper;
+pub mod card_issuer;
pub mod cards_info;
pub mod config;
pub mod configs;
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 3341bfad8a..2007a107e2 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -67,6 +67,7 @@ pub struct MockDb {
pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>,
pub hyperswitch_ai_interactions:
Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>,
+ pub card_issuers: Arc<Mutex<Vec<store::card_issuer::CardIssuer>>>,
pub key_manager_state: Option<KeyManagerState>,
}
@@ -125,6 +126,7 @@ impl MockDb {
user_authentication_methods: Default::default(),
themes: Default::default(),
hyperswitch_ai_interactions: Default::default(),
+ card_issuers: Default::default(),
key_manager_state: Some(key_manager_state),
})
}
diff --git a/migrations/2026-03-18-000001_create_card_issuers_table/down.sql b/migrations/2026-03-18-000001_create_card_issuers_table/down.sql
new file mode 100644
index 0000000000..725297c716
--- /dev/null
+++ b/migrations/2026-03-18-000001_create_card_issuers_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+DROP TABLE IF EXISTS card_issuers;
diff --git a/migrations/2026-03-18-000001_create_card_issuers_table/up.sql b/migrations/2026-03-18-000001_create_card_issuers_table/up.sql
new file mode 100644
index 0000000000..7b54587cb3
--- /dev/null
+++ b/migrations/2026-03-18-000001_create_card_issuers_table/up.sql
@@ -0,0 +1,7 @@
+-- Your SQL goes here
+CREATE TABLE IF NOT EXISTS card_issuers (
+ id VARCHAR(64) PRIMARY KEY,
+ issuer_name VARCHAR NOT NULL UNIQUE,
+ created_at TIMESTAMP NOT NULL,
+ last_modified_at TIMESTAMP NOT NULL
+);