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: Added PreAuthenticate Flow for Nmi HS<>UCS tunnel (#10632)

Amitsingh Tanwarac2119ac8382
diff --git a/crates/hyperswitch_connectors/src/connectors/nmi.rs b/crates/hyperswitch_connectors/src/connectors/nmi.rs
index 73826e4f65..d55fd5df7b 100644
--- a/crates/hyperswitch_connectors/src/connectors/nmi.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nmi.rs
@@ -14,13 +14,15 @@ use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
- AccessTokenAuth, Authorize, Capture, CompleteAuthorize, Execute, PSync, PaymentMethodToken,
- PreProcessing, RSync, Session, SetupMandate, Void,
+ unified_authentication_service::PreAuthenticate, AccessTokenAuth, Authorize, Capture,
+ CompleteAuthorize, Execute, PSync, PaymentMethodToken, PreProcessing, RSync, Session,
+ SetupMandate, Void,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
- PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
- PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
+ PaymentsPreAuthenticateData, PaymentsPreProcessingData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
@@ -28,8 +30,9 @@ use hyperswitch_domain_models::{
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
- PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData,
- PaymentsSyncRouterData, RefundsRouterData, SetupMandateRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsPreAuthenticateRouterData,
+ PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundsRouterData,
+ SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
@@ -42,8 +45,8 @@ use hyperswitch_interfaces::{
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
- PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType,
- RefundSyncType, Response, SetupMandateType,
+ PaymentsPreAuthenticateType, PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType,
+ RefundExecuteType, RefundSyncType, Response, SetupMandateType,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
@@ -81,6 +84,7 @@ impl api::Refund for Nmi {}
impl api::RefundExecute for Nmi {}
impl api::RefundSync for Nmi {}
impl api::PaymentToken for Nmi {}
+impl api::PaymentsPreAuthenticate for Nmi {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nmi
where
@@ -164,6 +168,87 @@ impl ConnectorValidation for Nmi {
}
}
+impl ConnectorIntegration<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>
+ for Nmi
+{
+ fn get_headers(
+ &self,
+ req: &PaymentsPreAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &PaymentsPreAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, ConnectorError> {
+ Ok(format!("{}api/transact.php", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &PaymentsPreAuthenticateRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<RequestContent, ConnectorError> {
+ let connector_req = nmi::NmiVaultRequest::try_from(req)?;
+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &PaymentsPreAuthenticateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, ConnectorError> {
+ let req = Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .attach_default_headers()
+ .headers(PaymentsPreAuthenticateType::get_headers(
+ self, req, connectors,
+ )?)
+ .url(&PaymentsPreAuthenticateType::get_url(
+ self, req, connectors,
+ )?)
+ .set_body(PaymentsPreAuthenticateType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ );
+ Ok(req)
+ }
+
+ fn handle_response(
+ &self,
+ data: &PaymentsPreAuthenticateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<PaymentsPreAuthenticateRouterData, ConnectorError> {
+ let response: nmi::NmiVaultResponse = serde_urlencoded::from_bytes(&res.response)
+ .change_context(ConnectorError::ResponseDeserializationFailed)?;
+ event_builder.map(|i| i.set_response_body(&response));
+ router_env::logger::info!(connector_response=?response);
+ RouterData::try_from(ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
+}
+
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Nmi
{
diff --git a/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
index da03f4990c..f7693952b9 100644
--- a/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
@@ -18,8 +18,9 @@ use hyperswitch_domain_models::{
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
- PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData,
- PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsPreAuthenticateRouterData,
+ PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
+ RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::errors::ConnectorError;
@@ -28,8 +29,8 @@ use serde::{Deserialize, Serialize};
use crate::{
types::{
- PaymentsPreprocessingResponseRouterData, PaymentsResponseRouterData,
- RefundsResponseRouterData, ResponseRouterData,
+ PaymentsPreAuthenticateResponseRouterData, PaymentsPreprocessingResponseRouterData,
+ PaymentsResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
get_unimplemented_payment_method_error_message, to_currency_base_unit_asf64,
@@ -112,32 +113,56 @@ pub enum CustomerAction {
UpdateCustomer,
}
+fn try_build_nmi_vault_request_from_router_data(
+ connector_auth_type: &ConnectorAuthType,
+ payment_method_data: Option<PaymentMethodData>,
+ billing_address: Result<&hyperswitch_domain_models::address::AddressDetails, Error>,
+) -> Result<NmiVaultRequest, Error> {
+ let auth_type: NmiAuthType = connector_auth_type.try_into()?;
+ let (ccnumber, ccexp, cvv) = get_card_details(payment_method_data)?;
+ let billing_details = billing_address?;
+ let first_name = billing_details.get_first_name()?;
+
+ Ok(NmiVaultRequest {
+ security_key: auth_type.api_key,
+ ccnumber,
+ ccexp,
+ cvv,
+ first_name: first_name.clone(),
+ last_name: billing_details
+ .get_last_name()
+ .unwrap_or(first_name)
+ .clone(),
+ address1: billing_details.line1.clone(),
+ address2: billing_details.line2.clone(),
+ city: billing_details.city.clone(),
+ state: billing_details.state.clone(),
+ country: billing_details.country,
+ zip: billing_details.zip.clone(),
+ customer_vault: CustomerAction::AddCustomer,
+ })
+}
+
+// Marker trait: only implemented for the allowed RouterData types
impl TryFrom<&PaymentsPreProcessingRouterData> for NmiVaultRequest {
type Error = Error;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
- let auth_type: NmiAuthType = (&item.connector_auth_type).try_into()?;
- let (ccnumber, ccexp, cvv) = get_card_details(item.request.payment_method_data.clone())?;
- let billing_details = item.get_billing_address()?;
- let first_name = billing_details.get_first_name()?;
+ try_build_nmi_vault_request_from_router_data(
+ &item.connector_auth_type,
+ item.request.payment_method_data.clone(),
+ item.get_billing_address(),
+ )
+ }
+}
- Ok(Self {
- security_key: auth_type.api_key,
- ccnumber,
- ccexp,
- cvv,
- first_name: first_name.clone(),
- last_name: billing_details
- .get_last_name()
- .unwrap_or(first_name)
- .clone(),
- address1: billing_details.line1.clone(),
- address2: billing_details.line2.clone(),
- city: billing_details.city.clone(),
- state: billing_details.state.clone(),
- country: billing_details.country,
- zip: billing_details.zip.clone(),
- customer_vault: CustomerAction::AddCustomer,
- })
+impl TryFrom<&PaymentsPreAuthenticateRouterData> for NmiVaultRequest {
+ type Error = Error;
+ fn try_from(item: &PaymentsPreAuthenticateRouterData) -> Result<Self, Self::Error> {
+ try_build_nmi_vault_request_from_router_data(
+ &item.connector_auth_type,
+ Some(item.request.payment_method_data.clone()),
+ item.get_billing_address(),
+ )
}
}
@@ -166,6 +191,91 @@ pub struct NmiVaultResponse {
pub transactionid: String,
}
+fn process_nmi_vault_response(
+ connector_auth_type: &ConnectorAuthType,
+ amount: Option<i64>,
+ currency: Option<Currency>,
+ vault_response: &NmiVaultResponse,
+ http_code: u16,
+ connector_request_reference_id: String,
+) -> Result<(Result<PaymentsResponseData, ErrorResponse>, AttemptStatus), Error> {
+ let auth_type: NmiAuthType = connector_auth_type.try_into()?;
+ let amount_data = amount.ok_or(ConnectorError::MissingRequiredField {
+ field_name: "amount",
+ })?;
+ let currency_data = currency.ok_or(ConnectorError::MissingRequiredField {
+ field_name: "currency",
+ })?;
+
+ build_nmi_vault_response(
+ auth_type,
+ amount_data,
+ currency_data,
+ vault_response,
+ http_code,
+ connector_request_reference_id,
+ )
+}
+
+fn build_nmi_vault_response(
+ auth_type: NmiAuthType,
+ amount_data: i64,
+ currency_data: Currency,
+ vault_response: &NmiVaultResponse,
+ http_code: u16,
+ connector_request_reference_id: String,
+) -> Result<(Result<PaymentsResponseData, ErrorResponse>, AttemptStatus), Error> {
+ let (response, status) = match vault_response.response {
+ Response::Approved => (
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
+ redirection_data: Box::new(Some(RedirectForm::Nmi {
+ amount: to_currency_base_unit_asf64(amount_data, currency_data.to_owned())?
+ .to_string(),
+ currency: currency_data,
+ customer_vault_id: vault_response
+ .customer_vault_id
+ .clone()
+ .ok_or(ConnectorError::MissingRequiredField {
+ field_name: "customer_vault_id",
+ })?
+ .peek()
+ .to_string(),
+ public_key: auth_type.public_key.ok_or(
+ ConnectorError::InvalidConnectorConfig {
+ config: "public_key",
+ },
+ )?,
+ order_id: connector_request_reference_id.clone(),
+ })),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(vault_response.transactionid.clone()),
+ incremental_authorization_allowed: None,
+ charges: None,
+ }),
+ AttemptStatus::AuthenticationPending,
+ ),
+ Response::Declined | Response::Error => (
+ Err(ErrorResponse {
+ code: vault_response.response_code.clone(),
+ message: vault_response.responsetext.to_owned(),
+ reason: Some(vault_response.responsetext.clone()),
+ status_code: http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(vault_response.transactionid.clone()),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ }),
+ AttemptStatus::Failure,
+ ),
+ };
+ Ok((response, status))
+}
+
impl TryFrom<PaymentsPreprocessingResponseRouterData<NmiVaultResponse>>
for PaymentsPreProcessingRouterData
{
@@ -173,69 +283,39 @@ impl TryFrom<PaymentsPreprocessingResponseRouterData<NmiVaultResponse>>
fn try_from(
item: PaymentsPreprocessingResponseRouterData<NmiVaultResponse>,
) -> Result<Self, Self::Error> {
- let auth_type: NmiAuthType = (&item.data.connector_auth_type).try_into()?;
- let amount_data = item
- .data
- .request
- .amount
- .ok_or(ConnectorError::MissingRequiredField {
- field_name: "amount",
- })?;
- let currency_data =
- item.data
- .request
- .currency
- .ok_or(ConnectorError::MissingRequiredField {
- field_name: "currency",
- })?;
- let (response, status) = match item.response.response {
- Response::Approved => (
- Ok(PaymentsResponseData::TransactionResponse {
- resource_id: ResponseId::NoResponseId,
- redirection_data: Box::new(Some(RedirectForm::Nmi {
- amount: to_currency_base_unit_asf64(amount_data, currency_data.to_owned())?
- .to_string(),
- currency: currency_data,
- customer_vault_id: item
- .response
- .customer_vault_id
- .ok_or(ConnectorError::MissingRequiredField {
- field_name: "customer_vault_id",
- })?
- .peek()
- .to_string(),
- public_key: auth_type.public_key.ok_or(
- ConnectorError::InvalidConnectorConfig {
- config: "public_key",
- },
- )?,
- order_id: item.data.connector_request_reference_id.clone(),
- })),
- mandate_reference: Box::new(None),
- connector_metadata: None,
- network_txn_id: None,
- connector_response_reference_id: Some(item.response.transactionid),
- incremental_authorization_allowed: None,
- charges: None,
- }),
- AttemptStatus::AuthenticationPending,
- ),
- Response::Declined | Response::Error => (
- Err(ErrorResponse {
- code: item.response.response_code,
- message: item.response.responsetext.to_owned(),
- reason: Some(item.response.responsetext),
- status_code: item.http_code,
- attempt_status: None,
- connector_transaction_id: Some(item.response.transactionid),
- network_advice_code: None,
- network_decline_code: None,
- network_error_message: None,
- connector_metadata: None,
- }),
- AttemptStatus::Failure,
- ),
- };
+ let (response, status) = process_nmi_vault_response(
+ &item.data.connector_auth_type,
+ item.data.request.amount,
+ item.data.request.currency,
+ &item.response,
+ item.http_code,
+ item.data.connector_request_reference_id.clone(),
+ )?;
+
+ Ok(Self {
+ status,
+ response,
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<PaymentsPreAuthenticateResponseRouterData<NmiVaultResponse>>
+ for PaymentsPreAuthenticateRouterData
+{
+ type Error = Error;
+ fn try_from(
+ item: PaymentsPreAuthenticateResponseRouterData<NmiVaultResponse>,
+ ) -> Result<Self, Self::Error> {
+ let (response, status) = process_nmi_vault_response(
+ &item.data.connector_auth_type,
+ Some(item.data.request.amount),
+ item.data.request.currency,
+ &item.response,
+ item.http_code,
+ item.data.connector_request_reference_id.clone(),
+ )?;
+
Ok(Self {
status,
response,
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index c2e5ed00e0..795c6dd140 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -2000,7 +2000,6 @@ default_imp_for_pre_authenticate_steps!(
connectors::Netcetera,
connectors::Nexinets,
connectors::Nexixpay,
- connectors::Nmi,
connectors::Nomupay,
connectors::Noon,
connectors::Nordea,
diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs
index 4afe6d3b02..852b73294b 100644
--- a/crates/hyperswitch_connectors/src/types.rs
+++ b/crates/hyperswitch_connectors/src/types.rs
@@ -8,6 +8,7 @@ use hyperswitch_domain_models::{
authentication::{
Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,
},
+ unified_authentication_service::PreAuthenticate,
Accept, AccessTokenAuth, Authorize, Capture, CreateOrder, Defend, Dsync, Evidence,
ExtendAuthorization, Fetch, PSync, PostProcessing, PreProcessing, Retrieve, Session,
Upload, Void,
@@ -20,9 +21,9 @@ use hyperswitch_domain_models::{
AcceptDisputeRequestData, AccessTokenRequestData, CreateOrderRequestData,
DefendDisputeRequestData, DisputeSyncData, FetchDisputesRequestData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsExtendAuthorizationData,
- PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsSessionData,
- PaymentsSyncData, RefundsData, RetrieveFileRequestData, SubmitEvidenceRequestData,
- UploadFileRequestData,
+ PaymentsPostProcessingData, PaymentsPreAuthenticateData, PaymentsPreProcessingData,
+ PaymentsSessionData, PaymentsSyncData, RefundsData, RetrieveFileRequestData,
+ SubmitEvidenceRequestData, UploadFileRequestData,
},
router_response_types::{
AcceptDisputeResponse, AuthenticationResponseData, DefendDisputeResponse,
@@ -54,6 +55,8 @@ pub(crate) type RefreshTokenRouterData =
pub(crate) type PaymentsCancelResponseRouterData<R> =
ResponseRouterData<Void, R, PaymentsCancelData, PaymentsResponseData>;
+pub(crate) type PaymentsPreAuthenticateResponseRouterData<R> =
+ ResponseRouterData<PreAuthenticate, R, PaymentsPreAuthenticateData, PaymentsResponseData>;
pub(crate) type PaymentsPreprocessingResponseRouterData<R> =
ResponseRouterData<PreProcessing, R, PaymentsPreProcessingData, PaymentsResponseData>;
pub(crate) type PaymentsSessionResponseRouterData<R> =