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(network_token): NT eligibility API in v2 (#10670)

Sarthak Sonide666c89c4c2
diff --git a/config/config.example.toml b/config/config.example.toml
index c9cd210d55..80a507d4ea 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -1247,6 +1247,7 @@ key_id= "" # key id to encrypt data for token service
delete_token_url= "" # base url to delete token from token service
check_token_status_url= "" # base url to check token status from token service
webhook_source_verification_key= "" # webhook source verification key to verify the webhook payload from token service
+check_tokenize_eligibility_url="" # base url to check tokenization eligibility from token service
[network_tokenization_supported_connectors]
connector_list = "adyen,cybersource,peachpayments" # Supported connectors for network tokenization
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index f52902c1e2..8681ff8360 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -361,6 +361,7 @@ key_id= "" # key id to encrypt data for token service
delete_token_url= "" # base url to delete token from token service
check_token_status_url= "" # base url to check token status from token service
webhook_source_verification_key= "" # webhook source verification key to verify the webhook payload from token service
+check_tokenize_eligibility_url="" # base url to check tokenization eligibility from token service
[grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration
host = "localhost" # Client Host
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 7cf9c9388a..bb25fc6b08 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -3622,6 +3622,26 @@ pub enum NetworkTokenStatusCheckResponse {
FailureResponse(NetworkTokenStatusCheckFailureResponse),
}
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+pub struct NetworkTokenEligibilityRequest {
+ /// The card bin to retrieve information for
+ pub card_bin: String,
+}
+
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+pub struct GetNetworkTokenEiligibilityResponse {
+ /// Indicates if the card bin is eligible for network tokenization for the particular merchant
+ pub eligible_for_network_tokenization: bool,
+}
+
+#[cfg(feature = "v2")]
+impl common_utils::events::ApiEventMetric for NetworkTokenEligibilityRequest {}
+
+#[cfg(feature = "v2")]
+impl common_utils::events::ApiEventMetric for GetNetworkTokenEiligibilityResponse {}
+
#[cfg(feature = "v2")]
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct PaymentMethodGetTokenDetailsResponse {
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index e6c9aacdd9..21088e7f77 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -604,6 +604,7 @@ pub struct NetworkTokenizationSupportedCardNetworks {
pub struct NetworkTokenizationService {
pub generate_token_url: url::Url,
pub fetch_token_url: url::Url,
+ pub check_tokenize_eligibility_url: url::Url,
pub token_service_api_key: Secret<String>,
pub public_key: Secret<String>,
pub private_key: Secret<String>,
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 6e932e59cb..88088b2fc8 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -887,6 +887,32 @@ fn get_card_network_with_us_local_debit_network_override(
}
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all)]
+pub async fn get_card_nt_eligibility(
+ state: &SessionState,
+ req: api::NetworkTokenEligibilityRequest,
+ _platform: &domain::Platform,
+ profile: &domain::Profile,
+) -> RouterResponse<api::GetNetworkTokenEiligibilityResponse> {
+ when(!profile.is_network_tokenization_enabled, || {
+ Err(report!(errors::ApiErrorResponse::NotSupported {
+ message: "Network tokenization is not enabled for this profile".to_string()
+ }))
+ })?;
+
+ let response = network_tokenization::make_nt_eligibility_call(state, req)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to fetch network token eligibility from tokenization service")?;
+
+ Ok(services::ApplicationResponse::Json(
+ api::GetNetworkTokenEiligibilityResponse {
+ eligible_for_network_tokenization: response.tokenize_support,
+ },
+ ))
+}
+
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn create_payment_method(
diff --git a/crates/router/src/core/payment_methods/network_tokenization.rs b/crates/router/src/core/payment_methods/network_tokenization.rs
index 8b9b80db1c..06521f3495 100644
--- a/crates/router/src/core/payment_methods/network_tokenization.rs
+++ b/crates/router/src/core/payment_methods/network_tokenization.rs
@@ -154,6 +154,79 @@ pub async fn mk_tokenization_req(
Ok((cn_response.clone(), Some(cn_response.card_reference)))
}
+#[cfg(feature = "v2")]
+pub async fn make_nt_eligibility_call(
+ state: &routes::SessionState,
+ payload: api_payment_methods::NetworkTokenEligibilityRequest,
+) -> CustomResult<pm_types::NTEligibilityResponse, errors::NetworkTokenizationError> {
+ let tokenization_service = match &state.conf.network_tokenization_service {
+ Some(nt_service) => Ok(nt_service.get_inner()),
+ None => Err(report!(
+ errors::NetworkTokenizationError::NetworkTokenizationServiceNotConfigured
+ )),
+ }?;
+
+ let url_string = format!(
+ "{}/{}?options.check_tokenize_support={}",
+ tokenization_service.check_tokenize_eligibility_url.as_str(),
+ payload.card_bin.clone(),
+ true
+ );
+
+ let mut request = services::Request::new(services::Method::Get, &url_string);
+ request.add_header(headers::CONTENT_TYPE, "application/json".into());
+ request.add_header(
+ headers::AUTHORIZATION,
+ tokenization_service
+ .token_service_api_key
+ .peek()
+ .clone()
+ .into_masked(),
+ );
+ request.add_default_headers();
+
+ let response = services::call_connector_api(state, request, "fetch_nt_eligibility")
+ .await
+ .change_context(errors::NetworkTokenizationError::ApiError);
+
+ let res = response
+ .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)
+ .attach_printable("Error while receiving response")
+ .and_then(|inner| match inner {
+ Err(err_res) => {
+ logger::error!("Error response from nt eligibility call: {:?}", err_res);
+ let parsed_error: pm_types::NetworkTokenErrorResponse = err_res
+ .response
+ .parse_struct("Card Network Tokenization Response")
+ .change_context(
+ errors::NetworkTokenizationError::ResponseDeserializationFailed,
+ )?;
+ logger::error!(
+ error_code = %parsed_error.error_info.code,
+ developer_message = %parsed_error.error_info.developer_message,
+ "Network tokenization error: {:?}",
+ parsed_error.error_message
+ );
+ Err(errors::NetworkTokenizationError::ApiError).attach_printable(format!(
+ "Network Tokenization ApiError : {:?}",
+ parsed_error.error_info.code
+ ))
+ }
+ Ok(res) => Ok(res),
+ })
+ .inspect_err(|err| {
+ logger::error!("Error while deserializing response: {:?}", err);
+ })?;
+
+ let network_response: pm_types::NTEligibilityResponse = res
+ .response
+ .parse_struct("NTEligibilityResponse")
+ .change_context(errors::NetworkTokenizationError::ResponseDeserializationFailed)?;
+ logger::debug!("Network Token Response: {:?}", network_response);
+
+ Ok(network_response)
+}
+
#[cfg(feature = "v2")]
pub async fn generate_network_token(
state: &routes::SessionState,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 712e07842e..a52fa6e1c3 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1589,6 +1589,10 @@ impl PaymentMethods {
web::resource("/create-intent")
.route(web::post().to(payment_methods::create_payment_method_intent_api)),
)
+ .service(
+ web::resource("/get-network-token-eligibility")
+ .route(web::get().to(payment_methods::get_pm_nt_eligibility_api)),
+ )
.service(
web::resource("/{payment_method_id}/check-network-token-status")
.route(web::get().to(payment_methods::network_token_status_check_api)),
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 12bed2a845..4456e3a264 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -373,9 +373,10 @@ impl From<Flow> for ApiIdentifier {
Flow::Proxy => Self::Proxy,
Flow::ProfileAcquirerCreate | Flow::ProfileAcquirerUpdate => Self::ProfileAcquirer,
Flow::ThreeDsDecisionRuleExecute => Self::ThreeDsDecisionRule,
- Flow::TokenizationCreate | Flow::TokenizationRetrieve | Flow::TokenizationDelete => {
- Self::GenericTokenization
- }
+ Flow::TokenizationCreate
+ | Flow::TokenizationRetrieve
+ | Flow::TokenizationDelete
+ | Flow::NetworkTokenEligibilityCheck => Self::GenericTokenization,
Flow::RecoveryDataBackfill | Flow::RevenueRecoveryRedis => Self::RecoveryRecovery,
}
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 80be6240f5..bf7dcf446a 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -101,6 +101,38 @@ pub async fn create_payment_method_api(
.await
}
+#[cfg(feature = "v2")]
+#[instrument(skip_all, fields(flow = ?Flow::NetworkTokenEligibilityCheck))]
+pub async fn get_pm_nt_eligibility_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::NetworkTokenEligibilityRequest>,
+) -> HttpResponse {
+ let flow = Flow::NetworkTokenEligibilityCheck;
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, auth: auth::AuthenticationData, req, _req_state| async move {
+ Box::pin(payment_methods_routes::get_card_nt_eligibility(
+ &state,
+ req,
+ &auth.platform,
+ &auth.profile,
+ ))
+ .await
+ },
+ &auth::V2ApiKeyAuth {
+ is_connected_allowed: false,
+ is_platform_allowed: false,
+ },
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "v2")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsCreate))]
pub async fn create_payment_method_intent_api(
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index 96c0c5987d..1beebdb571 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -2,17 +2,18 @@
pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CardNetworkTokenizeRequest,
CardNetworkTokenizeResponse, CardType, CustomerPaymentMethodResponseItem,
- DeleteTokenizeByTokenRequest, GetTokenizePayloadRequest, GetTokenizePayloadResponse,
- ListCountriesCurrenciesRequest, MigrateCardDetail, NetworkTokenDetailsPaymentMethod,
- NetworkTokenDetailsResponse, NetworkTokenResponse, PaymentMethodCollectLinkRenderRequest,
- PaymentMethodCollectLinkRequest, PaymentMethodCreate, PaymentMethodCreateData,
- PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodIntentConfirm,
- PaymentMethodIntentCreate, PaymentMethodListData, PaymentMethodListResponseForSession,
- PaymentMethodMigrate, PaymentMethodMigrateResponse, PaymentMethodResponse,
- PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData, PaymentMethodsData,
- ProxyCardDetails, RequestPaymentMethodTypes, TokenDataResponse, TokenDetailsResponse,
- TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1, TokenizedCardValue2,
- TokenizedWalletValue1, TokenizedWalletValue2, TotalPaymentMethodCountResponse,
+ DeleteTokenizeByTokenRequest, GetNetworkTokenEiligibilityResponse, GetTokenizePayloadRequest,
+ GetTokenizePayloadResponse, ListCountriesCurrenciesRequest, MigrateCardDetail,
+ NetworkTokenDetailsPaymentMethod, NetworkTokenDetailsResponse, NetworkTokenEligibilityRequest,
+ NetworkTokenResponse, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest,
+ PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
+ PaymentMethodIntentConfirm, PaymentMethodIntentCreate, PaymentMethodListData,
+ PaymentMethodListResponseForSession, PaymentMethodMigrate, PaymentMethodMigrateResponse,
+ PaymentMethodResponse, PaymentMethodResponseData, PaymentMethodUpdate, PaymentMethodUpdateData,
+ PaymentMethodsData, ProxyCardDetails, RequestPaymentMethodTypes, TokenDataResponse,
+ TokenDetailsResponse, TokenizePayloadEncrypted, TokenizePayloadRequest, TokenizedCardValue1,
+ TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
+ TotalPaymentMethodCountResponse,
};
#[cfg(feature = "v1")]
pub use api_models::payment_methods::{
diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs
index 359209c3ea..97d6ba9f4f 100644
--- a/crates/router/src/types/payment_methods.rs
+++ b/crates/router/src/types/payment_methods.rs
@@ -208,6 +208,39 @@ pub struct CardNetworkTokenResponse {
pub payload: Secret<String>, //encrypted payload
}
+#[cfg(feature = "v2")]
+#[derive(Debug, Serialize)]
+pub struct NTEligibilityRequest {
+ pub check_tokenize_support: bool,
+}
+
+#[cfg(feature = "v2")]
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
+pub struct NTEligibilityResponse {
+ /// country associated with the card
+ pub country: Option<String>,
+ /// extended card type
+ pub extended_card_type: Option<String>,
+ /// card brand (like VISA, MASTERCARD etc)
+ pub brand: Option<String>,
+ /// bank code as per juspay
+ pub juspay_bank_code: Option<String>,
+ /// object type
+ pub object: Option<String>,
+ /// card bin length
+ pub id: String,
+ /// card sub type
+ pub card_sub_type: Option<String>,
+ /// indicates whether the (merchant + card_bin) is enabled tokenization
+ #[serde(default)]
+ pub tokenize_support: bool,
+
+ /// card type (like CREDIT, DEBIT etc)
+ #[serde(rename = "type")]
+ pub card_type: Option<String>,
+ /// bank associated with the card
+ pub bank: Option<String>,
+}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 291c684a7d..b28c16df7d 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -156,6 +156,8 @@ pub enum Flow {
PaymentMethodsDelete,
/// Network token status check flow.
NetworkTokenStatusCheck,
+ /// Network token eligibility check flow.
+ NetworkTokenEligibilityCheck,
/// Default Payment method flow.
DefaultPaymentMethodsSet,
/// Payments create flow.