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(connector): introduce setup mandate flow for payload (#9110)

Pa1NarK4e33e9741a18
diff --git a/crates/hyperswitch_connectors/src/connectors/payload.rs b/crates/hyperswitch_connectors/src/connectors/payload.rs
index 792fa493c4..3967736fd0 100644
--- a/crates/hyperswitch_connectors/src/connectors/payload.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payload.rs
@@ -33,7 +33,7 @@ use hyperswitch_domain_models::{
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
- PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
@@ -44,7 +44,7 @@ use hyperswitch_interfaces::{
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
- types::{self, PaymentsVoidType, Response},
+ types::{self, PaymentsVoidType, Response, SetupMandateType},
webhooks,
};
use masking::{ExposeInterface, Mask, Secret};
@@ -190,15 +190,77 @@ impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> fo
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payload {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payload {
- fn build_request(
+ fn get_headers(
+ &self,
+ req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/transactions", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
&self,
- _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ req: &SetupMandateRouterData,
_connectors: &Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = requests::PayloadCardsRequestData::try_from(req)?;
+ Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
- Err(
- errors::ConnectorError::NotImplemented("Setup Mandate flow for Payload".to_string())
- .into(),
- )
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&SetupMandateType::get_url(self, req, connectors)?)
+ .headers(SetupMandateType::get_headers(self, req, connectors)?)
+ .set_body(SetupMandateType::get_request_body(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &SetupMandateRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
+ let response: responses::PayloadPaymentsResponse = res
+ .response
+ .parse_struct("PayloadPaymentsResponse")
+ .change_context(errors::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, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs
index 778aedb89f..90f4a65064 100644
--- a/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs
@@ -5,12 +5,16 @@ use common_enums::enums;
use common_utils::{ext_traits::ValueExt, types::StringMajorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
+ address::AddressDetails,
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
- router_request_types::{PaymentsAuthorizeData, ResponseId},
+ router_request_types::ResponseId,
router_response_types::{MandateReference, PaymentsResponseData, RefundsResponseData},
- types::{PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, RefundsRouterData,
+ SetupMandateRouterData,
+ },
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
@@ -23,16 +27,77 @@ use super::{requests, responses};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
- is_manual_capture, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
+ get_unimplemented_payment_method_error_message, is_manual_capture, AddressDetailsData,
+ CardData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData,
RouterData as OtherRouterData,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
-//TODO: Fill the struct with respective fields
+fn build_payload_cards_request_data(
+ payment_method_data: &PaymentMethodData,
+ connector_auth_type: &ConnectorAuthType,
+ currency: enums::Currency,
+ amount: StringMajorUnit,
+ billing_address: &AddressDetails,
+ capture_method: Option<enums::CaptureMethod>,
+ is_mandate: bool,
+) -> Result<requests::PayloadCardsRequestData, Error> {
+ if let PaymentMethodData::Card(req_card) = payment_method_data {
+ let payload_auth = PayloadAuth::try_from((connector_auth_type, currency))?;
+
+ let card = requests::PayloadCard {
+ number: req_card.clone().card_number,
+ expiry: req_card
+ .clone()
+ .get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
+ cvc: req_card.card_cvc.clone(),
+ };
+
+ let city = billing_address.get_city()?.to_owned();
+ let country = billing_address.get_country()?.to_owned();
+ let postal_code = billing_address.get_zip()?.to_owned();
+ let state_province = billing_address.get_state()?.to_owned();
+ let street_address = billing_address.get_line1()?.to_owned();
+
+ let billing_address = requests::BillingAddress {
+ city,
+ country,
+ postal_code,
+ state_province,
+ street_address,
+ };
+
+ // For manual capture, set status to "authorized"
+ let status = if is_manual_capture(capture_method) {
+ Some(responses::PayloadPaymentStatus::Authorized)
+ } else {
+ None
+ };
+
+ Ok(requests::PayloadCardsRequestData {
+ amount,
+ card,
+ transaction_types: requests::TransactionTypes::Payment,
+ payment_method_type: "card".to_string(),
+ status,
+ billing_address,
+ processing_id: payload_auth.processing_account_id,
+ keep_active: is_mandate,
+ })
+ } else {
+ Err(
+ errors::ConnectorError::NotImplemented(get_unimplemented_payment_method_error_message(
+ "Payload",
+ ))
+ .into(),
+ )
+ }
+}
+
pub struct PayloadRouterData<T> {
- pub amount: StringMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub amount: StringMajorUnit,
pub router_data: T,
}
@@ -104,6 +169,33 @@ impl TryFrom<&ConnectorAuthType> for PayloadAuthType {
}
}
+impl TryFrom<&SetupMandateRouterData> for requests::PayloadCardsRequestData {
+ type Error = Error;
+ fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
+ match item.request.amount {
+ Some(amount) if amount > 0 => Err(errors::ConnectorError::FlowNotSupported {
+ flow: "Setup mandate with non zero amount".to_string(),
+ connector: "Payload".to_string(),
+ }
+ .into()),
+ _ => {
+ let billing_address = item.get_billing_address()?;
+ let is_mandate = item.request.is_customer_initiated_mandate_payment();
+
+ build_payload_cards_request_data(
+ &item.request.payment_method_data,
+ &item.connector_auth_type,
+ item.request.currency,
+ StringMajorUnit::zero(),
+ billing_address,
+ item.request.capture_method,
+ is_mandate,
+ )
+ }
+ }
+ }
+}
+
impl TryFrom<&PayloadRouterData<&PaymentsAuthorizeRouterData>>
for requests::PayloadPaymentsRequest
{
@@ -119,55 +211,21 @@ impl TryFrom<&PayloadRouterData<&PaymentsAuthorizeRouterData>>
}
match item.router_data.request.payment_method_data.clone() {
- PaymentMethodData::Card(req_card) => {
- let payload_auth = PayloadAuth::try_from((
- &item.router_data.connector_auth_type,
- item.router_data.request.currency,
- ))?;
- let card = requests::PayloadCard {
- number: req_card.clone().card_number,
- expiry: req_card
- .clone()
- .get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
- cvc: req_card.card_cvc,
- };
+ PaymentMethodData::Card(_) => {
+ let billing_address = item.router_data.get_billing_address()?;
let is_mandate = item.router_data.request.is_mandate_payment();
- let address = item.router_data.get_billing_address()?;
-
- // Check for required fields and fail if they're missing
- let city = address.get_city()?.to_owned();
- let country = address.get_country()?.to_owned();
- let postal_code = address.get_zip()?.to_owned();
- let state_province = address.get_state()?.to_owned();
- let street_address = address.get_line1()?.to_owned();
-
- let billing_address = requests::BillingAddress {
- city,
- country,
- postal_code,
- state_province,
- street_address,
- };
- // For manual capture, set status to "authorized"
- let status = if is_manual_capture(item.router_data.request.capture_method) {
- Some(responses::PayloadPaymentStatus::Authorized)
- } else {
- None
- };
+ let cards_data = build_payload_cards_request_data(
+ &item.router_data.request.payment_method_data,
+ &item.router_data.connector_auth_type,
+ item.router_data.request.currency,
+ item.amount.clone(),
+ billing_address,
+ item.router_data.request.capture_method,
+ is_mandate,
+ )?;
- Ok(Self::PayloadCardsRequest(Box::new(
- requests::PayloadCardsRequestData {
- amount: item.amount.clone(),
- card,
- transaction_types: requests::TransactionTypes::Payment,
- payment_method_type: "card".to_string(),
- status,
- billing_address,
- processing_id: payload_auth.processing_account_id,
- keep_active: is_mandate,
- },
- )))
+ Ok(Self::PayloadCardsRequest(Box::new(cards_data)))
}
PaymentMethodData::MandatePayment => {
// For manual capture, set status to "authorized"
@@ -206,7 +264,7 @@ impl From<responses::PayloadPaymentStatus> for common_enums::AttemptStatus {
}
}
-impl<F, T>
+impl<F: 'static, T>
TryFrom<ResponseRouterData<F, responses::PayloadPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
where
@@ -220,10 +278,13 @@ where
responses::PayloadPaymentsResponse::PayloadCardsResponse(response) => {
let status = enums::AttemptStatus::from(response.status);
- let request_any: &dyn std::any::Any = &item.data.request;
- let is_mandate_payment = request_any
- .downcast_ref::<PaymentsAuthorizeData>()
- .is_some_and(|req| req.is_mandate_payment());
+ let router_data: &dyn std::any::Any = &item.data;
+ let is_mandate_payment = router_data
+ .downcast_ref::<PaymentsAuthorizeRouterData>()
+ .is_some_and(|router_data| router_data.request.is_mandate_payment())
+ || router_data
+ .downcast_ref::<SetupMandateRouterData>()
+ .is_some();
let mandate_reference = if is_mandate_payment {
let connector_payment_method_id =
diff --git a/cypress-tests/cypress/e2e/configs/Payment/Payload.js b/cypress-tests/cypress/e2e/configs/Payment/Payload.js
index 76096d4df0..81be92712d 100644
--- a/cypress-tests/cypress/e2e/configs/Payment/Payload.js
+++ b/cypress-tests/cypress/e2e/configs/Payment/Payload.js
@@ -605,12 +605,43 @@ export const connectorDetails = {
},
},
Request: {
- currency: "BRL",
+ amount: 0,
+ setup_future_usage: "off_session",
+ currency: "USD",
},
Response: {
status: 200,
body: {
status: "requires_payment_method",
+ setup_future_usage: "off_session",
+ amount: 0,
+ },
+ },
+ },
+ ZeroAuthConfirmPayment: {
+ Configs: {
+ DELAY: {
+ STATUS: true,
+ TIMEOUT: DUPLICATION_TIMEOUT,
+ },
+ },
+ Request: {
+ payment_type: "setup_mandate",
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: successfulNo3DSCardDetails,
+ },
+ setup_future_usage: "off_session",
+ customer_acceptance: customerAcceptance,
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ amount: 0,
+ setup_future_usage: "off_session",
+ payment_method_type: "credit",
},
},
},
@@ -630,11 +661,10 @@ export const connectorDetails = {
mandate_data: singleUseMandateData,
},
Response: {
- status: 501,
+ status: 200,
body: {
- code: "IR_00",
- message: "Setup Mandate flow for Payload is not implemented",
- type: "invalid_request",
+ status: "succeeded",
+ amount: 0,
},
},
},