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): [Iatapay] Implement AccessTokenAuth, Authorize, PSync, Refund, RSync and testcases (#1034)

Arvind Patela2527b5b2af0
diff --git a/config/config.example.toml b/config/config.example.toml
index e00730d62c..bda2714247 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -160,6 +160,7 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
fiserv.base_url = "https://cert.api.fiservapps.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
+iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
diff --git a/config/development.toml b/config/development.toml
index 3ef6509f46..b537128d78 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -67,6 +67,7 @@ cards = [
"fiserv",
"forte",
"globalpay",
+ "iatapay",
"mollie",
"multisafepay",
"nexinets",
@@ -113,6 +114,7 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
fiserv.base_url = "https://cert.api.fiservapps.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
+iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 6a6d8220a5..10f5129c77 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -84,6 +84,7 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
fiserv.base_url = "https://cert.api.fiservapps.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
+iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
@@ -122,6 +123,7 @@ cards = [
"fiserv",
"forte",
"globalpay",
+ "iatapay",
"mollie",
"multisafepay",
"nexinets",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index a7dcc8941d..2deab45a86 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -268,6 +268,7 @@ pub enum Currency {
#[strum(serialize_all = "snake_case")]
pub enum EventType {
PaymentSucceeded,
+ PaymentFailed,
PaymentProcessing,
ActionRequired,
RefundSucceeded,
@@ -592,6 +593,7 @@ pub enum Connector {
Cybersource,
#[default]
Dummy,
+ Iatapay,
#[cfg(feature = "dummy_connector")]
#[serde(rename = "dummyconnector")]
#[strum(serialize = "dummyconnector")]
@@ -628,6 +630,7 @@ impl Connector {
| (Self::Paypal, _)
| (Self::Payu, _)
| (Self::Trustpay, PaymentMethod::BankRedirect)
+ | (Self::Iatapay, _)
)
}
pub fn supports_file_storage_module(&self) -> bool {
@@ -671,6 +674,7 @@ pub enum RoutableConnectors {
Fiserv,
Forte,
Globalpay,
+ Iatapay,
Klarna,
Mollie,
Multisafepay,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 7c17396594..7f81bfc6d0 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -370,6 +370,7 @@ pub struct Connectors {
pub fiserv: ConnectorParams,
pub forte: ConnectorParams,
pub globalpay: ConnectorParams,
+ pub iatapay: ConnectorParams,
pub klarna: ConnectorParams,
pub mollie: ConnectorParams,
pub multisafepay: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 0683a8be33..a57ba2998f 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -14,6 +14,7 @@ pub mod dummyconnector;
pub mod fiserv;
pub mod forte;
pub mod globalpay;
+pub mod iatapay;
pub mod klarna;
pub mod multisafepay;
pub mod nexinets;
@@ -39,8 +40,8 @@ pub use self::{
aci::Aci, adyen::Adyen, airwallex::Airwallex, authorizedotnet::Authorizedotnet,
bambora::Bambora, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout,
coinbase::Coinbase, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte,
- globalpay::Globalpay, klarna::Klarna, mollie::Mollie, multisafepay::Multisafepay,
- nexinets::Nexinets, nuvei::Nuvei, opennode::Opennode, payeezy::Payeezy, paypal::Paypal,
- payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay,
- worldline::Worldline, worldpay::Worldpay, zen::Zen,
+ globalpay::Globalpay, iatapay::Iatapay, klarna::Klarna, mollie::Mollie,
+ multisafepay::Multisafepay, nexinets::Nexinets, nuvei::Nuvei, opennode::Opennode,
+ payeezy::Payeezy, paypal::Paypal, payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe,
+ trustpay::Trustpay, worldline::Worldline, worldpay::Worldpay, zen::Zen,
};
diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs
new file mode 100644
index 0000000000..4e7306cbe8
--- /dev/null
+++ b/crates/router/src/connector/iatapay.rs
@@ -0,0 +1,703 @@
+mod transformers;
+
+use std::fmt::Debug;
+
+use base64::Engine;
+use common_utils::{crypto, ext_traits::ByteSliceExt};
+use error_stack::{IntoReport, ResultExt};
+use transformers as iatapay;
+
+use self::iatapay::IatapayPaymentsResponse;
+use super::utils::{self, base64_decode};
+use crate::{
+ configs::settings,
+ consts,
+ core::errors::{self, CustomResult},
+ db, headers,
+ services::{self, ConnectorIntegration},
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, Response,
+ },
+ utils::{BytesExt, Encode},
+};
+
+#[derive(Debug, Clone)]
+pub struct Iatapay;
+
+impl api::Payment for Iatapay {}
+impl api::PaymentSession for Iatapay {}
+impl api::ConnectorAccessToken for Iatapay {}
+impl api::PreVerify for Iatapay {}
+impl api::PaymentAuthorize for Iatapay {}
+impl api::PaymentSync for Iatapay {}
+impl api::PaymentCapture for Iatapay {}
+impl api::PaymentVoid for Iatapay {}
+impl api::Refund for Iatapay {}
+impl api::RefundExecute for Iatapay {}
+impl api::RefundSync for Iatapay {}
+impl api::PaymentToken for Iatapay {}
+
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Iatapay
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Iatapay
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &types::RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let mut headers = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string(),
+ )];
+ let access_token = req
+ .access_token
+ .clone()
+ .ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
+
+ let auth_header = (
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", access_token.token),
+ );
+ headers.push(auth_header);
+ Ok(headers)
+ }
+}
+
+impl ConnectorCommon for Iatapay {
+ fn id(&self) -> &'static str {
+ "iatapay"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.iatapay.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let auth = iatapay::IatapayAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(headers::AUTHORIZATION.to_string(), auth.client_id)])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: iatapay::IatapayErrorResponse = res
+ .response
+ .parse_struct("IatapayErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.error,
+ message: response.message,
+ reason: response.reason,
+ })
+ }
+}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Iatapay
+{
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Iatapay
+{
+ fn get_url(
+ &self,
+ _req: &types::RefreshTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}{}", self.base_url(connectors), "/oauth/token"))
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ "application/x-www-form-urlencoded"
+ }
+
+ fn get_headers(
+ &self,
+ req: &types::RefreshTokenRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let auth: iatapay::IatapayAuthType =
+ iatapay::IatapayAuthType::try_from(&req.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+
+ let auth_id = format!("{}:{}", auth.client_id, auth.client_secret);
+ let auth_val: String = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id));
+
+ Ok(vec![
+ (
+ headers::CONTENT_TYPE.to_string(),
+ types::RefreshTokenType::get_content_type(self).to_string(),
+ ),
+ (headers::AUTHORIZATION.to_string(), auth_val),
+ ])
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefreshTokenRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = iatapay::IatapayAuthUpdateRequest::try_from(req)?;
+ println!("##accReq={:?}", req_obj);
+ let iatapay_req = Encode::<iatapay::IatapayAuthUpdateRequest>::url_encode(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ println!("##accReqString={:?}", iatapay_req);
+ Ok(Some(iatapay_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefreshTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let req = Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .attach_default_headers()
+ .headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
+ .url(&types::RefreshTokenType::get_url(self, req, connectors)?)
+ .body(types::RefreshTokenType::get_request_body(self, req)?)
+ .build(),
+ );
+
+ Ok(req)
+ }
+ fn handle_response(
+ &self,
+ data: &types::RefreshTokenRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
+ let response: iatapay::IatapayAuthUpdateResponse = res
+ .response
+ .parse_struct("iatapay IatapayAuthUpdateResponse")
+ .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> {
+ let response: iatapay::IatapayAccessTokenErrorResponse = res
+ .response
+ .parse_struct("Iatapay AccessTokenErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.error,
+ message: response.error_description,
+ reason: None,
+ })
+ }
+}
+
+impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
+ for Iatapay
+{
+}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Iatapay
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, 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::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/payments/", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = iatapay::IatapayPaymentsRequest::try_from(req)?;
+ let iatapay_req =
+ Encode::<iatapay::IatapayPaymentsRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(iatapay_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsAuthorizeType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: IatapayPaymentsResponse = res
+ .response
+ .parse_struct("Iatapay PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Iatapay
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, 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::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let connector_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}/payments/{}",
+ self.base_url(connectors),
+ connector_id
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ 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)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: IatapayPaymentsResponse = res
+ .response
+ .parse_struct("iatapay PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Iatapay
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, 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,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ ) -> CustomResult<Option<String>, 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> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: IatapayPaymentsResponse = res
+ .response
+ .parse_struct("Iatapay PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Iatapay
+{
+}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
+ for Iatapay
+{
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, 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::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}{}{}",
+ self.base_url(connectors),
+ "/payments/",
+ req.request.connector_transaction_id,
+ "/refund"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = iatapay::IatapayRefundRequest::try_from(req)?;
+ let iatapay_req =
+ Encode::<iatapay::IatapayRefundRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(iatapay_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::RefundExecuteType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ let response: iatapay::RefundResponse = res
+ .response
+ .parse_struct("iatapay RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Iatapay {
+ fn get_headers(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, 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::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}{}",
+ self.base_url(connectors),
+ "/refunds/",
+ match req.request.connector_refund_id.clone() {
+ Some(val) => val,
+ None => req.request.refund_id.clone(),
+ },
+ ))
+ }
+
+ 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: iatapay::RefundResponse = res
+ .response
+ .parse_struct("iatapay RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Iatapay {
+ fn get_webhook_source_verification_algorithm(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
+ Ok(Box::new(crypto::HmacSha256))
+ }
+
+ fn get_webhook_source_verification_signature(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let base64_signature = utils::get_header_key_value("Authorization", request.headers)?;
+ let base64_signature = base64_signature.replace("IATAPAY-HMAC-SHA256 ", "");
+ base64_decode(base64_signature)
+ }
+
+ fn get_webhook_source_verification_message(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ _merchant_id: &str,
+ _secret: &[u8],
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let message = std::str::from_utf8(request.body)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
+ Ok(message.to_string().into_bytes())
+ }
+
+ async fn get_webhook_source_verification_merchant_secret(
+ &self,
+ db: &dyn db::StorageInterface,
+ merchant_id: &str,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let key = format!("whsec_verification_{}_{}", self.id(), merchant_id);
+ let secret = db
+ .get_key(&key)
+ .await
+ .change_context(errors::ConnectorError::WebhookVerificationSecretNotFound)?;
+
+ Ok(secret)
+ }
+
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ let notif: IatapayPaymentsResponse =
+ request
+ .body
+ .parse_struct("IatapayPaymentsResponse")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+ if notif.iata_payment_id.is_some() {
+ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::ConnectorTransactionId(
+ notif.iata_payment_id.unwrap_or_default(),
+ ),
+ ))
+ } else {
+ Ok(api_models::webhooks::ObjectReferenceId::RefundId(
+ api_models::webhooks::RefundIdType::ConnectorRefundId(
+ notif.iata_refund_id.unwrap_or_default(),
+ ),
+ ))
+ }
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ let notif: IatapayPaymentsResponse =
+ request
+ .body
+ .parse_struct("IatapayPaymentsResponse")
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
+ match notif.status {
+ iatapay::IatapayPaymentStatus::Authorized => match notif.iata_payment_id.is_some() {
+ true => Ok(api::IncomingWebhookEvent::PaymentIntentSuccess),
+ false => Ok(api::IncomingWebhookEvent::RefundSuccess),
+ },
+ iatapay::IatapayPaymentStatus::Failed => match notif.iata_payment_id.is_some() {
+ true => Ok(api::IncomingWebhookEvent::PaymentIntentFailure),
+ false => Ok(api::IncomingWebhookEvent::RefundFailure),
+ },
+ _ => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ }
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {
+ let notif: IatapayPaymentsResponse =
+ request
+ .body
+ .parse_struct("IatapayPaymentsResponse")
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
+ Encode::<IatapayPaymentsResponse>::encode_to_value(&notif)
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
+ }
+}
diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
new file mode 100644
index 0000000000..f76da1c667
--- /dev/null
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -0,0 +1,349 @@
+use std::collections::HashMap;
+
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ connector::utils::{PaymentsAuthorizeRequestData, RefundsRequestData, RouterData},
+ core::errors,
+ services,
+ types::{self, api, storage::enums},
+};
+
+// Every access token will be valid for 5 minutes. It contains grant_type and scope for different type of access, but for our usecases it should be only 'client_credentials' and 'payment' resp(as per doc) for all type of api call.
+#[derive(Debug, Serialize)]
+pub struct IatapayAuthUpdateRequest {
+ grant_type: String,
+ scope: String,
+}
+impl TryFrom<&types::RefreshTokenRouterData> for IatapayAuthUpdateRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(_item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ grant_type: "client_credentials".to_string(),
+ scope: "payment".to_string(),
+ })
+ }
+}
+
+#[derive(Debug, Deserialize)]
+pub struct IatapayAuthUpdateResponse {
+ pub access_token: String,
+ pub token_type: String,
+ pub expires_in: i64,
+ pub scope: String,
+ pub jti: String,
+}
+
+impl<F, T> TryFrom<types::ResponseRouterData<F, IatapayAuthUpdateResponse, T, types::AccessToken>>
+ for types::RouterData<F, T, types::AccessToken>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, IatapayAuthUpdateResponse, T, types::AccessToken>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::AccessToken {
+ token: item.response.access_token,
+ expires: item.response.expires_in,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RedirectUrls {
+ success_url: String,
+ failure_url: String,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct IatapayPaymentsRequest {
+ merchant_id: String,
+ amount: i64,
+ currency: String,
+ country: String,
+ locale: String,
+ redirect_urls: RedirectUrls,
+ notification_url: String,
+}
+
+impl TryFrom<&types::PaymentsAuthorizeRouterData> for IatapayPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ let country = item.get_billing_country()?.to_string();
+ let return_url = item.get_return_url()?;
+ let payload = Self {
+ merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id,
+ amount: item.request.amount,
+ currency: item.request.currency.to_string(),
+ country: country.clone(),
+ locale: format!("en-{}", country),
+ redirect_urls: get_redirect_url(return_url),
+ notification_url: item.request.get_webhook_url()?,
+ };
+ Ok(payload)
+ }
+}
+
+fn get_redirect_url(return_url: String) -> RedirectUrls {
+ RedirectUrls {
+ success_url: return_url.clone(),
+ failure_url: return_url,
+ }
+}
+
+// Auth Struct
+pub struct IatapayAuthType {
+ pub(super) client_id: String,
+ pub(super) merchant_id: String,
+ pub(super) client_secret: String,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for IatapayAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::SignatureKey {
+ api_key,
+ key1,
+ api_secret,
+ } => Ok(Self {
+ client_id: api_key.to_string(),
+ merchant_id: key1.to_string(),
+ client_secret: api_secret.to_string(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
+ }
+ }
+}
+// PaymentsResponse
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum IatapayPaymentStatus {
+ #[default]
+ Created,
+ Initiated,
+ Authorized,
+ Settled,
+ Tobeinvestigated,
+ Blocked,
+ Cleared,
+ Failed,
+ Locked,
+ #[serde(rename = "UNEXPECTED SETTLED")]
+ UnexpectedSettled,
+}
+
+impl From<IatapayPaymentStatus> for enums::AttemptStatus {
+ fn from(item: IatapayPaymentStatus) -> Self {
+ match item {
+ IatapayPaymentStatus::Authorized | IatapayPaymentStatus::Settled => Self::Charged,
+ IatapayPaymentStatus::Failed | IatapayPaymentStatus::UnexpectedSettled => Self::Failure,
+ IatapayPaymentStatus::Created => Self::AuthenticationPending,
+ IatapayPaymentStatus::Initiated => Self::Pending,
+ _ => Self::Voided,
+ }
+ }
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct RedirectUrl {
+ pub redirect_url: String,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub struct CheckoutMethod {
+ pub redirect: RedirectUrl,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct IatapayPaymentsResponse {
+ pub status: IatapayPaymentStatus,
+ pub iata_payment_id: Option<String>,
+ pub iata_refund_id: Option<String>,
+ pub merchant_id: Option<String>,
+ pub merchant_payment_id: Option<String>,
+ pub amount: f64,
+ pub currency: String,
+ pub country: Option<String>,
+ pub locale: Option<String>,
+ pub bank_transfer_description: Option<String>,
+ pub checkout_methods: Option<CheckoutMethod>,
+ pub failure_code: Option<String>,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, IatapayPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, IatapayPaymentsResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let form_fields = HashMap::new();
+ let id = match item.response.iata_payment_id {
+ Some(s) => types::ResponseId::ConnectorTransactionId(s),
+ None => types::ResponseId::NoResponseId,
+ };
+ Ok(Self {
+ status: enums::AttemptStatus::from(item.response.status),
+ response: item.response.checkout_methods.map_or(
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: id.clone(),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ }),
+ |checkout_methods| {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: id,
+ redirection_data: Some(services::RedirectForm::Form {
+ endpoint: checkout_methods.redirect.redirect_url,
+ method: services::Method::Get,
+ form_fields,
+ }),
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ })
+ },
+ ),
+ ..item.data
+ })
+ }
+}
+
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct IatapayRefundRequest {
+ pub merchant_id: String,
+ pub merchant_refund_id: String,
+ pub amount: i64,
+ pub currency: String,
+ pub bank_transfer_description: Option<String>,
+ pub notification_url: String,
+}
+
+impl<F> TryFrom<&types::RefundsRouterData<F>> for IatapayRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.request.amount,
+ merchant_id: IatapayAuthType::try_from(&item.connector_auth_type)?.merchant_id,
+ merchant_refund_id: match item.request.connector_refund_id.clone() {
+ Some(val) => val,
+ None => item.request.refund_id.clone(),
+ },
+ currency: item.request.currency.to_string(),
+ bank_transfer_description: item.request.reason.clone(),
+ notification_url: item.request.get_webhook_url()?,
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum RefundStatus {
+ #[default]
+ Created,
+ Locked,
+ Initiated,
+ Authorized,
+ Settled,
+ Failed,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Created => Self::Pending,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Locked => Self::Pending,
+ RefundStatus::Initiated => Self::Pending,
+ RefundStatus::Authorized => Self::Pending,
+ RefundStatus::Settled => Self::Success,
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RefundResponse {
+ iata_refund_id: String,
+ status: RefundStatus,
+ merchant_refund_id: String,
+ amount: f64,
+ currency: String,
+ bank_transfer_description: Option<String>,
+ failure_code: Option<String>,
+ failure_details: Option<String>,
+ lock_reason: Option<String>,
+ creation_date_time: Option<String>,
+ finish_date_time: Option<String>,
+ update_date_time: Option<String>,
+ clearance_date_time: Option<String>,
+ iata_payment_id: Option<String>,
+ merchant_payment_id: Option<String>,
+ payment_amount: Option<f64>,
+ merchant_id: Option<String>,
+ account_country: Option<String>,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.iata_refund_id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.iata_refund_id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Deserialize)]
+pub struct IatapayErrorResponse {
+ pub status: u16,
+ pub error: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
+
+#[derive(Deserialize, Debug)]
+pub struct IatapayAccessTokenErrorResponse {
+ pub error: String,
+ pub error_description: String,
+}
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 63776c39bb..278dd44a76 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -307,6 +307,7 @@ impl PaymentsCancelRequestData for PaymentsCancelData {
pub trait RefundsRequestData {
fn get_connector_refund_id(&self) -> Result<String, Error>;
+ fn get_webhook_url(&self) -> Result<String, Error>;
}
impl RefundsRequestData for types::RefundsData {
@@ -317,6 +318,11 @@ impl RefundsRequestData for types::RefundsData {
.get_required_value("connector_refund_id")
.change_context(errors::ConnectorError::MissingConnectorTransactionID)
}
+ fn get_webhook_url(&self) -> Result<String, Error> {
+ self.webhook_url
+ .clone()
+ .ok_or_else(missing_field_err("webhook_url"))
+ }
}
static CARD_REGEX: Lazy<HashMap<CardIssuer, Result<Regex, regex::Error>>> = Lazy::new(|| {
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index a03a5372de..278a1dd24e 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -114,6 +114,7 @@ default_imp_for_complete_authorize!(
connector::Dlocal,
connector::Fiserv,
connector::Forte,
+ connector::Iatapay,
connector::Klarna,
connector::Multisafepay,
connector::Nexinets,
@@ -160,6 +161,7 @@ default_imp_for_create_customer!(
connector::Fiserv,
connector::Forte,
connector::Globalpay,
+ connector::Iatapay,
connector::Klarna,
connector::Mollie,
connector::Multisafepay,
@@ -207,6 +209,7 @@ default_imp_for_connector_redirect_response!(
connector::Dlocal,
connector::Fiserv,
connector::Forte,
+ connector::Iatapay,
connector::Klarna,
connector::Multisafepay,
connector::Nexinets,
@@ -245,6 +248,7 @@ default_imp_for_connector_request_id!(
connector::Fiserv,
connector::Forte,
connector::Globalpay,
+ connector::Iatapay,
connector::Klarna,
connector::Mollie,
connector::Multisafepay,
@@ -294,6 +298,7 @@ default_imp_for_accept_dispute!(
connector::Fiserv,
connector::Forte,
connector::Globalpay,
+ connector::Iatapay,
connector::Klarna,
connector::Mollie,
connector::Multisafepay,
@@ -353,6 +358,7 @@ default_imp_for_file_upload!(
connector::Fiserv,
connector::Forte,
connector::Globalpay,
+ connector::Iatapay,
connector::Klarna,
connector::Mollie,
connector::Multisafepay,
@@ -402,6 +408,7 @@ default_imp_for_submit_evidence!(
connector::Fiserv,
connector::Forte,
connector::Globalpay,
+ connector::Iatapay,
connector::Klarna,
connector::Mollie,
connector::Multisafepay,
@@ -451,6 +458,7 @@ default_imp_for_defend_dispute!(
connector::Fiserv,
connector::Forte,
connector::Globalpay,
+ connector::Iatapay,
connector::Klarna,
connector::Mollie,
connector::Multisafepay,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 8546c3749a..8741ac0ca5 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -380,12 +380,12 @@ pub fn create_redirect_url(
pub fn create_webhook_url(
router_base_url: &String,
- payment_attempt: &storage::PaymentAttempt,
+ merchant_id: &String,
connector_name: &String,
) -> String {
format!(
"{}/webhooks/{}/{}",
- router_base_url, payment_attempt.merchant_id, connector_name
+ router_base_url, merchant_id, connector_name
)
}
pub fn create_complete_authorize_url(
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index d1a13816f0..0b9198001a 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -533,7 +533,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
));
let webhook_url = Some(helpers::create_webhook_url(
router_base_url,
- attempt,
+ &attempt.merchant_id,
connector_name,
));
let router_return_url = Some(helpers::create_redirect_url(
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 5b5f6e8ba2..c409373496 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -58,6 +58,12 @@ pub async fn construct_refund_router_data<'a, F>(
.payment_method
.get_required_value("payment_method_type")?;
+ let webhook_url = Some(helpers::create_webhook_url(
+ &state.conf.server.base_url.clone(),
+ &merchant_account.merchant_id,
+ &connector_id.to_string(),
+ ));
+
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_account.merchant_id.clone(),
@@ -82,6 +88,7 @@ pub async fn construct_refund_router_data<'a, F>(
refund_amount: refund.refund_amount,
currency,
amount,
+ webhook_url,
connector_metadata: payment_attempt.connector_metadata.clone(),
reason: refund.refund_reason.clone(),
connector_refund_id: refund.connector_refund_id.clone(),
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index aa01bf5ba7..93843f326f 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -407,6 +407,7 @@ pub struct RefundsData {
/// Amount for the payment against which this refund is issued
pub amount: i64,
pub reason: Option<String>,
+ pub webhook_url: Option<String>,
/// Amount to be refunded
pub refund_amount: i64,
/// Arbitrary metadata required for refund
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 790c600cd3..7af5f62429 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -214,6 +214,7 @@ impl ConnectorData {
"fiserv" => Ok(Box::new(&connector::Fiserv)),
"forte" => Ok(Box::new(&connector::Forte)),
"globalpay" => Ok(Box::new(&connector::Globalpay)),
+ "iatapay" => Ok(Box::new(&connector::Iatapay)),
"klarna" => Ok(Box::new(&connector::Klarna)),
"mollie" => Ok(Box::new(&connector::Mollie)),
"nuvei" => Ok(Box::new(&connector::Nuvei)),
diff --git a/crates/router/src/types/api/webhooks.rs b/crates/router/src/types/api/webhooks.rs
index 3fc8df5e17..7cfc61bdf5 100644
--- a/crates/router/src/types/api/webhooks.rs
+++ b/crates/router/src/types/api/webhooks.rs
@@ -115,7 +115,6 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
let message = self
.get_webhook_source_verification_message(request, merchant_id, &secret)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
-
algorithm
.verify_signature(&secret, &signature, &message)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index b347809668..6965681fd5 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -161,6 +161,7 @@ impl ForeignTryFrom<api_enums::IntentStatus> for storage_enums::EventType {
fn foreign_try_from(value: api_enums::IntentStatus) -> Result<Self, Self::Error> {
match value {
api_enums::IntentStatus::Succeeded => Ok(Self::PaymentSucceeded),
+ api_enums::IntentStatus::Failed => Ok(Self::PaymentFailed),
api_enums::IntentStatus::Processing => Ok(Self::PaymentProcessing),
api_enums::IntentStatus::RequiresMerchantAction => Ok(Self::ActionRequired),
_ => Err(errors::ValidationError::IncorrectValueProvided {
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 486ef680f3..74e9befb6a 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -101,6 +101,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
refund_id: uuid::Uuid::new_v4().to_string(),
connector_transaction_id: String::new(),
refund_amount: 100,
+ webhook_url: None,
connector_metadata: None,
reason: None,
connector_refund_id: None,
diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs
index cf3b16d02a..f209d1bdec 100644
--- a/crates/router/tests/connectors/authorizedotnet.rs
+++ b/crates/router/tests/connectors/authorizedotnet.rs
@@ -101,6 +101,7 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
refund_id: uuid::Uuid::new_v4().to_string(),
connector_transaction_id: String::new(),
refund_amount: 1,
+ webhook_url: None,
connector_metadata: None,
reason: None,
connector_refund_id: None,
diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs
index 848dc9c22a..0613f1a84a 100644
--- a/crates/router/tests/connectors/connector_auth.rs
+++ b/crates/router/tests/connectors/connector_auth.rs
@@ -20,6 +20,7 @@ pub(crate) struct ConnectorAuthentication {
pub fiserv: Option<SignatureKey>,
pub forte: Option<MultiAuthKey>,
pub globalpay: Option<HeaderKey>,
+ pub iatapay: Option<SignatureKey>,
pub mollie: Option<HeaderKey>,
pub multisafepay: Option<HeaderKey>,
pub nexinets: Option<BodyKey>,
diff --git a/crates/router/tests/connectors/dlocal.rs b/crates/router/tests/connectors/dlocal.rs
index d323c72aa3..d58e2b6ea6 100644
--- a/crates/router/tests/connectors/dlocal.rs
+++ b/crates/router/tests/connectors/dlocal.rs
@@ -438,6 +438,7 @@ pub fn get_payment_info() -> PaymentInfo {
auth_type: None,
access_token: None,
connector_meta_data: None,
+ ..Default::default()
}
}
// Connector dependent test cases goes here
diff --git a/crates/router/tests/connectors/iatapay.rs b/crates/router/tests/connectors/iatapay.rs
new file mode 100644
index 0000000000..8d318a4fa5
--- /dev/null
+++ b/crates/router/tests/connectors/iatapay.rs
@@ -0,0 +1,181 @@
+use masking::Secret;
+use router::types::{self, api, storage::enums, AccessToken, PaymentAddress};
+
+use crate::{
+ connector_auth,
+ utils::{
+ self, get_connector_transaction_id, Connector, ConnectorActions, PaymentAuthorizeType,
+ },
+};
+
+#[derive(Clone, Copy)]
+struct IatapayTest;
+impl ConnectorActions for IatapayTest {}
+impl Connector for IatapayTest {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Iatapay;
+ types::api::ConnectorData {
+ connector: Box::new(&Iatapay),
+ connector_name: types::Connector::Iatapay,
+ get_token: types::api::GetToken::Connector,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ types::ConnectorAuthType::from(
+ connector_auth::ConnectorAuthentication::new()
+ .iatapay
+ .expect("Missing connector authentication configuration"),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "iatapay".to_string()
+ }
+}
+
+fn get_access_token() -> Option<AccessToken> {
+ let connector = IatapayTest {};
+ match connector.get_auth_token() {
+ types::ConnectorAuthType::SignatureKey {
+ api_key,
+ key1: _,
+ api_secret: _,
+ } => Some(AccessToken {
+ token: api_key,
+ expires: 60 * 5,
+ }),
+ _ => None,
+ }
+}
+
+static CONNECTOR: IatapayTest = IatapayTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ Some(utils::PaymentInfo {
+ address: Some(PaymentAddress {
+ billing: Some(api::Address {
+ address: Some(api::AddressDetails {
+ first_name: Some(Secret::new("first".to_string())),
+ last_name: Some(Secret::new("last".to_string())),
+ line1: Some(Secret::new("line1".to_string())),
+ line2: Some(Secret::new("line2".to_string())),
+ city: Some("city".to_string()),
+ zip: Some(Secret::new("zip".to_string())),
+ country: Some(api_models::enums::CountryAlpha2::NL),
+ ..Default::default()
+ }),
+ phone: Some(api::PhoneDetails {
+ number: Some(Secret::new("1234567890".to_string())),
+ country_code: Some("+91".to_string()),
+ }),
+ }),
+ ..Default::default()
+ }),
+ access_token: get_access_token(),
+ return_url: Some(String::from("https://hyperswitch.io")),
+ ..Default::default()
+ })
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ Some(types::PaymentsAuthorizeData {
+ router_return_url: Some("https://hyperswitch.io".to_string()),
+ webhook_url: Some("https://hyperswitch.io".to_string()),
+ currency: enums::Currency::EUR,
+ ..PaymentAuthorizeType::default().0
+ })
+}
+
+// Cards Positive Tests
+
+// Creates a payment checking if its status is "requires_customer_action" for redirectinal flow
+#[actix_web::test]
+async fn should_only_create_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::AuthenticationPending);
+}
+
+//refund on an unsuccessed payments
+#[actix_web::test]
+async fn should_fail_for_refund_on_unsuccessed_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let refund_response = CONNECTOR
+ .refund_payment(
+ get_connector_transaction_id(response.response).unwrap(),
+ Some(types::RefundsData {
+ refund_amount: response.request.amount,
+ webhook_url: Some("https://hyperswitch.io".to_string()),
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap_err().code,
+ "BAD_REQUEST".to_string(),
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .refund_payment(
+ "PWGKCZ91M4JJ0".to_string(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ webhook_url: Some("https://hyperswitch.io".to_string()),
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "The amount to be refunded (100) is greater than the unrefunded amount (10.00): the amount of the payment is 10.00 and the refunded amount is 0.00",
+ );
+}
+
+#[actix_web::test]
+async fn should_sync_payment() {
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ "PE9OTYNP639XW".to_string(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+#[actix_web::test]
+async fn should_sync_refund() {
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ "R5DNXUW4EY6PQ".to_string(),
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 68efe80dc3..766a67029b 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -22,6 +22,7 @@ mod dummyconnector;
mod fiserv;
mod forte;
mod globalpay;
+mod iatapay;
mod mollie;
mod multisafepay;
mod nexinets;
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 36187d09cd..262ab819dd 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -97,5 +97,10 @@ api_key = "api_key"
key1 = "key1"
api_secret = "secret"
+[iatapay]
+key1 = "key1"
+api_key = "api_key"
+api_secret = "secrect"
+
[dummyconnector]
api_key="API Key"
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 678bd2468f..fe9c7163ad 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -32,6 +32,7 @@ pub struct PaymentInfo {
pub auth_type: Option<enums::AuthenticationType>,
pub access_token: Option<AccessToken>,
pub connector_meta_data: Option<serde_json::Value>,
+ pub return_url: Option<String>,
}
#[async_trait]
@@ -318,6 +319,7 @@ pub trait ConnectorActions: Connector {
currency: enums::Currency::USD,
refund_id: uuid::Uuid::new_v4().to_string(),
connector_transaction_id: "".to_string(),
+ webhook_url: None,
refund_amount: 100,
connector_metadata: None,
reason: None,
@@ -378,7 +380,7 @@ pub trait ConnectorActions: Connector {
payment_method: enums::PaymentMethod::Card,
connector_auth_type: self.get_auth_token(),
description: Some("This is a test".to_string()),
- return_url: None,
+ return_url: info.clone().and_then(|a| a.return_url),
request: req,
response: Err(types::ErrorResponse::default()),
payment_method_id: None,
@@ -577,6 +579,7 @@ impl Default for PaymentRefundType {
refund_id: uuid::Uuid::new_v4().to_string(),
connector_transaction_id: String::new(),
refund_amount: 100,
+ webhook_url: None,
connector_metadata: None,
reason: Some("Customer returned product".to_string()),
connector_refund_id: None,
diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs
index fea5949a43..1214227fa8 100644
--- a/crates/storage_models/src/enums.rs
+++ b/crates/storage_models/src/enums.rs
@@ -319,6 +319,7 @@ pub enum EventObjectType {
#[strum(serialize_all = "snake_case")]
pub enum EventType {
PaymentSucceeded,
+ PaymentFailed,
PaymentProcessing,
ActionRequired,
RefundSucceeded,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index b4055c37b0..86571a26b5 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -73,6 +73,7 @@ dummyconnector.base_url = "http://localhost:8080/dummy-connector"
fiserv.base_url = "https://cert.api.fiservapps.com/"
forte.base_url = "https://sandbox.forte.net/api/v3"
globalpay.base_url = "https://apis.sandbox.globalpay.com/ucp/"
+iatapay.base_url = "https://sandbox.iata-pay.iata.org/api/v1"
klarna.base_url = "https://api-na.playground.klarna.com/"
mollie.base_url = "https://api.mollie.com/v2/"
multisafepay.base_url = "https://testapi.multisafepay.com/"
@@ -110,6 +111,7 @@ cards = [
"fiserv",
"forte",
"globalpay",
+ "iatapay",
"mollie",
"multisafepay",
"nexinets",
diff --git a/migrations/2023-04-27-120010_add_payment_failed_event_type/down.sql b/migrations/2023-04-27-120010_add_payment_failed_event_type/down.sql
new file mode 100644
index 0000000000..7f3bd8175c
--- /dev/null
+++ b/migrations/2023-04-27-120010_add_payment_failed_event_type/down.sql
@@ -0,0 +1,5 @@
+DELETE FROM pg_enum
+WHERE enumlabel = 'payment_failed'
+AND enumtypid = (
+ SELECT oid FROM pg_type WHERE typname = 'EventType'
+);
\ No newline at end of file
diff --git a/migrations/2023-04-27-120010_add_payment_failed_event_type/up.sql b/migrations/2023-04-27-120010_add_payment_failed_event_type/up.sql
new file mode 100644
index 0000000000..2a977d18a5
--- /dev/null
+++ b/migrations/2023-04-27-120010_add_payment_failed_event_type/up.sql
@@ -0,0 +1 @@
+ALTER TYPE "EventType" ADD VALUE IF NOT EXISTS 'payment_failed';
\ No newline at end of file
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 5f3c23f30f..261513e128 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -4,7 +4,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# add new connector to existing list and sort it
- connectors=(aci adyen airwallex applepay authorizedotnet bambora bluesnap braintree checkout coinbase cybersource dlocal dummyconnector fiserv forte globalpay klarna mollie multisafepay nexinets nuvei opennode payeezy paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1")
+ connectors=(aci adyen airwallex applepay authorizedotnet bambora bluesnap braintree checkout coinbase cybersource dlocal dummyconnector fiserv forte globalpay iatapay klarna mollie multisafepay nexinets nuvei opennode payeezy paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp