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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(connector): [FINIX] webhook + statement descriptor (#10758)
Nithin N761183bb198a
diff --git a/crates/hyperswitch_connectors/src/connectors/finix.rs b/crates/hyperswitch_connectors/src/connectors/finix.rsindex 831a3aa793..444ff6ca3d 100644--- a/crates/hyperswitch_connectors/src/connectors/finix.rs+++ b/crates/hyperswitch_connectors/src/connectors/finix.rs@@ -1,16 +1,21 @@pub mod transformers;-use std::sync::LazyLock;+use std::{collections::HashMap, sync::LazyLock};+use api_models::webhooks::IncomingWebhookEvent;use base64::Engine;use common_enums::{enums, CaptureMethod, ConnectorIntegrationStatus, PaymentMethodType};use common_utils::{+ crypto::{HmacSha256, VerifySignature},errors::CustomResult,- ext_traits::BytesExt,+ ext_traits::{ByteSliceExt, BytesExt},request::{Method, Request, RequestBuilder, RequestContent},- types::{AmountConvertor, MinorUnit, MinorUnitForConnector},+ types::{+ AmountConvertor, MinorUnit, MinorUnitForConnector, StringMinorUnit,+ StringMinorUnitForConnector,+ },};-use error_stack::{report, ResultExt};+use error_stack::ResultExt;use hyperswitch_domain_models::{payment_method_data::PaymentMethodData,router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},@@ -40,6 +45,7 @@ use hyperswitch_interfaces::{ConnectorValidation,},configs::Connectors,+ disputes::DisputePayload,errors,events::connector_api_logs::ConnectorEvent,types::{self, Response},@@ -49,6 +55,7 @@ use masking::{ExposeInterface, Mask};use transformers as finix;use crate::{+ connectors::finix::transformers::FinixWebhookSignature,constants::headers,types::ResponseRouterData,utils::{self, PaymentMethodDataType},@@ -57,12 +64,14 @@ use crate::{#[derive(Clone)]pub struct Finix {amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),+ amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),}impl Finix {pub fn new() -> &'static Self {&Self {amount_converter: &MinorUnitForConnector,+ amount_converter_webhooks: &StringMinorUnitForConnector,}}}@@ -601,10 +610,12 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Finevent_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {- let response: finix::FinixPaymentsResponse = res+ let combined_response: finix::FinixCombinedPaymentResponse = res.response.parse_struct("finix PaymentsSyncResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;++ let response = combined_response.get_payment_response()?;event_builder.map(|i| i.set_response_body(&response));router_env::logger::info!(connector_response=?response);let response_id = response.id.clone();@@ -872,10 +883,11 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Finix {event_builder: Option<&mut ConnectorEvent>,res: Response,) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {- let response: finix::FinixPaymentsResponse = res+ let combined_response: finix::FinixCombinedPaymentResponse = res.response.parse_struct("FinixPaymentsResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ let response = combined_response.get_payment_response()?;event_builder.map(|i| i.set_response_body(&response));router_env::logger::info!(connector_response=?response);RouterData::try_from(ResponseRouterData {@@ -970,30 +982,6 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Finix {}}-#[async_trait::async_trait]-impl webhooks::IncomingWebhook for Finix {- fn get_webhook_object_reference_id(- &self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,- ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))- }-- fn get_webhook_event_type(- &self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,- ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))- }-- fn get_webhook_resource_object(- &self,- _request: &webhooks::IncomingWebhookRequestDetails<'_>,- ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {- Err(report!(errors::ConnectorError::WebhooksNotImplemented))- }-}-static FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {let default_capture_methods = vec![CaptureMethod::Automatic, CaptureMethod::Manual];@@ -1067,16 +1055,6 @@ static FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = Lazyspecific_features: None,},);- finix_supported_payment_methods.add(- common_enums::PaymentMethod::Wallet,- PaymentMethodType::ApplePay,- PaymentMethodDetails {- mandates: enums::FeatureStatus::NotSupported,- refunds: enums::FeatureStatus::Supported,- supported_capture_methods: default_capture_methods.clone(),- specific_features: None,- },- );finix_supported_payment_methods});@@ -1112,3 +1090,129 @@ impl ConnectorSpecifications for Finix {false}}+fn is_test_webhook(request: &webhooks::IncomingWebhookRequestDetails<'_>) -> bool {+ let req_data = String::from_utf8(request.body.to_vec());+ req_data == Ok("{}".to_string())+}+pub fn decode_finix_signature(+ header_value: &actix_web::http::header::HeaderMap,+) -> Result<FinixWebhookSignature, errors::ConnectorError> {+ let security_header = header_value+ .get("Finix-Signature")+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?+ .to_str()+ .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)?+ .to_owned();++ let map: HashMap<&str, &str> = security_header+ .split(',')+ .map(|kv| {+ let mut parts = kv.trim().splitn(2, '=');+ let key = parts+ .next()+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;+ let value = parts+ .next()+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;+ Ok((key, value))+ })+ .collect::<Result<_, _>>()?;++ let timestamp = map+ .get("timestamp")+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?+ .to_string();++ let sig = map+ .get("sig")+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?+ .as_bytes()+ .to_vec();++ Ok(FinixWebhookSignature { timestamp, sig })+}+#[async_trait::async_trait]+impl webhooks::IncomingWebhook for Finix {+ fn get_webhook_source_verification_algorithm(+ &self,+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<Box<dyn VerifySignature + Send>, errors::ConnectorError> {+ Ok(Box::new(HmacSha256))+ }++ fn get_webhook_source_verification_signature(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {+ let security_header_kvs = decode_finix_signature(request.headers)?;++ hex::decode(security_header_kvs.sig)+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)+ }+ fn get_webhook_source_verification_message(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ _merchant_id: &common_utils::id_type::MerchantId,+ _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {+ let security_header_kvs = decode_finix_signature(request.headers)?;++ Ok(format!(+ "{}:{}",+ &security_header_kvs.timestamp,+ String::from_utf8_lossy(request.body)+ )+ .into_bytes())+ }+ fn get_webhook_object_reference_id(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {+ let webhook_body: finix::FinixWebhookBody =+ request+ .body+ .parse_struct("FinixWebhookBody")+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;++ webhook_body.get_webhook_object_reference_id()+ }++ fn get_webhook_event_type(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {+ if is_test_webhook(request) {+ return Ok(IncomingWebhookEvent::SetupWebhook);+ }+ let webhook_body: finix::FinixWebhookBody =+ request+ .body+ .parse_struct("FinixWebhookBody")+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;++ webhook_body.get_webhook_event_type()+ }+ fn get_dispute_details(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<DisputePayload, errors::ConnectorError> {+ let webhook_body: finix::FinixWebhookBody =+ request+ .body+ .parse_struct("FinixWebhookBody")+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;+ webhook_body.get_dispute_details()+ }+ fn get_webhook_resource_object(+ &self,+ request: &webhooks::IncomingWebhookRequestDetails<'_>,+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {+ let webhook_body: finix::FinixWebhookBody =+ request+ .body+ .parse_struct("FinixWebhookBody")+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;+ Ok(Box::new(webhook_body))+ }+}diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers.rsindex bdf998a1cd..76c64c86bb 100644--- a/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs+++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers.rs@@ -1,9 +1,14 @@pub mod request;pub mod response;-use api_models::payments::MandateReferenceId;+use api_models::{+ payments::{MandateReferenceId, PaymentIdType},+ webhooks::{IncomingWebhookEvent, RefundIdType},+};use base64::Engine;-use common_enums::{enums, AttemptStatus, CaptureMethod, CountryAlpha2, CountryAlpha3};-use common_utils::types::MinorUnit;+use common_enums::{+ enums, AttemptStatus, CaptureMethod, CountryAlpha2, CountryAlpha3, DisputeStage,+};+use common_utils::{errors::CustomResult, types::MinorUnit};use error_stack::ResultExt;use hyperswitch_domain_models::{payment_method_data::{PaymentMethodData, WalletData},@@ -22,7 +27,7 @@ use hyperswitch_domain_models::{},types::RefundsRouterData,};-use hyperswitch_interfaces::{consts, errors::ConnectorError};+use hyperswitch_interfaces::{consts, disputes::DisputePayload, errors::ConnectorError};use masking::{ExposeInterface, Secret};pub use request::*;pub use response::*;@@ -31,7 +36,7 @@ use crate::{types::{RefundsResponseRouterData, ResponseRouterData},unimplemented_payment_method,utils::{- get_unimplemented_payment_method_error_message, AddressDetailsData, CardData,+ self, get_unimplemented_payment_method_error_message, AddressDetailsData, CardData,RouterData as _,},};@@ -187,7 +192,12 @@ impl TryFrom<&FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsResp"Payment method not supported".to_string(),))?,};-+ let statement_descriptor = item+ .router_data+ .request+ .billing_descriptor+ .clone()+ .and_then(|billing_descriptor| billing_descriptor.statement_descriptor);Ok(Self {amount: item.amount,currency: item.router_data.request.currency,@@ -196,6 +206,7 @@ impl TryFrom<&FinixRouterData<'_, Authorize, PaymentsAuthorizeData, PaymentsRespidempotency_id: Some(item.router_data.connector_request_reference_id.clone()),tags: None,three_d_secure: None,+ statement_descriptor,})}}@@ -636,3 +647,132 @@ impl FinixErrorResponse {.unwrap_or(consts::NO_ERROR_MESSAGE.to_string())}}+impl FinixWebhookBody {+ pub fn get_webhook_object_reference_id(+ &self,+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> {+ match &self.webhook_embedded {+ FinixEmbedded::Authorizations { authorizations } => {+ let authorization = authorizations.get_first_event()?;++ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(+ PaymentIdType::ConnectorTransactionId(authorization.id.to_string()),+ ))+ }+ FinixEmbedded::Transfers { transfers } => {+ let transfer = transfers.get_first_event()?;++ match transfer.payment_type {+ Some(FinixPaymentType::REVERSAL) => {+ Ok(api_models::webhooks::ObjectReferenceId::RefundId(+ RefundIdType::ConnectorRefundId(transfer.id.to_string()),+ ))+ }+ // finix platform fee ignored+ Some(FinixPaymentType::FEE) => {+ Err(ConnectorError::WebhookEventTypeNotFound.into())+ }+ _ => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(+ PaymentIdType::ConnectorTransactionId(transfer.id.to_string()),+ )),+ }+ }++ FinixEmbedded::Disputes { disputes } => {+ let dispute = disputes.get_first_event()?;++ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(+ PaymentIdType::ConnectorTransactionId(dispute.transfer.to_string()),+ ))+ }+ }+ }+ pub fn get_webhook_event_type(&self) -> CustomResult<IncomingWebhookEvent, ConnectorError> {+ match &self.webhook_embedded {+ FinixEmbedded::Authorizations { authorizations } => {+ let authorizations = authorizations.get_first_event()?;++ if authorizations.is_void == Some(true) {+ match authorizations.state {+ FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {+ Ok(IncomingWebhookEvent::PaymentIntentCancelFailure)+ }+ FinixState::PENDING => Ok(IncomingWebhookEvent::PaymentIntentProcessing),+ FinixState::SUCCEEDED => Ok(IncomingWebhookEvent::PaymentIntentCancelled),+ }+ } else {+ match authorizations.state {+ FinixState::PENDING => Ok(IncomingWebhookEvent::PaymentIntentProcessing),++ FinixState::SUCCEEDED => {+ Ok(IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)+ }+ FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {+ Ok(IncomingWebhookEvent::PaymentIntentAuthorizationFailure)+ }+ }+ }+ }+ FinixEmbedded::Transfers { transfers } => {+ let transfers = transfers.get_first_event()?;++ if transfers.payment_type == Some(FinixPaymentType::REVERSAL) {+ match transfers.state {+ FinixState::SUCCEEDED => Ok(IncomingWebhookEvent::RefundSuccess),+ FinixState::PENDING => Ok(IncomingWebhookEvent::EventNotSupported),+ FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {+ Ok(IncomingWebhookEvent::RefundFailure)+ }+ }+ } else {+ match transfers.state {+ FinixState::PENDING => Ok(IncomingWebhookEvent::PaymentIntentProcessing),+ FinixState::SUCCEEDED => Ok(IncomingWebhookEvent::PaymentIntentSuccess),+ FinixState::FAILED | FinixState::CANCELED | FinixState::UNKNOWN => {+ Ok(IncomingWebhookEvent::PaymentIntentFailure)+ }+ }+ }+ }+ FinixEmbedded::Disputes { disputes } => {+ let dispute = disputes.get_first_event()?;++ match dispute.state {+ FinixDisputeState::PENDING => Ok(IncomingWebhookEvent::DisputeOpened),+ FinixDisputeState::INQUIRY => Ok(IncomingWebhookEvent::DisputeChallenged),+ FinixDisputeState::LOST => Ok(IncomingWebhookEvent::DisputeLost),+ FinixDisputeState::WON => Ok(IncomingWebhookEvent::DisputeWon),+ }+ }+ }+ }++ pub fn get_dispute_details(&self) -> CustomResult<DisputePayload, ConnectorError> {+ match &self.webhook_embedded {+ FinixEmbedded::Disputes { disputes } => {+ let dispute = disputes.get_first_event()?;+ let amount = utils::convert_amount(+ super::Finix::new().amount_converter_webhooks,+ dispute.amount,+ dispute.currency,+ )?;+ Ok(DisputePayload {+ amount,+ currency: dispute.currency,+ dispute_stage: DisputeStage::Dispute,+ connector_status: dispute.state.to_string(),+ connector_dispute_id: dispute.id,+ connector_reason: dispute.reason,+ connector_reason_code: None,+ challenge_required_by: dispute.respond_by,+ created_at: dispute.created_at,+ updated_at: dispute.updated_at,+ })+ }+ FinixEmbedded::Authorizations { .. } | FinixEmbedded::Transfers { .. } => {+ Err(ConnectorError::ResponseDeserializationFailed)+ .attach_printable("Expected Dispute webhooks, but found other webhooks")?+ }+ }+ }+}diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rsindex f1a19d8b40..65ff276de6 100644--- a/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs+++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers/request.rs@@ -16,6 +16,7 @@ pub struct FinixPaymentsRequest {pub tags: Option<FinixTags>,pub three_d_secure: Option<FinixThreeDSecure>,pub idempotency_id: Option<String>,+ pub statement_descriptor: Option<String>,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]diff --git a/crates/hyperswitch_connectors/src/connectors/finix/transformers/response.rs b/crates/hyperswitch_connectors/src/connectors/finix/transformers/response.rsindex 9f29d9a75f..8f0f0dc594 100644--- a/crates/hyperswitch_connectors/src/connectors/finix/transformers/response.rs+++ b/crates/hyperswitch_connectors/src/connectors/finix/transformers/response.rs@@ -3,6 +3,8 @@ use std::collections::HashMap;use common_enums::Currency;use common_utils::types::MinorUnit;use serde::{Deserialize, Serialize};+use strum::Display;+use time::PrimitiveDateTime;use super::*;#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]@@ -26,9 +28,28 @@ pub struct FinixPaymentsResponse {pub payment_type: Option<FinixPaymentType>,// pub trace_id: String,pub three_d_secure: Option<FinixThreeDSecure>,- // Add other fields from the API response as needed.}+#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(untagged)]+pub enum FinixCombinedPaymentResponse {+ SyncResponse(Box<FinixPaymentsResponse>),+ WebhookResponse(Box<FinixEmbedded>),+}+impl FinixCombinedPaymentResponse {+ pub fn get_payment_response(&self) -> Result<FinixPaymentsResponse, ConnectorError> {+ match self {+ Self::SyncResponse(txn_res) => Ok(*txn_res.clone()),+ Self::WebhookResponse(webhook_res) => match webhook_res.as_ref() {+ FinixEmbedded::Authorizations { authorizations } => {+ authorizations.get_first_event()+ }+ FinixEmbedded::Transfers { transfers } => transfers.get_first_event(),+ FinixEmbedded::Disputes { .. } => Err(ConnectorError::ResponseHandlingFailed),+ },+ }+ }+}#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]pub struct FinixIdentityResponse {pub id: String,@@ -77,3 +98,71 @@ pub struct FinixError {pub message: Option<String>,pub code: Option<String>,}++//------------------- WEBHOOKS++#[derive(Clone, Display, Debug, Serialize, Deserialize)]+pub enum FinixDisputeState {+ INQUIRY,+ PENDING,+ LOST,+ WON,+}+#[derive(Clone, Debug, Serialize, Deserialize)]++pub struct FinixDisputes {+ pub transfer: String,+ pub reason: Option<String>,+ pub amount: MinorUnit,+ pub state: FinixDisputeState,+ pub currency: Currency,+ pub id: String,+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub created_at: Option<PrimitiveDateTime>,+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub updated_at: Option<PrimitiveDateTime>,+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]+ pub respond_by: Option<PrimitiveDateTime>,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct SingleEventType<T>(Vec<T>);+impl<T: Clone> SingleEventType<T> {+ pub fn get_first_event(&self) -> Result<T, ConnectorError> {+ self.0+ .first()+ .cloned()+ .ok_or(ConnectorError::WebhookBodyDecodingFailed)+ }+}++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(untagged)]+pub enum FinixEmbedded {+ Authorizations {+ authorizations: SingleEventType<FinixPaymentsResponse>,+ },+ Transfers {+ transfers: SingleEventType<FinixPaymentsResponse>,+ },+ Disputes {+ disputes: SingleEventType<FinixDisputes>,+ },+}+#[derive(Clone, Debug, Serialize, Deserialize)]++pub struct FinixWebhookBody {+ #[serde(rename = "type")]+ pub webhook_type: String,+ pub entity: String,+ #[serde(rename = "_embedded")]+ pub webhook_embedded: FinixEmbedded,+}++//--------------++#[derive(Debug, serde::Deserialize)]+pub struct FinixWebhookSignature {+ pub timestamp: String,+ pub sig: Vec<u8>,+}diff --git a/crates/payment_methods/src/configs/payment_connector_required_fields.rs b/crates/payment_methods/src/configs/payment_connector_required_fields.rsindex a4e44be23e..e19b03cbea 100644--- a/crates/payment_methods/src/configs/payment_connector_required_fields.rs+++ b/crates/payment_methods/src/configs/payment_connector_required_fields.rs@@ -1411,6 +1411,7 @@ fn get_cards_required_fields() -> HashMap<Connector, RequiredFieldFinal> {Connector::Elavon,fields(vec![], [card_basic(), billing_email()].concat(), vec![]),),+ (Connector::Finix, fields(vec![], vec![], card_basic())),(Connector::Fiserv, fields(vec![], card_basic(), vec![])),(Connector::Fiuu,