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): [PeachPayments] Add Cards Flow (#9030)

Ben Janeckef3635a2e1d6d
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index e60d1eab85..34cd0c5147 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -12111,6 +12111,7 @@
"paystack",
"paytm",
"payu",
+ "peachpayments",
"phonepe",
"placetopay",
"powertranz",
@@ -30218,6 +30219,7 @@
"paystack",
"paytm",
"payu",
+ "peachpayments",
"phonepe",
"placetopay",
"powertranz",
diff --git a/api-reference/v2/openapi_spec_v2.json b/api-reference/v2/openapi_spec_v2.json
index 1fcc816ce8..1559dce918 100644
--- a/api-reference/v2/openapi_spec_v2.json
+++ b/api-reference/v2/openapi_spec_v2.json
@@ -8655,6 +8655,7 @@
"paystack",
"paytm",
"payu",
+ "peachpayments",
"phonepe",
"placetopay",
"powertranz",
@@ -23847,6 +23848,7 @@
"paystack",
"paytm",
"payu",
+ "peachpayments",
"phonepe",
"placetopay",
"powertranz",
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs
index 5051b03567..3a7d2f535c 100644
--- a/crates/common_enums/src/connector_enums.rs
+++ b/crates/common_enums/src/connector_enums.rs
@@ -136,7 +136,7 @@ pub enum RoutableConnectors {
Paystack,
Paytm,
Payu,
- // Peachpayments,
+ Peachpayments,
Phonepe,
Placetopay,
Powertranz,
@@ -314,7 +314,7 @@ pub enum Connector {
Paystack,
Paytm,
Payu,
- // Peachpayments,
+ Peachpayments,
Phonepe,
Placetopay,
Powertranz,
@@ -503,7 +503,7 @@ impl Connector {
| Self::Paysafe
| Self::Paystack
| Self::Payu
- // | Self::Peachpayments
+ | Self::Peachpayments
| Self::Placetopay
| Self::Powertranz
| Self::Prophetpay
@@ -683,7 +683,7 @@ impl From<RoutableConnectors> for Connector {
RoutableConnectors::Paysafe => Self::Paysafe,
RoutableConnectors::Paystack => Self::Paystack,
RoutableConnectors::Payu => Self::Payu,
- // RoutableConnectors::Peachpayments => Self::Peachpayments,
+ RoutableConnectors::Peachpayments => Self::Peachpayments,
RoutableConnectors::Placetopay => Self::Placetopay,
RoutableConnectors::Powertranz => Self::Powertranz,
RoutableConnectors::Prophetpay => Self::Prophetpay,
@@ -818,7 +818,7 @@ impl TryFrom<Connector> for RoutableConnectors {
Connector::Paysafe => Ok(Self::Paysafe),
Connector::Paystack => Ok(Self::Paystack),
Connector::Payu => Ok(Self::Payu),
- // Connector::Peachpayments => Ok(Self::Peachpayments),
+ Connector::Peachpayments => Ok(Self::Peachpayments),
Connector::Placetopay => Ok(Self::Placetopay),
Connector::Powertranz => Ok(Self::Powertranz),
Connector::Prophetpay => Ok(Self::Prophetpay),
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 060240873f..dfede98f1e 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -486,7 +486,7 @@ impl ConnectorConfig {
Connector::Paysafe => Ok(connector_data.paysafe),
Connector::Paystack => Ok(connector_data.paystack),
Connector::Payu => Ok(connector_data.payu),
- // Connector::Peachpayments => Ok(connector_data.peachpayments),
+ Connector::Peachpayments => Ok(connector_data.peachpayments),
Connector::Placetopay => Ok(connector_data.placetopay),
Connector::Plaid => Ok(connector_data.plaid),
Connector::Powertranz => Ok(connector_data.powertranz),
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 8b6b0e875f..a5de72b6e2 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -6841,5 +6841,113 @@ required=true
type="Text"
[peachpayments]
-[peachpayments.connector_auth.HeaderKey]
-api_key = "API Key"
+[[peachpayments.credit]]
+ payment_method_type = "Mastercard"
+[[peachpayments.credit]]
+ payment_method_type = "Visa"
+[[peachpayments.credit]]
+ payment_method_type = "AmericanExpress"
+[[peachpayments.debit]]
+ payment_method_type = "Mastercard"
+[[peachpayments.debit]]
+ payment_method_type = "Visa"
+[[peachpayments.debit]]
+ payment_method_type = "AmericanExpress"
+[peachpayments.connector_auth.BodyKey]
+api_key="API Key"
+key1="Tenant ID"
+[peachpayments.connector_webhook_details]
+merchant_secret="Webhook Secret"
+
+[peachpayments.metadata.merchant_name]
+name="merchant_name"
+label="Merchant Name"
+placeholder="Enter Merchant Name"
+required=true
+type="Text"
+[peachpayments.metadata.mcc]
+name="mcc"
+label="Merchant Category Code"
+placeholder="Enter MCC (e.g., 5411)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_phone]
+name="merchant_phone"
+label="Merchant Phone"
+placeholder="Enter merchant phone (e.g., +27123456789)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_email]
+name="merchant_email"
+label="Merchant Email"
+placeholder="Enter merchant email"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_mobile]
+name="merchant_mobile"
+label="Merchant Mobile"
+placeholder="Enter merchant mobile (e.g., +27123456789)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_address]
+name="merchant_address"
+label="Merchant Address"
+placeholder="Enter merchant address"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_city]
+name="merchant_city"
+label="Merchant City"
+placeholder="Enter merchant city"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_postal_code]
+name="merchant_postal_code"
+label="Merchant Postal Code"
+placeholder="Enter postal code"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_region_code]
+name="merchant_region_code"
+label="Merchant Region Code"
+placeholder="Enter region code (e.g., WC)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_type]
+name="merchant_type"
+label="Merchant Type"
+placeholder="Select merchant type"
+required=true
+type="Select"
+options=["direct", "sub"]
+[peachpayments.metadata.merchant_website]
+name="merchant_website"
+label="Merchant Website"
+placeholder="Enter merchant website URL"
+required=true
+type="Text"
+[peachpayments.metadata.routing_mid]
+name="routing_mid"
+label="Routing MID"
+placeholder="Enter routing MID"
+required=true
+type="Text"
+[peachpayments.metadata.routing_tid]
+name="routing_tid"
+label="Routing TID"
+placeholder="Enter routing TID"
+required=true
+type="Text"
+[peachpayments.metadata.routing_route]
+name="routing_route"
+label="Routing Route"
+placeholder="Select routing route"
+required=true
+type="Select"
+options=["cardgateway_emulator", "exipay_emulator", "absa_base24", "nedbank_postbridge"]
+[peachpayments.metadata.amex_id]
+name="amex_id"
+label="AmEx ID"
+placeholder="Enter AmEx ID for routing"
+required=false
+type="Text"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 7501bb4c33..3515ff2c58 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -5510,5 +5510,113 @@ required=true
type="Text"
[peachpayments]
-[peachpayments.connector_auth.HeaderKey]
-api_key = "API Key"
+[[peachpayments.credit]]
+ payment_method_type = "Mastercard"
+[[peachpayments.credit]]
+ payment_method_type = "Visa"
+[[peachpayments.credit]]
+ payment_method_type = "AmericanExpress"
+[[peachpayments.debit]]
+ payment_method_type = "Mastercard"
+[[peachpayments.debit]]
+ payment_method_type = "Visa"
+[[peachpayments.debit]]
+ payment_method_type = "AmericanExpress"
+[peachpayments.connector_auth.BodyKey]
+api_key="API Key"
+key1="Tenant ID"
+[peachpayments.connector_webhook_details]
+merchant_secret="Webhook Secret"
+
+[peachpayments.metadata.merchant_name]
+name="merchant_name"
+label="Merchant Name"
+placeholder="Enter Merchant Name"
+required=true
+type="Text"
+[peachpayments.metadata.mcc]
+name="mcc"
+label="Merchant Category Code"
+placeholder="Enter MCC (e.g., 5411)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_phone]
+name="merchant_phone"
+label="Merchant Phone"
+placeholder="Enter merchant phone (e.g., +27123456789)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_email]
+name="merchant_email"
+label="Merchant Email"
+placeholder="Enter merchant email"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_mobile]
+name="merchant_mobile"
+label="Merchant Mobile"
+placeholder="Enter merchant mobile (e.g., +27123456789)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_address]
+name="merchant_address"
+label="Merchant Address"
+placeholder="Enter merchant address"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_city]
+name="merchant_city"
+label="Merchant City"
+placeholder="Enter merchant city"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_postal_code]
+name="merchant_postal_code"
+label="Merchant Postal Code"
+placeholder="Enter postal code"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_region_code]
+name="merchant_region_code"
+label="Merchant Region Code"
+placeholder="Enter region code (e.g., WC)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_type]
+name="merchant_type"
+label="Merchant Type"
+placeholder="Select merchant type"
+required=true
+type="Select"
+options=["direct", "sub"]
+[peachpayments.metadata.merchant_website]
+name="merchant_website"
+label="Merchant Website"
+placeholder="Enter merchant website URL"
+required=true
+type="Text"
+[peachpayments.metadata.routing_mid]
+name="routing_mid"
+label="Routing MID"
+placeholder="Enter routing MID"
+required=true
+type="Text"
+[peachpayments.metadata.routing_tid]
+name="routing_tid"
+label="Routing TID"
+placeholder="Enter routing TID"
+required=true
+type="Text"
+[peachpayments.metadata.routing_route]
+name="routing_route"
+label="Routing Route"
+placeholder="Select routing route"
+required=true
+type="Select"
+options=["cardgateway_emulator", "exipay_emulator", "absa_base24", "nedbank_postbridge"]
+[peachpayments.metadata.amex_id]
+name="amex_id"
+label="AmEx ID"
+placeholder="Enter AmEx ID for routing"
+required=false
+type="Text"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 8220f4f2ea..9cfb45cf6d 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -6823,6 +6823,116 @@ placeholder="Enter Account ID"
required=true
type="Text"
+
+
[peachpayments]
-[peachpayments.connector_auth.HeaderKey]
-api_key = "API Key"
+[[peachpayments.credit]]
+ payment_method_type = "Mastercard"
+[[peachpayments.credit]]
+ payment_method_type = "Visa"
+[[peachpayments.credit]]
+ payment_method_type = "AmericanExpress"
+[[peachpayments.debit]]
+ payment_method_type = "Mastercard"
+[[peachpayments.debit]]
+ payment_method_type = "Visa"
+[[peachpayments.debit]]
+ payment_method_type = "AmericanExpress"
+[peachpayments.connector_auth.BodyKey]
+api_key="API Key"
+key1="Tenant ID"
+[peachpayments.connector_webhook_details]
+merchant_secret="Webhook Secret"
+
+[peachpayments.metadata.merchant_name]
+name="merchant_name"
+label="Merchant Name"
+placeholder="Enter Merchant Name"
+required=true
+type="Text"
+[peachpayments.metadata.mcc]
+name="mcc"
+label="Merchant Category Code"
+placeholder="Enter MCC (e.g., 5411)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_phone]
+name="merchant_phone"
+label="Merchant Phone"
+placeholder="Enter merchant phone (e.g., +27123456789)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_email]
+name="merchant_email"
+label="Merchant Email"
+placeholder="Enter merchant email"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_mobile]
+name="merchant_mobile"
+label="Merchant Mobile"
+placeholder="Enter merchant mobile (e.g., +27123456789)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_address]
+name="merchant_address"
+label="Merchant Address"
+placeholder="Enter merchant address"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_city]
+name="merchant_city"
+label="Merchant City"
+placeholder="Enter merchant city"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_postal_code]
+name="merchant_postal_code"
+label="Merchant Postal Code"
+placeholder="Enter postal code"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_region_code]
+name="merchant_region_code"
+label="Merchant Region Code"
+placeholder="Enter region code (e.g., WC)"
+required=true
+type="Text"
+[peachpayments.metadata.merchant_type]
+name="merchant_type"
+label="Merchant Type"
+placeholder="Select merchant type"
+required=true
+type="Select"
+options=["direct", "sub"]
+[peachpayments.metadata.merchant_website]
+name="merchant_website"
+label="Merchant Website"
+placeholder="Enter merchant website URL"
+required=true
+type="Text"
+[peachpayments.metadata.routing_mid]
+name="routing_mid"
+label="Routing MID"
+placeholder="Enter routing MID"
+required=true
+type="Text"
+[peachpayments.metadata.routing_tid]
+name="routing_tid"
+label="Routing TID"
+placeholder="Enter routing TID"
+required=true
+type="Text"
+[peachpayments.metadata.routing_route]
+name="routing_route"
+label="Routing Route"
+placeholder="Select routing route"
+required=true
+type="Select"
+options=["cardgateway_emulator", "exipay_emulator", "absa_base24", "nedbank_postbridge"]
+[peachpayments.metadata.amex_id]
+name="amex_id"
+label="AmEx ID"
+placeholder="Enter AmEx ID for routing"
+required=false
+type="Text"
diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments.rs
index 3c25889332..abc8caf1ef 100644
--- a/crates/hyperswitch_connectors/src/connectors/peachpayments.rs
+++ b/crates/hyperswitch_connectors/src/connectors/peachpayments.rs
@@ -2,7 +2,7 @@ pub mod transformers;
use std::sync::LazyLock;
-use common_enums::enums;
+use common_enums::{self, enums};
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
@@ -11,7 +11,6 @@ use common_utils::{
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
- payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
@@ -24,11 +23,12 @@ use hyperswitch_domain_models::{
RefundsData, SetupMandateRequestData,
},
router_response_types::{
- ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
+ SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
- PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
- RefundSyncRouterData, RefundsRouterData,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
@@ -122,10 +122,14 @@ impl ConnectorCommon for Peachpayments {
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = peachpayments::PeachpaymentsAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(vec![(
- headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
- )])
+ Ok(vec![
+ ("x-api-key".to_string(), auth.api_key.expose().into_masked()),
+ (
+ "x-tenant-id".to_string(),
+ auth.tenant_id.expose().into_masked(),
+ ),
+ ("x-exi-auth-ver".to_string(), "v1".to_string().into_masked()),
+ ])
}
fn build_error_response(
@@ -143,9 +147,9 @@ impl ConnectorCommon for Peachpayments {
Ok(ErrorResponse {
status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
+ code: response.error_ref.clone(),
+ message: response.message.clone(),
+ reason: Some(response.message.clone()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
@@ -156,31 +160,7 @@ impl ConnectorCommon for Peachpayments {
}
}
-impl ConnectorValidation for Peachpayments {
- fn validate_mandate_payment(
- &self,
- _pm_type: Option<enums::PaymentMethodType>,
- pm_data: PaymentMethodData,
- ) -> CustomResult<(), errors::ConnectorError> {
- match pm_data {
- PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
- "validate_mandate_payment does not support cards".to_string(),
- )
- .into()),
- _ => Ok(()),
- }
- }
-
- fn validate_psync_reference_id(
- &self,
- _data: &PaymentsSyncData,
- _is_three_ds: bool,
- _status: enums::AttemptStatus,
- _connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
- ) -> CustomResult<(), errors::ConnectorError> {
- Ok(())
- }
-}
+impl ConnectorValidation for Peachpayments {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Peachpayments {
//TODO: implement sessions flow
@@ -211,9 +191,9 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!("{}/transactions", self.base_url(connectors)))
}
fn get_request_body(
@@ -298,10 +278,19 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Pea
fn get_url(
&self,
- _req: &PaymentsSyncRouterData,
- _connectors: &Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_transaction_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}/transactions/{}",
+ self.base_url(connectors),
+ connector_transaction_id
+ ))
}
fn build_request(
@@ -362,18 +351,32 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
fn get_url(
&self,
- _req: &PaymentsCaptureRouterData,
- _connectors: &Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_transaction_id = &req.request.connector_transaction_id;
+ Ok(format!(
+ "{}/transactions/{}/confirm",
+ self.base_url(connectors),
+ connector_transaction_id
+ ))
}
fn get_request_body(
&self,
- _req: &PaymentsCaptureRouterData,
+ req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ let amount = utils::convert_amount(
+ self.amount_converter,
+ req.request.minor_amount_to_capture,
+ req.request.currency,
+ )?;
+
+ let connector_router_data = peachpayments::PeachpaymentsRouterData::from((amount, req));
+ let connector_req =
+ peachpayments::PeachpaymentsConfirmRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
@@ -402,7 +405,7 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
- let response: peachpayments::PeachpaymentsPaymentsResponse = res
+ let response: peachpayments::PeachpaymentsConfirmResponse = res
.response
.parse_struct("Peachpayments PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -424,12 +427,10 @@ impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> fo
}
}
-impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Peachpayments {}
-
-impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpayments {
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Peachpayments {
fn get_headers(
&self,
- req: &RefundsRouterData<Execute>,
+ req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
@@ -441,58 +442,53 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpa
fn get_url(
&self,
- _req: &RefundsRouterData<Execute>,
- _connectors: &Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_transaction_id = &req.request.connector_transaction_id;
+ Ok(format!(
+ "{}/transactions/{}/void",
+ self.base_url(connectors),
+ connector_transaction_id
+ ))
}
fn get_request_body(
&self,
- req: &RefundsRouterData<Execute>,
+ req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let refund_amount = utils::convert_amount(
- self.amount_converter,
- req.request.minor_refund_amount,
- req.request.currency,
- )?;
-
- let connector_router_data =
- peachpayments::PeachpaymentsRouterData::from((refund_amount, req));
- let connector_req =
- peachpayments::PeachpaymentsRefundRequest::try_from(&connector_router_data)?;
+ let connector_req = peachpayments::PeachpaymentsVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &RefundsRouterData<Execute>,
+ req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
- let request = RequestBuilder::new()
- .method(Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::RefundExecuteType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::RefundExecuteType::get_request_body(
- self, req, connectors,
- )?)
- .build();
- Ok(Some(request))
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(types::PaymentsVoidType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
}
fn handle_response(
&self,
- data: &RefundsRouterData<Execute>,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
- let response: peachpayments::RefundResponse = res
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: peachpayments::PeachpaymentsPaymentsResponse = res
.response
- .parse_struct("peachpayments RefundResponse")
+ .parse_struct("Peachpayments PaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -512,70 +508,23 @@ impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpa
}
}
-impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Peachpayments {
- fn get_headers(
- &self,
- req: &RefundSyncRouterData,
- 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(
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Peachpayments {
+ fn build_request(
&self,
- _req: &RefundSyncRouterData,
+ _req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("Execute".to_string()).into())
}
+}
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Peachpayments {
fn build_request(
&self,
- req: &RefundSyncRouterData,
- connectors: &Connectors,
+ _req: &RefundSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
- Ok(Some(
- RequestBuilder::new()
- .method(Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
- .set_body(types::RefundSyncType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- ))
- }
-
- fn handle_response(
- &self,
- data: &RefundSyncRouterData,
- event_builder: Option<&mut ConnectorEvent>,
- res: Response,
- ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
- let response: peachpayments::RefundResponse = res
- .response
- .parse_struct("peachpayments RefundSyncResponse")
- .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)
+ Err(errors::ConnectorError::NotImplemented("Refunds Retrieve".to_string()).into())
}
}
@@ -604,11 +553,64 @@ impl webhooks::IncomingWebhook for Peachpayments {
}
static PEACHPAYMENTS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
- LazyLock::new(SupportedPaymentMethods::new);
+ LazyLock::new(|| {
+ let supported_capture_methods = vec![
+ enums::CaptureMethod::Manual,
+ enums::CaptureMethod::SequentialAutomatic,
+ ];
+
+ let supported_card_network = vec![
+ common_enums::CardNetwork::Visa,
+ common_enums::CardNetwork::Mastercard,
+ common_enums::CardNetwork::AmericanExpress,
+ ];
+
+ let mut peachpayments_supported_payment_methods = SupportedPaymentMethods::new();
+
+ peachpayments_supported_payment_methods.add(
+ enums::PaymentMethod::Card,
+ enums::PaymentMethodType::Credit,
+ PaymentMethodDetails {
+ mandates: enums::FeatureStatus::NotSupported,
+ refunds: enums::FeatureStatus::NotSupported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: Some(
+ api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
+ api_models::feature_matrix::CardSpecificFeatures {
+ three_ds: common_enums::FeatureStatus::Supported,
+ no_three_ds: common_enums::FeatureStatus::Supported,
+ supported_card_networks: supported_card_network.clone(),
+ }
+ }),
+ ),
+ },
+ );
+
+ peachpayments_supported_payment_methods.add(
+ enums::PaymentMethod::Card,
+ enums::PaymentMethodType::Debit,
+ PaymentMethodDetails {
+ mandates: enums::FeatureStatus::NotSupported,
+ refunds: enums::FeatureStatus::NotSupported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: Some(
+ api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
+ api_models::feature_matrix::CardSpecificFeatures {
+ three_ds: common_enums::FeatureStatus::Supported,
+ no_three_ds: common_enums::FeatureStatus::Supported,
+ supported_card_networks: supported_card_network.clone(),
+ }
+ }),
+ ),
+ },
+ );
+
+ peachpayments_supported_payment_methods
+ });
static PEACHPAYMENTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Peachpayments",
- description: "Peachpayments connector",
+ description: "The secure African payment gateway with easy integrations, 365-day support, and advanced orchestration.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
diff --git a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
index 1d403f2632..a5e34b416a 100644
--- a/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
@@ -1,18 +1,28 @@
-use common_enums::enums;
-use common_utils::types::MinorUnit;
+use std::str::FromStr;
+
+use cards::CardNumber;
+use common_utils::{pii, types::MinorUnit};
+use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
- router_data::{ConnectorAuthType, RouterData},
- router_flow_types::refunds::{Execute, RSync},
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_request_types::ResponseId,
- router_response_types::{PaymentsResponseData, RefundsResponseData},
- types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+ router_response_types::PaymentsResponseData,
+ types::{PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData},
+};
+use hyperswitch_interfaces::{
+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
+ errors,
};
-use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
+use strum::Display;
+use time::{format_description::well_known::Rfc3339, OffsetDateTime};
-use crate::types::{RefundsResponseRouterData, ResponseRouterData};
+use crate::{
+ types::ResponseRouterData,
+ utils::{self, CardData},
+};
//TODO: Fill the struct with respective fields
pub struct PeachpaymentsRouterData<T> {
@@ -30,20 +40,288 @@ impl<T> From<(MinorUnit, T)> for PeachpaymentsRouterData<T> {
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, PartialEq)]
+impl TryFrom<&Option<pii::SecretSerdeValue>> for PeachPaymentsConnectorMetadataObject {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
+ let metadata = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
+ })?;
+ Ok(metadata)
+ }
+}
+
+// Card Gateway API Transaction Request
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsPaymentsRequest {
- amount: MinorUnit,
- card: PeachpaymentsCard,
+ pub charge_method: String,
+ pub reference_id: String,
+ pub ecommerce_card_payment_only_transaction_data: EcommerceCardPaymentOnlyTransactionData,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pos_data: Option<serde_json::Value>,
+ pub send_date_time: String,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct EcommerceCardPaymentOnlyTransactionData {
+ pub merchant_information: MerchantInformation,
+ pub routing: Routing,
+ pub card: CardDetails,
+ pub amount: AmountDetails,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub three_ds_data: Option<ThreeDSData>,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct MerchantInformation {
+ pub client_merchant_reference_id: String,
+ pub name: String,
+ pub mcc: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub phone: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub email: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mobile: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub address: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub city: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub postal_code: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub region_code: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub merchant_type: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub website_url: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct Routing {
+ pub route: String,
+ pub mid: String,
+ pub tid: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub visa_payment_facilitator_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub master_card_payment_facilitator_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sub_mid: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub amex_id: Option<String>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct CardDetails {
+ pub pan: CardNumber,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cardholder_name: Option<Secret<String>>,
+ pub expiry_year: Secret<String>,
+ pub expiry_month: Secret<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cvv: Option<Secret<String>>,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct RefundCardDetails {
+ pub pan: Secret<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cardholder_name: Option<Secret<String>>,
+ pub expiry_year: Secret<String>,
+ pub expiry_month: Secret<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cvv: Option<Secret<String>>,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct PeachpaymentsCard {
- number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct AmountDetails {
+ pub amount: MinorUnit,
+ pub currency_code: String,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct ThreeDSData {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cavv: Option<Secret<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tavv: Option<Secret<String>>,
+ pub eci: String,
+ pub ds_trans_id: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub xid: Option<String>,
+ pub authentication_status: AuthenticationStatus,
+ pub three_ds_version: String,
+}
+
+// Confirm Transaction Request (for capture)
+#[derive(Debug, Serialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct PeachpaymentsConfirmRequest {
+ pub ecommerce_card_payment_only_confirmation_data: EcommerceCardPaymentOnlyConfirmationData,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub struct EcommerceCardPaymentOnlyConfirmationData {
+ pub amount: AmountDetails,
+}
+
+// Void Transaction Request
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PeachpaymentsVoidRequest {
+ pub payment_method: PaymentMethod,
+ pub send_date_time: String,
+ pub failure_reason: FailureReason,
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum PaymentMethod {
+ EcommerceCardPaymentOnly,
+}
+
+impl TryFrom<&PeachpaymentsRouterData<&PaymentsCaptureRouterData>> for PeachpaymentsConfirmRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PeachpaymentsRouterData<&PaymentsCaptureRouterData>,
+ ) -> Result<Self, Self::Error> {
+ let amount_in_cents = item.amount;
+
+ let amount = AmountDetails {
+ amount: amount_in_cents,
+ currency_code: item.router_data.request.currency.to_string(),
+ };
+
+ let confirmation_data = EcommerceCardPaymentOnlyConfirmationData { amount };
+
+ Ok(Self {
+ ecommerce_card_payment_only_confirmation_data: confirmation_data,
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum FailureReason {
+ UnableToSend,
+ #[default]
+ Timeout,
+ SecurityError,
+ IssuerUnavailable,
+ TooLateResponse,
+ Malfunction,
+ UnableToComplete,
+ OnlineDeclined,
+ SuspectedFraud,
+ CardDeclined,
+ Partial,
+ OfflineDeclined,
+ CustomerCancel,
+}
+
+impl FromStr for FailureReason {
+ type Err = error_stack::Report<errors::ConnectorError>;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ match value.to_lowercase().as_str() {
+ "unable_to_send" => Ok(Self::UnableToSend),
+ "timeout" => Ok(Self::Timeout),
+ "security_error" => Ok(Self::SecurityError),
+ "issuer_unavailable" => Ok(Self::IssuerUnavailable),
+ "too_late_response" => Ok(Self::TooLateResponse),
+ "malfunction" => Ok(Self::Malfunction),
+ "unable_to_complete" => Ok(Self::UnableToComplete),
+ "online_declined" => Ok(Self::OnlineDeclined),
+ "suspected_fraud" => Ok(Self::SuspectedFraud),
+ "card_declined" => Ok(Self::CardDeclined),
+ "partial" => Ok(Self::Partial),
+ "offline_declined" => Ok(Self::OfflineDeclined),
+ "customer_cancel" => Ok(Self::CustomerCancel),
+ _ => Ok(Self::Timeout),
+ }
+ }
+}
+
+impl TryFrom<&PaymentsCancelRouterData> for PeachpaymentsVoidRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ let send_date_time = OffsetDateTime::now_utc()
+ .format(&Rfc3339)
+ .map_err(|_| errors::ConnectorError::ParsingFailed)?;
+ Ok(Self {
+ payment_method: PaymentMethod::EcommerceCardPaymentOnly,
+ send_date_time,
+ failure_reason: item
+ .request
+ .cancellation_reason
+ .as_ref()
+ .map(|reason| FailureReason::from_str(reason))
+ .transpose()?
+ .unwrap_or(FailureReason::Timeout),
+ })
+ }
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+pub enum AuthenticationStatus {
+ Y, // Fully authenticated
+ A, // Attempted authentication / liability shift
+ N, // Not authenticated / failed
+}
+
+impl From<&str> for AuthenticationStatus {
+ fn from(eci: &str) -> Self {
+ match eci {
+ "05" | "06" => Self::Y,
+ "07" => Self::A,
+ _ => Self::N,
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct PeachPaymentsConnectorMetadataObject {
+ pub client_merchant_reference_id: String,
+ pub name: String,
+ pub mcc: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub phone: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub email: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mobile: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub address: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub city: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub postal_code: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub region_code: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub merchant_type: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub website_url: Option<String>,
+ pub route: String,
+ pub mid: String,
+ pub tid: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub visa_payment_facilitator_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub master_card_payment_facilitator_id: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sub_mid: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub amex_id: Option<String>,
}
impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>>
@@ -54,58 +332,260 @@ impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>>
item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
- PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
- "Card payment method not implemented".to_string(),
- )
- .into()),
+ PaymentMethodData::Card(req_card) => {
+ let amount_in_cents = item.amount;
+
+ let connector_merchant_config = PeachPaymentsConnectorMetadataObject::try_from(
+ &item.router_data.connector_meta_data,
+ )?;
+
+ let merchant_information = MerchantInformation {
+ client_merchant_reference_id: connector_merchant_config
+ .client_merchant_reference_id,
+ name: connector_merchant_config.name,
+ mcc: connector_merchant_config.mcc,
+ phone: connector_merchant_config.phone,
+ email: connector_merchant_config.email,
+ mobile: connector_merchant_config.mobile,
+ address: connector_merchant_config.address,
+ city: connector_merchant_config.city,
+ postal_code: connector_merchant_config.postal_code,
+ region_code: connector_merchant_config.region_code,
+ merchant_type: connector_merchant_config.merchant_type,
+ website_url: connector_merchant_config.website_url,
+ };
+
+ // Get routing configuration from metadata
+ let routing = Routing {
+ route: connector_merchant_config.route,
+ mid: connector_merchant_config.mid,
+ tid: connector_merchant_config.tid,
+ visa_payment_facilitator_id: connector_merchant_config
+ .visa_payment_facilitator_id,
+ master_card_payment_facilitator_id: connector_merchant_config
+ .master_card_payment_facilitator_id,
+ sub_mid: connector_merchant_config.sub_mid,
+ amex_id: connector_merchant_config.amex_id,
+ };
+
+ let card = CardDetails {
+ pan: req_card.card_number.clone(),
+ cardholder_name: req_card.card_holder_name.clone(),
+ expiry_year: req_card.get_card_expiry_year_2_digit()?,
+ expiry_month: req_card.card_exp_month.clone(),
+ cvv: Some(req_card.card_cvc.clone()),
+ };
+
+ let amount = AmountDetails {
+ amount: amount_in_cents,
+ currency_code: item.router_data.request.currency.to_string(),
+ };
+
+ // Extract 3DS data if available
+ let three_ds_data = item
+ .router_data
+ .request
+ .authentication_data
+ .as_ref()
+ .and_then(|auth_data| {
+ // Only include 3DS data if we have essential fields (ECI is most critical)
+ if let Some(eci) = &auth_data.eci {
+ let ds_trans_id = auth_data
+ .ds_trans_id
+ .clone()
+ .or_else(|| auth_data.threeds_server_transaction_id.clone())?;
+
+ // Determine authentication status based on ECI value
+ let authentication_status = eci.as_str().into();
+
+ // Convert message version to string, handling None case
+ let three_ds_version = auth_data.message_version.as_ref().map(|v| {
+ let version_str = v.to_string();
+ let mut parts = version_str.split('.');
+ match (parts.next(), parts.next()) {
+ (Some(major), Some(minor)) => format!("{}.{}", major, minor),
+ _ => v.to_string(), // fallback if format unexpected
+ }
+ })?;
+
+ Some(ThreeDSData {
+ cavv: Some(auth_data.cavv.clone()),
+ tavv: None, // Network token field - not available in Hyperswitch AuthenticationData
+ eci: eci.clone(),
+ ds_trans_id,
+ xid: None, // Legacy 3DS 1.x/network token field - not available in Hyperswitch AuthenticationData
+ authentication_status,
+ three_ds_version,
+ })
+ } else {
+ None
+ }
+ });
+
+ let ecommerce_data = EcommerceCardPaymentOnlyTransactionData {
+ merchant_information,
+ routing,
+ card,
+ amount,
+ three_ds_data,
+ };
+
+ // Generate current timestamp for sendDateTime (ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ)
+ let send_date_time = OffsetDateTime::now_utc()
+ .format(&time::format_description::well_known::Iso8601::DEFAULT)
+ .map_err(|_| errors::ConnectorError::RequestEncodingFailed)?;
+
+ Ok(Self {
+ charge_method: "ecommerce_card_payment_only".to_string(),
+ reference_id: item.router_data.connector_request_reference_id.clone(),
+ ecommerce_card_payment_only_transaction_data: ecommerce_data,
+ pos_data: None,
+ send_date_time,
+ })
+ }
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
-//TODO: Fill the struct with respective fields
-// Auth Struct
+// Auth Struct for Card Gateway API
pub struct PeachpaymentsAuthType {
- pub(super) api_key: Secret<String>,
+ pub(crate) api_key: Secret<String>,
+ pub(crate) tenant_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PeachpaymentsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
- match auth_type {
- ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_owned(),
- }),
- _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ Ok(Self {
+ api_key: api_key.clone(),
+ tenant_id: key1.clone(),
+ })
+ } else {
+ Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
-// PaymentsResponse
-//TODO: Append the remaining status flags
-#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
+// Card Gateway API Response
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PeachpaymentsPaymentStatus {
- Succeeded,
+ Successful,
+ Pending,
+ Authorized,
+ Approved,
+ #[serde(rename = "approved_confirmed")]
+ ApprovedConfirmed,
+ Declined,
Failed,
- #[default]
- Processing,
+ Reversed,
+ #[serde(rename = "threeds_required")]
+ ThreedsRequired,
+ Voided,
}
impl From<PeachpaymentsPaymentStatus> for common_enums::AttemptStatus {
fn from(item: PeachpaymentsPaymentStatus) -> Self {
match item {
- PeachpaymentsPaymentStatus::Succeeded => Self::Charged,
- PeachpaymentsPaymentStatus::Failed => Self::Failure,
- PeachpaymentsPaymentStatus::Processing => Self::Authorizing,
+ // PENDING means authorized but not yet captured - requires confirmation
+ PeachpaymentsPaymentStatus::Pending
+ | PeachpaymentsPaymentStatus::Authorized
+ | PeachpaymentsPaymentStatus::Approved => Self::Authorized,
+ PeachpaymentsPaymentStatus::Declined | PeachpaymentsPaymentStatus::Failed => {
+ Self::Failure
+ }
+ PeachpaymentsPaymentStatus::Voided | PeachpaymentsPaymentStatus::Reversed => {
+ Self::Voided
+ }
+ PeachpaymentsPaymentStatus::ThreedsRequired => Self::AuthenticationPending,
+ PeachpaymentsPaymentStatus::ApprovedConfirmed
+ | PeachpaymentsPaymentStatus::Successful => Self::Charged,
}
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
pub struct PeachpaymentsPaymentsResponse {
- status: PeachpaymentsPaymentStatus,
- id: String,
+ pub transaction_id: String,
+ pub response_code: ResponseCode,
+ pub transaction_result: PeachpaymentsPaymentStatus,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub ecommerce_card_payment_only_transaction_data: Option<EcommerceCardPaymentOnlyResponseData>,
+}
+
+// Confirm Transaction Response
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct PeachpaymentsConfirmResponse {
+ pub transaction_id: String,
+ pub response_code: ResponseCode,
+ pub transaction_result: PeachpaymentsPaymentStatus,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub authorization_code: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(untagged)]
+pub enum ResponseCode {
+ Text(String),
+ Structured {
+ value: ResponseCodeValue,
+ description: String,
+ },
+}
+
+impl ResponseCode {
+ pub fn value(&self) -> Option<&ResponseCodeValue> {
+ match self {
+ Self::Structured { value, .. } => Some(value),
+ _ => None,
+ }
+ }
+
+ pub fn description(&self) -> Option<&String> {
+ match self {
+ Self::Structured { description, .. } => Some(description),
+ _ => None,
+ }
+ }
+
+ pub fn as_text(&self) -> Option<&String> {
+ match self {
+ Self::Text(s) => Some(s),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Debug, Display, Clone, Serialize, Deserialize, PartialEq)]
+pub enum ResponseCodeValue {
+ #[serde(rename = "00", alias = "08")]
+ Success,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct EcommerceCardPaymentOnlyResponseData {
+ pub card: Option<CardResponseData>,
+ pub amount: Option<AmountDetails>,
+ pub stan: Option<String>,
+ pub rrn: Option<String>,
+ #[serde(rename = "approvalCode")]
+ pub approval_code: Option<String>,
+ #[serde(rename = "merchantAdviceCode")]
+ pub merchant_advice_code: Option<String>,
+ pub description: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde[rename_all = "camelCase"]]
+pub struct CardResponseData {
+ pub bin_number: Option<String>,
+ pub masked_pan: Option<String>,
+ pub cardholder_name: Option<String>,
+ pub expiry_month: Option<String>,
+ pub expiry_year: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>>
@@ -115,109 +595,156 @@ impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, Payme
fn try_from(
item: ResponseRouterData<F, PeachpaymentsPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
- Ok(Self {
- status: common_enums::AttemptStatus::from(item.response.status),
- response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: ResponseId::ConnectorTransactionId(item.response.id),
+ let status = common_enums::AttemptStatus::from(item.response.transaction_result);
+
+ // Check if it's an error response
+ let response = if item.response.response_code.value() != Some(&ResponseCodeValue::Success) {
+ Err(ErrorResponse {
+ code: item
+ .response
+ .response_code
+ .value()
+ .map(|val| val.to_string())
+ .unwrap_or(NO_ERROR_CODE.to_string()),
+ message: item
+ .response
+ .response_code
+ .description()
+ .map(|desc| desc.to_string())
+ .unwrap_or(NO_ERROR_MESSAGE.to_string()),
+ reason: item
+ .response
+ .ecommerce_card_payment_only_transaction_data
+ .and_then(|data| data.description),
+ status_code: item.http_code,
+ attempt_status: Some(status),
+ connector_transaction_id: Some(item.response.transaction_id.clone()),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ } else {
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
+ item.response.transaction_id.clone(),
+ ),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: None,
charges: None,
- }),
+ })
+ };
+
+ Ok(Self {
+ status,
+ response,
..item.data
})
}
}
-//TODO: Fill the struct with respective fields
-// REFUND :
-// Type definition for RefundRequest
-#[derive(Default, Debug, Serialize)]
-pub struct PeachpaymentsRefundRequest {
- pub amount: MinorUnit,
-}
-
-impl<F> TryFrom<&PeachpaymentsRouterData<&RefundsRouterData<F>>> for PeachpaymentsRefundRequest {
+// TryFrom implementation for confirm response
+impl<F, T> TryFrom<ResponseRouterData<F, PeachpaymentsConfirmResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &PeachpaymentsRouterData<&RefundsRouterData<F>>,
+ item: ResponseRouterData<F, PeachpaymentsConfirmResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
- Ok(Self {
- amount: item.amount.to_owned(),
- })
- }
-}
-
-// Type definition for Refund Response
-
-#[allow(dead_code)]
-#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
-pub enum RefundStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
-}
+ let status = common_enums::AttemptStatus::from(item.response.transaction_result);
-impl From<RefundStatus> for enums::RefundStatus {
- fn from(item: RefundStatus) -> Self {
- match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
- //TODO: Review mapping
- }
- }
-}
-
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
-pub struct RefundResponse {
- id: String,
- status: RefundStatus,
-}
+ // Check if it's an error response
+ let response = if item.response.response_code.value() != Some(&ResponseCodeValue::Success) {
+ Err(ErrorResponse {
+ code: item
+ .response
+ .response_code
+ .value()
+ .map(|val| val.to_string())
+ .unwrap_or(NO_ERROR_CODE.to_string()),
+ message: item
+ .response
+ .response_code
+ .description()
+ .map(|desc| desc.to_string())
+ .unwrap_or(NO_ERROR_MESSAGE.to_string()),
+ reason: None,
+ status_code: item.http_code,
+ attempt_status: Some(status),
+ connector_transaction_id: Some(item.response.transaction_id.clone()),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ } else {
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
+ item.response.transaction_id.clone(),
+ ),
+ redirection_data: Box::new(None),
+ mandate_reference: Box::new(None),
+ connector_metadata: item.response.authorization_code.map(|auth_code| {
+ serde_json::json!({
+ "authorization_code": auth_code
+ })
+ }),
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.transaction_id),
+ incremental_authorization_allowed: None,
+ charges: None,
+ })
+ };
-impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: RefundsResponseRouterData<Execute, RefundResponse>,
- ) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
- }),
+ status,
+ response,
..item.data
})
}
}
-impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
+impl TryFrom<&PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>>
+ for PeachpaymentsConfirmRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: RefundsResponseRouterData<RSync, RefundResponse>,
+ item: &PeachpaymentsRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
+ let amount_in_cents = item.amount;
+
+ let amount = AmountDetails {
+ amount: amount_in_cents,
+ currency_code: item.router_data.request.currency.to_string(),
+ };
+
+ let confirmation_data = EcommerceCardPaymentOnlyConfirmationData { amount };
+
Ok(Self {
- response: Ok(RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
- }),
- ..item.data
+ ecommerce_card_payment_only_confirmation_data: confirmation_data,
})
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+// Error Response
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
pub struct PeachpaymentsErrorResponse {
- pub status_code: u16,
- pub code: String,
+ pub error_ref: String,
pub message: String,
- pub reason: Option<String>,
- pub network_advice_code: Option<String>,
- pub network_decline_code: Option<String>,
- pub network_error_message: Option<String>,
+}
+
+impl TryFrom<ErrorResponse> for PeachpaymentsErrorResponse {
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(error_response: ErrorResponse) -> Result<Self, Self::Error> {
+ Ok(Self {
+ error_ref: error_response.code,
+ message: error_response.message,
+ })
+ }
}
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 1a4424ac5b..a6f46e0c2a 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -3317,8 +3317,8 @@ default_imp_for_fetch_disputes!(
connectors::Paysafe,
connectors::Paystack,
connectors::Payu,
- connectors::Peachpayments,
connectors::Paytm,
+ connectors::Peachpayments,
connectors::Phonepe,
connectors::Placetopay,
connectors::Plaid,
@@ -3461,8 +3461,8 @@ default_imp_for_dispute_sync!(
connectors::Paysafe,
connectors::Paystack,
connectors::Payu,
- connectors::Peachpayments,
connectors::Paytm,
+ connectors::Peachpayments,
connectors::Phonepe,
connectors::Placetopay,
connectors::Plaid,
diff --git a/crates/router/src/core/connector_validation.rs b/crates/router/src/core/connector_validation.rs
index c6271341d6..8df3036e35 100644
--- a/crates/router/src/core/connector_validation.rs
+++ b/crates/router/src/core/connector_validation.rs
@@ -415,10 +415,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> {
payu::transformers::PayuAuthType::try_from(self.auth_type)?;
Ok(())
}
- // api_enums::Connector::Peachpayments => {
- // peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?;
- // Ok(())
- // }
+ api_enums::Connector::Peachpayments => {
+ peachpayments::transformers::PeachpaymentsAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Placetopay => {
placetopay::transformers::PlacetopayAuthType::try_from(self.auth_type)?;
Ok(())
diff --git a/crates/router/src/types/api/connector_mapping.rs b/crates/router/src/types/api/connector_mapping.rs
index 28300ecbf2..2333f1c8bc 100644
--- a/crates/router/src/types/api/connector_mapping.rs
+++ b/crates/router/src/types/api/connector_mapping.rs
@@ -352,9 +352,9 @@ impl ConnectorData {
Ok(ConnectorEnum::Old(Box::new(connector::Payone::new())))
}
enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))),
- // enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new(
- // hyperswitch_connectors::connectors::Peachpayments::new(),
- // ))),
+ enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new(
+ hyperswitch_connectors::connectors::Peachpayments::new(),
+ ))),
enums::Connector::Placetopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new())))
}
diff --git a/crates/router/src/types/api/feature_matrix.rs b/crates/router/src/types/api/feature_matrix.rs
index d82c1968b0..d5480ab2c2 100644
--- a/crates/router/src/types/api/feature_matrix.rs
+++ b/crates/router/src/types/api/feature_matrix.rs
@@ -274,9 +274,9 @@ impl FeatureMatrixConnectorData {
Ok(ConnectorEnum::Old(Box::new(connector::Payone::new())))
}
enums::Connector::Payu => Ok(ConnectorEnum::Old(Box::new(connector::Payu::new()))),
- // enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new(
- // connector::Peachpayments::new(),
- // ))),
+ enums::Connector::Peachpayments => Ok(ConnectorEnum::Old(Box::new(
+ connector::Peachpayments::new(),
+ ))),
enums::Connector::Placetopay => {
Ok(ConnectorEnum::Old(Box::new(connector::Placetopay::new())))
}
diff --git a/crates/router/src/types/connector_transformers.rs b/crates/router/src/types/connector_transformers.rs
index 683ba60373..6bcec0681d 100644
--- a/crates/router/src/types/connector_transformers.rs
+++ b/crates/router/src/types/connector_transformers.rs
@@ -113,7 +113,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Paysafe => Self::Paysafe,
api_enums::Connector::Paystack => Self::Paystack,
api_enums::Connector::Payu => Self::Payu,
- // api_enums::Connector::Peachpayments => Self::Peachpayments,
+ api_enums::Connector::Peachpayments => Self::Peachpayments,
api_models::enums::Connector::Placetopay => Self::Placetopay,
api_enums::Connector::Plaid => Self::Plaid,
api_enums::Connector::Powertranz => Self::Powertranz,