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): [PowerTranz] Add cards support for PowerTranz connector (#1687)
Arjun Karthik07120bf42204
diff --git a/config/config.example.toml b/config/config.example.tomlindex f1910c8f5e..4f54a4a6c2 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -183,7 +183,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"payme.base_url = "https://sandbox.payme.io/"paypal.base_url = "https://www.sandbox.paypal.com/"payu.base_url = "https://secure.snd.payu.com/"-powertranz.base_url = "https://staging.ptranz.com/api/spi/"+powertranz.base_url = "https://staging.ptranz.com/api/"rapyd.base_url = "https://sandboxapi.rapyd.net"shift4.base_url = "https://api.shift4.com/"stripe.base_url = "https://api.stripe.com/"diff --git a/config/development.toml b/config/development.tomlindex 8f1566d7b5..ce57de8ec9 100644--- a/config/development.toml+++ b/config/development.toml@@ -143,7 +143,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"payme.base_url = "https://sandbox.payme.io/"paypal.base_url = "https://www.sandbox.paypal.com/"payu.base_url = "https://secure.snd.payu.com/"-powertranz.base_url = "https://staging.ptranz.com/api/spi/"+powertranz.base_url = "https://staging.ptranz.com/api/"rapyd.base_url = "https://sandboxapi.rapyd.net"shift4.base_url = "https://api.shift4.com/"stripe.base_url = "https://api.stripe.com/"diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex 454805d63b..8a6edfce6c 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -104,7 +104,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"payme.base_url = "https://sandbox.payme.io/"paypal.base_url = "https://www.sandbox.paypal.com/"payu.base_url = "https://secure.snd.payu.com/"-powertranz.base_url = "https://staging.ptranz.com/api/spi/"+powertranz.base_url = "https://staging.ptranz.com/api/"rapyd.base_url = "https://sandboxapi.rapyd.net"shift4.base_url = "https://api.shift4.com/"stripe.base_url = "https://api.stripe.com/"diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rsindex 65354e008a..3dad6e8fc8 100644--- a/crates/api_models/src/enums.rs+++ b/crates/api_models/src/enums.rs@@ -656,7 +656,7 @@ pub enum Connector {Payme,Paypal,Payu,- //Powertranz,+ Powertranz,Rapyd,Shift4,Stripe,@@ -762,7 +762,7 @@ pub enum RoutableConnectors {Payme,Paypal,Payu,- //Powertranz,+ Powertranz,Rapyd,Shift4,Stripe,diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rsindex 9afd9d8708..13410dbe5c 100644--- a/crates/diesel_models/src/enums.rs+++ b/crates/diesel_models/src/enums.rs@@ -267,6 +267,119 @@ pub enum Currency {ZAR,}+impl Currency {+ pub fn iso_4217(&self) -> &'static str {+ match *self {+ Self::AED => "784",+ Self::ALL => "008",+ Self::AMD => "051",+ Self::ANG => "532",+ Self::ARS => "032",+ Self::AUD => "036",+ Self::AWG => "533",+ Self::AZN => "944",+ Self::BBD => "052",+ Self::BDT => "050",+ Self::BHD => "048",+ Self::BMD => "060",+ Self::BND => "096",+ Self::BOB => "068",+ Self::BRL => "986",+ Self::BSD => "044",+ Self::BWP => "072",+ Self::BZD => "084",+ Self::CAD => "124",+ Self::CHF => "756",+ Self::COP => "170",+ Self::CRC => "188",+ Self::CUP => "192",+ Self::CZK => "203",+ Self::DKK => "208",+ Self::DOP => "214",+ Self::DZD => "012",+ Self::EGP => "818",+ Self::ETB => "230",+ Self::EUR => "978",+ Self::FJD => "242",+ Self::GBP => "826",+ Self::GHS => "936",+ Self::GIP => "292",+ Self::GMD => "270",+ Self::GTQ => "320",+ Self::GYD => "328",+ Self::HKD => "344",+ Self::HNL => "340",+ Self::HTG => "332",+ Self::HUF => "348",+ Self::HRK => "191",+ Self::IDR => "360",+ Self::ILS => "376",+ Self::INR => "356",+ Self::JMD => "388",+ Self::JOD => "400",+ Self::JPY => "392",+ Self::KES => "404",+ Self::KGS => "417",+ Self::KHR => "116",+ Self::KRW => "410",+ Self::KWD => "414",+ Self::KYD => "136",+ Self::KZT => "398",+ Self::LAK => "418",+ Self::LBP => "422",+ Self::LKR => "144",+ Self::LRD => "430",+ Self::LSL => "426",+ Self::MAD => "504",+ Self::MDL => "498",+ Self::MKD => "807",+ Self::MMK => "104",+ Self::MNT => "496",+ Self::MOP => "446",+ Self::MUR => "480",+ Self::MVR => "462",+ Self::MWK => "454",+ Self::MXN => "484",+ Self::MYR => "458",+ Self::NAD => "516",+ Self::NGN => "566",+ Self::NIO => "558",+ Self::NOK => "578",+ Self::NPR => "524",+ Self::NZD => "554",+ Self::OMR => "512",+ Self::PEN => "604",+ Self::PGK => "598",+ Self::PHP => "608",+ Self::PKR => "586",+ Self::PLN => "985",+ Self::QAR => "634",+ Self::RON => "946",+ Self::CNY => "156",+ Self::RUB => "643",+ Self::SAR => "682",+ Self::SCR => "690",+ Self::SEK => "752",+ Self::SGD => "702",+ Self::SLL => "694",+ Self::SOS => "706",+ Self::SSP => "728",+ Self::SVC => "222",+ Self::SZL => "748",+ Self::THB => "764",+ Self::TRY => "949",+ Self::TTD => "780",+ Self::TWD => "901",+ Self::TZS => "834",+ Self::USD => "840",+ Self::UYU => "858",+ Self::UZS => "860",+ Self::YER => "886",+ Self::ZAR => "710",+ }+ }+}+#[derive(Clone,Copy,diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rsindex d9880b1143..e19e1a3bf2 100644--- a/crates/router/src/connector/powertranz.rs+++ b/crates/router/src/connector/powertranz.rs@@ -6,8 +6,10 @@ use error_stack::{IntoReport, ResultExt};use masking::ExposeInterface;use transformers as powertranz;+use super::utils::PaymentsAuthorizeRequestData;use crate::{configs::settings,+ consts,core::errors::{self, CustomResult},headers,services::{@@ -39,6 +41,9 @@ impl api::RefundExecute for Powertranz {}impl api::RefundSync for Powertranz {}impl api::PaymentToken for Powertranz {}+const POWER_TRANZ_ID: &str = "PowerTranz-PowerTranzId";+const POWER_TRANZ_PASSWORD: &str = "PowerTranz-PowerTranzPassword";+implConnectorIntegration<api::PaymentMethodToken,@@ -46,7 +51,6 @@ impltypes::PaymentsResponseData,> for Powertranz{- // Not Implemented (R)}impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Powertranz@@ -60,12 +64,10 @@ where) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {let mut header = vec![(headers::CONTENT_TYPE.to_string(),- types::PaymentsAuthorizeType::get_content_type(self)- .to_string()- .into(),+ self.common_get_content_type().to_string().into(),)];- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;- header.append(&mut api_key);+ let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;+ header.append(&mut auth_header);Ok(header)}}@@ -89,10 +91,16 @@ impl ConnectorCommon for Powertranz {) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {let auth = powertranz::PowertranzAuthType::try_from(auth_type).change_context(errors::ConnectorError::FailedToObtainAuthType)?;- Ok(vec![(- headers::AUTHORIZATION.to_string(),- auth.api_key.expose().into_masked(),- )])+ Ok(vec![+ (+ POWER_TRANZ_ID.to_string(),+ auth.power_tranz_id.expose().into_masked(),+ ),+ (+ POWER_TRANZ_PASSWORD.to_string(),+ auth.power_tranz_password.expose().into_masked(),+ ),+ ])}fn build_error_response(@@ -103,12 +111,22 @@ impl ConnectorCommon for Powertranz {.response.parse_struct("PowertranzErrorResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ let first_error = response.errors.first();+ let code = first_error.map(|error| error.code.clone());+ let message = first_error.map(|error| error.message.clone());Ok(ErrorResponse {status_code: res.status_code,- code: response.code,- message: response.message,- reason: response.reason,+ code: code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),+ message: message.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),+ reason: Some(+ response+ .errors+ .iter()+ .map(|error| format!("{} : {}", error.code, error.message))+ .collect::<Vec<_>>()+ .join(", "),+ ),})}}@@ -116,7 +134,6 @@ impl ConnectorCommon for Powertranz {impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>for Powertranz{- //TODO: implement sessions flow}impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>@@ -146,10 +163,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::Pfn get_url(&self,- _req: &types::PaymentsAuthorizeRouterData,- _connectors: &settings::Connectors,+ req: &types::PaymentsAuthorizeRouterData,+ connectors: &settings::Connectors,) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())+ let endpoint = match req.request.is_auto_capture()? {+ true => "sale",+ false => "auth",+ };+ Ok(format!("{}{endpoint}", self.base_url(connectors)))}fn get_request_body(@@ -190,7 +211,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::Pdata: &types::PaymentsAuthorizeRouterData,res: Response,) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {- let response: powertranz::PowertranzPaymentsResponse = res+ let response: powertranz::PowertranzBaseResponse = res.response.parse_struct("Powertranz PaymentsAuthorizeResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;@@ -211,10 +232,25 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::Pimpl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>for Powertranz+{+ fn build_request(+ &self,+ _req: &types::PaymentsSyncRouterData,+ _connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ Err(errors::ConnectorError::FlowNotSupported {+ flow: "Payment Sync".to_string(),+ connector: "PowerTranz".to_string(),+ })?+ }+}++impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>+ for Powertranz{fn get_headers(&self,- req: &types::PaymentsSyncRouterData,+ req: &types::PaymentsCaptureRouterData,connectors: &settings::Connectors,) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {self.build_headers(req, connectors)@@ -226,35 +262,51 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRefn get_url(&self,- _req: &types::PaymentsSyncRouterData,- _connectors: &settings::Connectors,+ _req: &types::PaymentsCaptureRouterData,+ connectors: &settings::Connectors,) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())+ Ok(format!("{}capture", self.base_url(connectors)))+ }++ fn get_request_body(+ &self,+ req: &types::PaymentsCaptureRouterData,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let req_obj = powertranz::PowertranzBaseRequest::try_from(&req.request)?;+ let powertranz_req = types::RequestBody::log_and_get_request_body(+ &req_obj,+ utils::Encode::<powertranz::PowertranzBaseRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(powertranz_req))}fn build_request(&self,- req: &types::PaymentsSyncRouterData,+ req: &types::PaymentsCaptureRouterData,connectors: &settings::Connectors,) -> CustomResult<Option<services::Request>, errors::ConnectorError> {Ok(Some(services::RequestBuilder::new()- .method(services::Method::Get)- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)+ .method(services::Method::Post)+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?).attach_default_headers()- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)+ .headers(types::PaymentsCaptureType::get_headers(+ self, req, connectors,+ )?)+ .body(types::PaymentsCaptureType::get_request_body(self, req)?).build(),))}fn handle_response(&self,- data: &types::PaymentsSyncRouterData,+ data: &types::PaymentsCaptureRouterData,res: Response,- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {- let response: powertranz::PowertranzPaymentsResponse = res+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {+ let response: powertranz::PowertranzBaseResponse = res.response- .parse_struct("powertranz PaymentsSyncResponse")+ .parse_struct("Powertranz PaymentsCaptureResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;types::RouterData::try_from(types::ResponseRouterData {response,@@ -271,62 +323,46 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe}}-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>for Powertranz{fn get_headers(&self,- req: &types::PaymentsCaptureRouterData,+ req: &types::PaymentsCancelRouterData,connectors: &settings::Connectors,) -> CustomResult<Vec<(String, request::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: &types::PaymentsCaptureRouterData,- _connectors: &settings::Connectors,+ _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,+ connectors: &settings::Connectors,) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())+ Ok(format!("{}void", self.base_url(connectors)))}fn get_request_body(&self,- _req: &types::PaymentsCaptureRouterData,+ req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())- }-- fn build_request(- &self,- req: &types::PaymentsCaptureRouterData,- connectors: &settings::Connectors,- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {- Ok(Some(- services::RequestBuilder::new()- .method(services::Method::Post)- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)- .attach_default_headers()- .headers(types::PaymentsCaptureType::get_headers(- self, req, connectors,- )?)- .body(types::PaymentsCaptureType::get_request_body(self, req)?)- .build(),- ))+ let req_obj = powertranz::PowertranzBaseRequest::try_from(&req.request)?;+ let powertranz_req = types::RequestBody::log_and_get_request_body(+ &req_obj,+ utils::Encode::<powertranz::PowertranzBaseRequest>::encode_to_string_of_json,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(powertranz_req))}fn handle_response(&self,- data: &types::PaymentsCaptureRouterData,+ data: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,res: Response,- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {- let response: powertranz::PowertranzPaymentsResponse = res+ ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {+ let response: powertranz::PowertranzBaseResponse = res.response- .parse_struct("Powertranz PaymentsCaptureResponse")+ .parse_struct("powertranz CancelResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;types::RouterData::try_from(types::ResponseRouterData {response,@@ -335,6 +371,22 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme})}+ fn build_request(+ &self,+ req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,+ connectors: &settings::Connectors,+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {+ Ok(Some(+ services::RequestBuilder::new()+ .method(services::Method::Post)+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)+ .attach_default_headers()+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)+ .body(types::PaymentsVoidType::get_request_body(self, req)?)+ .build(),+ ))+ }+fn get_error_response(&self,res: Response,@@ -343,11 +395,6 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme}}-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>- for Powertranz-{-}-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>for Powertranz{@@ -366,19 +413,19 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponfn get_url(&self,_req: &types::RefundsRouterData<api::Execute>,- _connectors: &settings::Connectors,+ connectors: &settings::Connectors,) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())+ Ok(format!("{}refund", self.base_url(connectors)))}fn get_request_body(&self,req: &types::RefundsRouterData<api::Execute>,) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {- let req_obj = powertranz::PowertranzRefundRequest::try_from(req)?;+ let req_obj = powertranz::PowertranzBaseRequest::try_from(req)?;let powertranz_req = types::RequestBody::log_and_get_request_body(&req_obj,- utils::Encode::<powertranz::PowertranzRefundRequest>::encode_to_string_of_json,+ utils::Encode::<powertranz::PowertranzBaseRequest>::encode_to_string_of_json,).change_context(errors::ConnectorError::RequestEncodingFailed)?;Ok(Some(powertranz_req))@@ -406,7 +453,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespondata: &types::RefundsRouterData<api::Execute>,res: Response,) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {- let response: powertranz::RefundResponse = res+ let response: powertranz::PowertranzBaseResponse = res.response.parse_struct("powertranz RefundResponse").change_context(errors::ConnectorError::ResponseDeserializationFailed)?;@@ -428,63 +475,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponimpl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>for Powertranz{- fn get_headers(- &self,- req: &types::RefundSyncRouterData,- connectors: &settings::Connectors,- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {- self.build_headers(req, connectors)- }-- fn get_content_type(&self) -> &'static str {- self.common_get_content_type()- }-- fn get_url(+ fn build_request(&self,_req: &types::RefundSyncRouterData,_connectors: &settings::Connectors,- ) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())- }-- fn build_request(- &self,- req: &types::RefundSyncRouterData,- connectors: &settings::Connectors,) -> CustomResult<Option<services::Request>, errors::ConnectorError> {- Ok(Some(- services::RequestBuilder::new()- .method(services::Method::Get)- .url(&types::RefundSyncType::get_url(self, req, connectors)?)- .attach_default_headers()- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)- .body(types::RefundSyncType::get_request_body(self, req)?)- .build(),- ))- }-- fn handle_response(- &self,- data: &types::RefundSyncRouterData,- res: Response,- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {- let response: powertranz::RefundResponse = res- .response- .parse_struct("powertranz RefundSyncResponse")- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;- types::RouterData::try_from(types::ResponseRouterData {- response,- data: data.clone(),- http_code: res.status_code,- })- }-- fn get_error_response(- &self,- res: Response,- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {- self.build_error_response(res)+ Err(errors::ConnectorError::FlowNotSupported {+ flow: "Refund Sync".to_string(),+ connector: "PowerTranz".to_string(),+ })?}}diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rsindex 6ce06d446b..a00af5d215 100644--- a/crates/router/src/connector/powertranz/transformers.rs+++ b/crates/router/src/connector/powertranz/transformers.rs@@ -1,211 +1,338 @@-use masking::Secret;+use api_models::payments::{Address, Card};+use common_utils::pii::Email;+use diesel_models::enums::RefundStatus;+use masking::{ExposeInterface, Secret};use serde::{Deserialize, Serialize};+use uuid::Uuid;use crate::{- connector::utils::PaymentsAuthorizeRequestData,+ connector::utils::{self, CardData},+ consts,core::errors,- types::{self, api, storage::enums},+ types::{self, api, storage::enums, transformers::ForeignFrom},};-//TODO: Fill the struct with respective fields-#[derive(Default, Debug, Serialize, Eq, PartialEq)]+#[derive(Debug, Serialize)]+#[serde(rename_all = "PascalCase")]pub struct PowertranzPaymentsRequest {- amount: i64,- card: PowertranzCard,+ transaction_identifier: String,+ total_amount: f64,+ currency_code: String,+ three_d_secure: bool,+ source: Source,+ order_identifier: String,+ billing_address: Option<PowertranzAddressDetails>,+ shipping_address: Option<PowertranzAddressDetails>,}-#[derive(Default, Debug, Serialize, Eq, PartialEq)]+#[derive(Debug, Serialize)]+#[serde(untagged)]+pub enum Source {+ Card(PowertranzCard),+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "PascalCase")]pub struct PowertranzCard {- name: Secret<String>,- number: cards::CardNumber,- expiry_month: Secret<String>,- expiry_year: Secret<String>,- cvc: Secret<String>,- complete: bool,+ cardholder_name: Secret<String>,+ card_pan: cards::CardNumber,+ card_expiration: Secret<String>,+ card_cvv: Secret<String>,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "PascalCase")]+pub struct PowertranzAddressDetails {+ first_name: Option<Secret<String>>,+ last_name: Option<Secret<String>>,+ line1: Option<Secret<String>>,+ line2: Option<Secret<String>>,+ city: Option<String>,+ country: Option<enums::CountryAlpha2>,+ state: Option<Secret<String>>,+ postal_code: Option<Secret<String>>,+ email_address: Option<Email>,+ phone_number: Option<Secret<String>>,}impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {- match item.request.payment_method_data.clone() {- api::PaymentMethodData::Card(req_card) => {- let card = PowertranzCard {- name: req_card.card_holder_name,- number: req_card.card_number,- expiry_month: req_card.card_exp_month,- expiry_year: req_card.card_exp_year,- cvc: req_card.card_cvc,- complete: item.request.is_auto_capture()?,- };- Ok(Self {- amount: item.request.amount,- card,+ let source = match item.request.payment_method_data.clone() {+ api::PaymentMethodData::Card(card) => Ok(Source::from(&card)),+ _ => Err(errors::ConnectorError::NotImplemented(+ "Payment method".to_string(),+ )),+ }?;+ let billing_address = get_address_details(&item.address.billing, &item.request.email);+ let shipping_address = get_address_details(&item.address.shipping, &item.request.email);+ Ok(Self {+ transaction_identifier: Uuid::new_v4().to_string(),+ total_amount: utils::to_currency_base_unit_asf64(+ item.request.amount,+ item.request.currency,+ )?,+ currency_code: diesel_models::enums::Currency::iso_4217(&item.request.currency)+ .to_string(),+ three_d_secure: false,+ source,+ order_identifier: item.payment_id.clone(),+ billing_address,+ shipping_address,+ })+ }+}++fn get_address_details(+ address: &Option<Address>,+ email: &Option<Email>,+) -> Option<PowertranzAddressDetails> {+ let phone_number = address+ .as_ref()+ .and_then(|address| address.phone.as_ref())+ .and_then(|phone| {+ phone.number.as_ref().and_then(|number| {+ phone.country_code.as_ref().map(|country_code| {+ Secret::new(format!("{}{}", country_code, number.clone().expose()))})- }- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),- }+ })+ });++ address+ .as_ref()+ .and_then(|address| address.address.as_ref())+ .map(|address_details| PowertranzAddressDetails {+ first_name: address_details.first_name.clone(),+ last_name: address_details.last_name.clone(),+ line1: address_details.line1.clone(),+ line2: address_details.line2.clone(),+ city: address_details.city.clone(),+ country: address_details.country,+ state: address_details.state.clone(),+ postal_code: address_details.zip.clone(),+ email_address: email.clone(),+ phone_number,+ })+}++impl From<&Card> for Source {+ fn from(card: &Card) -> Self {+ let card = PowertranzCard {+ cardholder_name: card.card_holder_name.clone(),+ card_pan: card.card_number.clone(),+ card_expiration: card.get_expiry_date_as_yymm(),+ card_cvv: card.card_cvc.clone(),+ };+ Self::Card(card)}}-//TODO: Fill the struct with respective fields// Auth Structpub struct PowertranzAuthType {- pub(super) api_key: Secret<String>,+ pub(super) power_tranz_id: Secret<String>,+ pub(super) power_tranz_password: Secret<String>,}impl TryFrom<&types::ConnectorAuthType> for PowertranzAuthType {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {match auth_type {- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {- api_key: Secret::new(api_key.to_string()),+ types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {+ power_tranz_id: Secret::new(key1.to_string()),+ power_tranz_password: Secret::new(api_key.to_string()),}),_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),}}}-// PaymentsResponse-//TODO: Append the remaining status flags-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "lowercase")]-pub enum PowertranzPaymentStatus {- Succeeded,- Failed,- #[default]- Processing,-}--impl From<PowertranzPaymentStatus> for enums::AttemptStatus {- fn from(item: PowertranzPaymentStatus) -> Self {- match item {- PowertranzPaymentStatus::Succeeded => Self::Charged,- PowertranzPaymentStatus::Failed => Self::Failure,- PowertranzPaymentStatus::Processing => Self::Authorizing,- }- }++// Common struct used in Payment, Capture, Void, Refund+#[derive(Debug, Deserialize)]+#[serde(rename_all = "PascalCase")]+pub struct PowertranzBaseResponse {+ transaction_type: u8,+ approved: bool,+ transaction_identifier: String,+ original_trxn_identifier: Option<String>,+ errors: Option<Vec<Error>>,}-//TODO: Fill the struct with respective fields-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]-pub struct PowertranzPaymentsResponse {- status: PowertranzPaymentStatus,- id: String,+impl ForeignFrom<(u8, bool)> for enums::AttemptStatus {+ fn foreign_from((transaction_type, approved): (u8, bool)) -> Self {+ match transaction_type {+ // Auth+ 1 => match approved {+ true => Self::Authorized,+ false => Self::Failure,+ },+ // Sale or Capture+ 2 | 3 => match approved {+ true => Self::Charged,+ false => Self::Failure,+ },+ // Void+ 4 => match approved {+ true => Self::Voided,+ false => Self::VoidFailed,+ },+ // Refund+ 5 => match approved {+ true => Self::AutoRefunded,+ false => Self::Failure,+ },+ // Risk Management+ _ => match approved {+ true => Self::Pending,+ false => Self::Failure,+ },+ }+ }}impl<F, T>- TryFrom<- types::ResponseRouterData<F, PowertranzPaymentsResponse, T, types::PaymentsResponseData>,- > for types::RouterData<F, T, types::PaymentsResponseData>+ TryFrom<types::ResponseRouterData<F, PowertranzBaseResponse, T, types::PaymentsResponseData>>+ for types::RouterData<F, T, types::PaymentsResponseData>{type Error = error_stack::Report<errors::ConnectorError>;fn try_from(- item: types::ResponseRouterData<- F,- PowertranzPaymentsResponse,- T,- types::PaymentsResponseData,- >,+ item: types::ResponseRouterData<F, PowertranzBaseResponse, T, types::PaymentsResponseData>,) -> Result<Self, Self::Error> {- Ok(Self {- status: enums::AttemptStatus::from(item.response.status),- response: Ok(types::PaymentsResponseData::TransactionResponse {- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),+ let error_response = build_error_response(&item.response, item.http_code);+ // original_trxn_identifier will be present only in capture and void+ let connector_transaction_id = item+ .response+ .original_trxn_identifier+ .unwrap_or(item.response.transaction_identifier);+ let response = error_response.map_or(+ Ok(types::PaymentsResponseData::TransactionResponse {+ resource_id: types::ResponseId::ConnectorTransactionId(connector_transaction_id),redirection_data: None,mandate_reference: None,connector_metadata: None,network_txn_id: None,connector_response_reference_id: None,}),+ Err,+ );+ Ok(Self {+ status: enums::AttemptStatus::foreign_from((+ item.response.transaction_type,+ item.response.approved,+ )),+ response,..item.data})}}-//TODO: Fill the struct with respective fields-// REFUND :-// Type definition for RefundRequest+// Type definition for Capture, Void, Refund Request#[derive(Default, Debug, Serialize)]-pub struct PowertranzRefundRequest {- pub amount: i64,+#[serde(rename_all = "PascalCase")]+pub struct PowertranzBaseRequest {+ transaction_identifier: String,+ total_amount: Option<f64>,+ refund: Option<bool>,}-impl<F> TryFrom<&types::RefundsRouterData<F>> for PowertranzRefundRequest {+impl TryFrom<&types::PaymentsCancelData> for PowertranzBaseRequest {type Error = error_stack::Report<errors::ConnectorError>;- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {+ fn try_from(item: &types::PaymentsCancelData) -> Result<Self, Self::Error> {Ok(Self {- amount: item.request.refund_amount,+ transaction_identifier: item.connector_transaction_id.clone(),+ total_amount: None,+ refund: None,})}}-// Type definition for Refund Response--#[allow(dead_code)]-#[derive(Debug, Serialize, Default, Deserialize, Clone)]-pub enum RefundStatus {- Succeeded,- Failed,- #[default]- Processing,-}--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- }+impl TryFrom<&types::PaymentsCaptureData> for PowertranzBaseRequest {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(item: &types::PaymentsCaptureData) -> Result<Self, Self::Error> {+ let total_amount = Some(utils::to_currency_base_unit_asf64(+ item.amount_to_capture,+ item.currency,+ )?);+ Ok(Self {+ transaction_identifier: item.connector_transaction_id.clone(),+ total_amount,+ refund: None,+ })}}-//TODO: Fill the struct with respective fields-#[derive(Default, Debug, Clone, Serialize, Deserialize)]-pub struct RefundResponse {- id: String,- status: RefundStatus,-}--impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>- for types::RefundsRouterData<api::Execute>-{+impl<F> TryFrom<&types::RefundsRouterData<F>> for PowertranzBaseRequest {type Error = error_stack::Report<errors::ConnectorError>;- fn try_from(- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,- ) -> Result<Self, Self::Error> {+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {+ let total_amount = Some(utils::to_currency_base_unit_asf64(+ item.request.refund_amount,+ item.request.currency,+ )?);Ok(Self {- response: Ok(types::RefundsResponseData {- connector_refund_id: item.response.id.to_string(),- refund_status: enums::RefundStatus::from(item.response.status),- }),- ..item.data+ transaction_identifier: item.request.connector_transaction_id.clone(),+ total_amount,+ refund: Some(true),})}}-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>- for types::RefundsRouterData<api::RSync>+impl TryFrom<types::RefundsResponseRouterData<api::Execute, PowertranzBaseResponse>>+ for types::RefundsRouterData<api::Execute>{type Error = error_stack::Report<errors::ConnectorError>;fn try_from(- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,+ item: types::RefundsResponseRouterData<api::Execute, PowertranzBaseResponse>,) -> Result<Self, Self::Error> {- Ok(Self {- response: Ok(types::RefundsResponseData {- connector_refund_id: item.response.id.to_string(),- refund_status: enums::RefundStatus::from(item.response.status),+ let error_response = build_error_response(&item.response, item.http_code);+ let response = error_response.map_or(+ Ok(types::RefundsResponseData {+ connector_refund_id: item.response.transaction_identifier.to_string(),+ refund_status: match item.response.approved {+ true => RefundStatus::Success,+ false => RefundStatus::Failure,+ },}),+ Err,+ );+ Ok(Self {+ response,..item.data})}}-//TODO: Fill the struct with respective fields-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]+fn build_error_response(+ item: &PowertranzBaseResponse,+ status_code: u16,+) -> Option<types::ErrorResponse> {+ item.errors.as_ref().map(|errors| {+ let first_error = errors.first();+ let code = first_error.map(|error| error.code.clone());+ let message = first_error.map(|error| error.message.clone());++ types::ErrorResponse {+ status_code,+ code: code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),+ message: message.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),+ reason: Some(+ errors+ .iter()+ .map(|error| format!("{} : {}", error.code, error.message))+ .collect::<Vec<_>>()+ .join(", "),+ ),+ }+ })+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "PascalCase")]pub struct PowertranzErrorResponse {- pub status_code: u16,+ pub errors: Vec<Error>,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "PascalCase")]+pub struct Error {pub code: String,pub message: String,- pub reason: Option<String>,}diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rsindex ce9e5e3fa5..2c559c91be 100644--- a/crates/router/src/connector/utils.rs+++ b/crates/router/src/connector/utils.rs@@ -11,7 +11,7 @@ use common_utils::{pii::{self, Email, IpAddress},};use error_stack::{report, IntoReport, ResultExt};-use masking::Secret;+use masking::{ExposeInterface, Secret};use once_cell::sync::Lazy;use regex::Regex;use serde::Serializer;@@ -514,6 +514,7 @@ pub trait CardData {) -> Secret<String>;fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>;fn get_expiry_year_4_digit(&self) -> Secret<String>;+ fn get_expiry_date_as_yymm(&self) -> Secret<String>;}impl CardData for api::Card {@@ -553,6 +554,11 @@ impl CardData for api::Card {}Secret::new(year)}+ fn get_expiry_date_as_yymm(&self) -> Secret<String> {+ let year = self.get_card_expiry_year_2_digit().expose();+ let month = self.card_exp_month.clone().expose();+ Secret::new(format!("{year}{month}"))+ }}#[track_caller]diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rsindex b6c70db72a..3b66da8246 100644--- a/crates/router/src/types/api.rs+++ b/crates/router/src/types/api.rs@@ -243,7 +243,7 @@ impl ConnectorData {// "payeezy" => Ok(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usageenums::Connector::Payme => Ok(Box::new(&connector::Payme)),enums::Connector::Payu => Ok(Box::new(&connector::Payu)),- //enums::Connector::Powertranz => Ok(Box::new(&connector::powertranz)),+ enums::Connector::Powertranz => Ok(Box::new(&connector::Powertranz)),enums::Connector::Rapyd => Ok(Box::new(&connector::Rapyd)),enums::Connector::Shift4 => Ok(Box::new(&connector::Shift4)),enums::Connector::Stripe => Ok(Box::new(&connector::Stripe)),diff --git a/crates/router/tests/connectors/powertranz.rs b/crates/router/tests/connectors/powertranz.rsindex 67d0bfd2e4..acd95cfd11 100644--- a/crates/router/tests/connectors/powertranz.rs+++ b/crates/router/tests/connectors/powertranz.rs@@ -65,6 +65,7 @@ async fn should_capture_authorized_payment() {// Partially captures a payment using the manual capture flow (Non 3DS).#[actix_web::test]+#[ignore = "Connector does not support partial capture"]async fn should_partially_capture_authorized_payment() {let response = CONNECTOR.authorize_and_capture_payment(@@ -82,6 +83,7 @@ async fn should_partially_capture_authorized_payment() {// Synchronizes a payment using the manual capture flow (Non 3DS).#[actix_web::test]+#[ignore = "Connector does not support payment sync"]async fn should_sync_authorized_payment() {let authorize_response = CONNECTOR.authorize_payment(payment_method_details(), get_default_payment_info())@@ -163,6 +165,7 @@ async fn should_partially_refund_manually_captured_payment() {// Synchronizes a refund using the manual capture flow (Non 3DS).#[actix_web::test]+#[ignore = "Connector does not support payment sync"]async fn should_sync_manually_captured_refund() {let refund_response = CONNECTOR.capture_payment_and_refund(@@ -200,6 +203,7 @@ async fn should_make_payment() {// Synchronizes a payment using the automatic capture flow (Non 3DS).#[actix_web::test]+#[ignore = "Connector does not support payment sync"]async fn should_sync_auto_captured_payment() {let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info())@@ -260,6 +264,7 @@ async fn should_partially_refund_succeeded_payment() {// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).#[actix_web::test]+#[ignore = "Connector does not support multiple refund"]async fn should_refund_succeeded_payment_multiple_times() {CONNECTOR.make_payment_and_multiple_refund(@@ -275,6 +280,7 @@ async fn should_refund_succeeded_payment_multiple_times() {// Synchronizes a refund using the automatic capture flow (Non 3DS).#[actix_web::test]+#[ignore = "Connector does not support refund sync"]async fn should_sync_refund() {let refund_response = CONNECTOR.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())@@ -314,7 +320,7 @@ async fn should_fail_payment_for_incorrect_cvc() {.unwrap();assert_eq!(response.response.unwrap_err().message,- "Your card's security code is invalid.".to_string(),+ "Field is invalid: CardCvv".to_string(),);}@@ -336,7 +342,7 @@ async fn should_fail_payment_for_invalid_exp_month() {.unwrap();assert_eq!(response.response.unwrap_err().message,- "Your card's expiration month is invalid.".to_string(),+ "Field is invalid: CardExpiration".to_string(),);}@@ -356,10 +362,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {).await.unwrap();- assert_eq!(- response.response.unwrap_err().message,- "Your card's expiration year is invalid.".to_string(),- );+ assert_eq!(response.status, enums::AttemptStatus::Failure,);}// Voids a payment using automatic capture flow (Non 3DS).@@ -376,10 +379,7 @@ async fn should_fail_void_payment_for_auto_capture() {.void_payment(txn_id.unwrap(), None, get_default_payment_info()).await.unwrap();- assert_eq!(- void_response.response.unwrap_err().message,- "You cannot cancel this PaymentIntent because it has a status of succeeded."- );+ assert_eq!(void_response.status, enums::AttemptStatus::VoidFailed);}// Captures a payment using invalid connector payment id.@@ -391,7 +391,7 @@ async fn should_fail_capture_for_invalid_payment() {.unwrap();assert_eq!(capture_response.response.unwrap_err().message,- String::from("No such payment_intent: '123456789'")+ String::from("Original auth not found"));}@@ -409,10 +409,7 @@ async fn should_fail_for_refund_amount_higher_than_payment_amount() {).await.unwrap();- assert_eq!(- response.response.unwrap_err().message,- "Refund amount (₹1.50) is greater than charge amount (₹1.00)",- );+ assert_eq!(response.response.unwrap_err().message, "Invalid amount",);}// Connector dependent test cases goes herediff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.tomlindex 2b273f55ae..1bf520051d 100644--- a/crates/router/tests/connectors/sample_auth.toml+++ b/crates/router/tests/connectors/sample_auth.toml@@ -148,4 +148,5 @@ api_key = "Partner code"key1 = "Credential code"[powertranz]-api_key="API Key"+api_key="PowerTranz-PowerTranzPassword"+key1 = "PowerTranz-PowerTranzId"\ No newline at end of filediff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rsindex 2ca29e996e..17cd85e8d5 100644--- a/crates/test_utils/src/connector_auth.rs+++ b/crates/test_utils/src/connector_auth.rs@@ -39,7 +39,7 @@ pub struct ConnectorAuthentication {pub payme: Option<BodyKey>,pub paypal: Option<BodyKey>,pub payu: Option<BodyKey>,- pub powertranz: Option<HeaderKey>,+ pub powertranz: Option<BodyKey>,pub rapyd: Option<BodyKey>,pub shift4: Option<HeaderKey>,pub stripe: Option<HeaderKey>,diff --git a/loadtest/config/development.toml b/loadtest/config/development.tomlindex 6d95269860..edbe431d04 100644--- a/loadtest/config/development.toml+++ b/loadtest/config/development.toml@@ -91,7 +91,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"payme.base_url = "https://sandbox.payme.io/"paypal.base_url = "https://www.sandbox.paypal.com/"payu.base_url = "https://secure.snd.payu.com/"-powertranz.base_url = "https://staging.ptranz.com/api/spi/"+powertranz.base_url = "https://staging.ptranz.com/api/"rapyd.base_url = "https://sandboxapi.rapyd.net"shift4.base_url = "https://api.shift4.com/"stripe.base_url = "https://api.stripe.com/"diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.jsonindex bc499aaebd..7bf717cb30 100644--- a/openapi/openapi_spec.json+++ b/openapi/openapi_spec.json@@ -2954,6 +2954,7 @@"payme","paypal","payu",+ "powertranz","rapyd","shift4","stripe",