text
string
file_path
string
module
string
type
string
tokens
int64
language
string
struct_name
string
type_name
string
trait_name
string
impl_type
string
function_name
string
source
string
section
string
keys
list
macro_type
string
url
string
title
string
chunk_index
int64
impl DatabaseStore for Store { type Config = Database; async fn new( config: Database, tenant_config: &dyn TenantConfig, test_transaction: bool, ) -> StorageResult<Self> { Ok(Self { master_pool: diesel_make_pg_pool(&config, tenant_config.get_schema(), test_transaction) .await?, accounts_pool: diesel_make_pg_pool( &config, tenant_config.get_accounts_schema(), test_transaction, ) .await?, }) } fn get_master_pool(&self) -> &PgPool { &self.master_pool } fn get_replica_pool(&self) -> &PgPool { &self.master_pool } fn get_accounts_master_pool(&self) -> &PgPool { &self.accounts_pool } fn get_accounts_replica_pool(&self) -> &PgPool { &self.accounts_pool } }
crates/storage_impl/src/database/store.rs
storage_impl
impl_block
195
rust
null
Store
DatabaseStore for
impl DatabaseStore for for Store
null
null
null
null
null
null
null
null
pub async fn delete_from_stream( &self, stream_name: &str, entry_id: &str, ) -> errors::DrainerResult<()> { let (_trim_result, execution_time) = common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async { self.redis_conn .stream_delete_entries(&stream_name.into(), entry_id) .await .map_err(errors::DrainerError::from)?; Ok(()) }) .await; metrics::REDIS_STREAM_DEL_TIME.record( execution_time, router_env::metric_attributes!(("stream", stream_name.to_owned())), ); Ok(()) }
crates/drainer/src/stream.rs
drainer
function_signature
146
rust
null
null
null
null
delete_from_stream
null
null
null
null
null
null
null
File: crates/router/tests/connectors/digitalvirgo.rs use masking::Secret; use router::{ types::{self, api, storage::enums, }}; use crate::utils::{self, ConnectorActions}; use test_utils::connector_auth; #[derive(Clone, Copy)] struct DigitalvirgoTest; impl ConnectorActions for DigitalvirgoTest {} impl utils::Connector for DigitalvirgoTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Digitalvirgo; api::ConnectorData { connector: Box::new(Digitalvirgo::new()), connector_name: types::Connector::Digitalvirgo, get_token: types::api::GetToken::Connector, merchant_connector_id: None, } } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .digitalvirgo .expect("Missing connector authentication configuration").into(), ) } fn get_name(&self) -> String { "digitalvirgo".to_string() } } static CONNECTOR: DigitalvirgoTest = DigitalvirgoTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::api::PaymentMethodData::Card(api::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: api::PaymentMethodData::Card(api::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .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." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // 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 .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
crates/router/tests/connectors/digitalvirgo.rs
router
full_file
2,910
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::locker_id.eq(locker_id.to_owned()), ) .await }
crates/diesel_models/src/query/payment_method.rs
diesel_models
function_signature
70
rust
null
null
null
null
find_by_locker_id
null
null
null
null
null
null
null
impl api::UasAuthenticationConfirmation for Juspaythreedsserver {}
crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs
hyperswitch_connectors
impl_block
16
rust
null
Juspaythreedsserver
api::UasAuthenticationConfirmation for
impl api::UasAuthenticationConfirmation for for Juspaythreedsserver
null
null
null
null
null
null
null
null
pub fn new() -> &'static Self { &Self { amount_converter: &FloatMajorUnitForConnector, } }
crates/hyperswitch_connectors/src/connectors/getnet.rs
hyperswitch_connectors
function_signature
28
rust
null
null
null
null
new
null
null
null
null
null
null
null
impl api::PaymentToken for Hyperwallet {}
crates/hyperswitch_connectors/src/connectors/hyperwallet.rs
hyperswitch_connectors
impl_block
9
rust
null
Hyperwallet
api::PaymentToken for
impl api::PaymentToken for for Hyperwallet
null
null
null
null
null
null
null
null
impl AuthenticationEligibilityRequest { pub fn get_next_action_api( &self, base_url: String, authentication_id: String, ) -> CustomResult<NextAction, errors::ParsingError> { let url = format!("{base_url}/authentication/{authentication_id}/authenticate"); Ok(NextAction { url: url::Url::parse(&url).change_context(errors::ParsingError::UrlParsingError)?, http_method: common_utils::request::Method::Post, }) } pub fn get_billing_address(&self) -> Option<Address> { self.billing.clone() } pub fn get_shipping_address(&self) -> Option<Address> { self.shipping.clone() } pub fn get_browser_information(&self) -> Option<BrowserInformation> { self.browser_information.clone() } }
crates/api_models/src/authentication.rs
api_models
impl_block
177
rust
null
AuthenticationEligibilityRequest
null
impl AuthenticationEligibilityRequest
null
null
null
null
null
null
null
null
pub struct MessagesResponseData { version: VersionResponseData, }
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
hyperswitch_connectors
struct_definition
14
rust
MessagesResponseData
null
null
null
null
null
null
null
null
null
null
null
pub struct VgsErrorResponse { pub errors: Vec<VgsErrorItem>, pub trace_id: String, }
crates/hyperswitch_connectors/src/connectors/vgs/transformers.rs
hyperswitch_connectors
struct_definition
24
rust
VgsErrorResponse
null
null
null
null
null
null
null
null
null
null
null
pub fn get_id(&self) -> &str { &self.attempt_id }
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
function_signature
20
rust
null
null
null
null
get_id
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs Public functions: 1 Public structs: 1 pub mod transformers; use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId}; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session, SetupMandate, Void, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors::ConnectorError, events::connector_api_logs::ConnectorEvent, types::{ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType, RefundSyncType, Response, }, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use masking::{ExposeInterface, Mask as _, Maskable}; use self::transformers as wellsfargopayout; use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount}; #[derive(Clone)] pub struct Wellsfargopayout { amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), } impl Wellsfargopayout { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } } impl api::Payment for Wellsfargopayout {} impl api::PaymentSession for Wellsfargopayout {} impl api::ConnectorAccessToken for Wellsfargopayout {} impl api::MandateSetup for Wellsfargopayout {} impl api::PaymentAuthorize for Wellsfargopayout {} impl api::PaymentSync for Wellsfargopayout {} impl api::PaymentCapture for Wellsfargopayout {} impl api::PaymentVoid for Wellsfargopayout {} impl api::Refund for Wellsfargopayout {} impl api::RefundExecute for Wellsfargopayout {} impl api::RefundSync for Wellsfargopayout {} impl api::PaymentToken for Wellsfargopayout {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Wellsfargopayout { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wellsfargopayout where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let mut header = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; let mut api_key = self.get_auth_header(&req.connector_auth_type)?; header.append(&mut api_key); Ok(header) } } impl ConnectorCommon for Wellsfargopayout { fn id(&self) -> &'static str { "wellsfargopayout" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Minor // todo!() // TODO! Check connector documentation, on which unit they are processing the currency. // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor, // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.wellsfargopayout.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { let auth = wellsfargopayout::WellsfargopayoutAuthType::try_from(auth_type) .change_context(ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::AUTHORIZATION.to_string(), auth.api_key.expose().into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutErrorResponse = res .response .parse_struct("WellsfargopayoutErrorResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); Ok(ErrorResponse { status_code: res.status_code, code: response.code, message: response.message, reason: response.reason, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } } impl ConnectorValidation for Wellsfargopayout { //TODO: implement functions when support enabled } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Wellsfargopayout { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Wellsfargopayout { } impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Wellsfargopayout { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = wellsfargopayout::WellsfargopayoutRouterData::from((amount, req)); let connector_req = wellsfargopayout::WellsfargopayoutPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?) .set_body(PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("Wellsfargopayout PaymentsAuthorizeResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("wellsfargopayout PaymentsSyncResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { Err(ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, ConnectorError> { let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res .response .parse_struct("Wellsfargopayout PaymentsCaptureResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wellsfargopayout {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, ConnectorError> { let refund_amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = wellsfargopayout::WellsfargopayoutRouterData::from((refund_amount, req)); let connector_req = wellsfargopayout::WellsfargopayoutRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, ConnectorError> { let response: wellsfargopayout::RefundResponse = res .response .parse_struct("wellsfargopayout RefundResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Wellsfargopayout { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<String, ConnectorError> { Err(ConnectorError::NotImplemented("get_url method".to_string()).into()) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(RefundSyncType::get_headers(self, req, connectors)?) .set_body(RefundSyncType::get_request_body(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, ConnectorError> { let response: wellsfargopayout::RefundResponse = res .response .parse_struct("wellsfargopayout RefundSyncResponse") .change_context(ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl IncomingWebhook for Wellsfargopayout { fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<ObjectReferenceId, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { Err(report!(ConnectorError::WebhooksNotImplemented)) } } static WELLSFARGOPAYOUTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Wellsfargo Payout", description: "Wells Fargo Payouts streamlines secure domestic and international payments for businesses via online banking, supporting Bill Pay, Digital Wires, and Zelle", connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor, integration_status: common_enums::ConnectorIntegrationStatus::Sandbox, }; impl ConnectorSpecifications for Wellsfargopayout { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&WELLSFARGOPAYOUTS_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { None } fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> { None } }
crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs
hyperswitch_connectors
full_file
4,607
null
null
null
null
null
null
null
null
null
null
null
null
null
impl NuveiPaymentsGenericResponse for CompleteAuthorize {}
crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs
hyperswitch_connectors
impl_block
11
rust
null
CompleteAuthorize
NuveiPaymentsGenericResponse for
impl NuveiPaymentsGenericResponse for for CompleteAuthorize
null
null
null
null
null
null
null
null
impl ConnectorEvent { /// fn new ConnectorEvent #[allow(clippy::too_many_arguments)] pub fn new( tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: &str, request: serde_json::Value, url: String, method: Method, payment_id: String, merchant_id: common_utils::id_type::MerchantId, request_id: Option<&RequestId>, latency: u128, refund_id: Option<String>, dispute_id: Option<String>, status_code: u16, ) -> Self { Self { tenant_id, connector_name, flow: flow .rsplit_once("::") .map(|(_, s)| s) .unwrap_or(flow) .to_string(), request: request.to_string(), masked_response: None, error: None, url, method: method.to_string(), payment_id, merchant_id, created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, request_id: request_id .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), latency, refund_id, dispute_id, status_code, } } /// fn set_response_body pub fn set_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.masked_response = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error_response_body pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { match masking::masked_serialize(response) { Ok(masked) => { self.error = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error pub fn set_error(&mut self, error: serde_json::Value) { self.error = Some(error.to_string()); } }
crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
hyperswitch_interfaces
impl_block
483
rust
null
ConnectorEvent
null
impl ConnectorEvent
null
null
null
null
null
null
null
null
impl api::RefundExecute for Payload {}
crates/hyperswitch_connectors/src/connectors/payload.rs
hyperswitch_connectors
impl_block
9
rust
null
Payload
api::RefundExecute for
impl api::RefundExecute for for Payload
null
null
null
null
null
null
null
null
pub struct Getnet { amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), }
crates/hyperswitch_connectors/src/connectors/getnet.rs
hyperswitch_connectors
struct_definition
27
rust
Getnet
null
null
null
null
null
null
null
null
null
null
null
impl api::PaymentAuthorize for Cybersource {}
crates/hyperswitch_connectors/src/connectors/cybersource.rs
hyperswitch_connectors
impl_block
10
rust
null
Cybersource
api::PaymentAuthorize for
impl api::PaymentAuthorize for for Cybersource
null
null
null
null
null
null
null
null
pub async fn upsert_decision_manager_config( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<api_models::conditional_configs::DecisionManagerRequest>, ) -> impl Responder { let flow = Flow::DecisionManagerUpsertConfig; Box::pin(oss_api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: auth::AuthenticationData, update_decision, _| { conditional_config::upsert_conditional_config( state, auth.key_store, update_decision, auth.profile, ) }, #[cfg(not(feature = "release"))] auth::auth_type( &auth::V2ApiKeyAuth { is_connected_allowed: false, is_platform_allowed: false, }, &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, req.headers(), ), #[cfg(feature = "release")] &auth::JWTAuth { permission: Permission::ProfileThreeDsDecisionManagerWrite, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/routing.rs
router
function_signature
248
rust
null
null
null
null
upsert_decision_manager_config
null
null
null
null
null
null
null
pub struct FeesType { #[serde(rename = "type")] pub fees_type: String, pub fees: FloatMajorUnit, pub currency_code: Currency, }
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
hyperswitch_connectors
struct_definition
36
rust
FeesType
null
null
null
null
null
null
null
null
null
null
null
pub async fn populate_bin_details_for_payment_method_create( _card_details: api_models::payment_methods::CardDetail, _db: &dyn state::PaymentMethodsStorageInterface, ) -> api_models::payment_methods::CardDetail { todo!() }
crates/payment_methods/src/helpers.rs
payment_methods
function_signature
54
rust
null
null
null
null
populate_bin_details_for_payment_method_create
null
null
null
null
null
null
null
pub fn parse_routing_algorithm( value: Option<pii::SecretSerdeValue>, ) -> Result<Option<Self>, error_stack::Report<ParsingError>> { value .map(|val| val.parse_value::<Self>("RoutingAlgorithmRef")) .transpose() }
crates/api_models/src/routing.rs
api_models
function_signature
59
rust
null
null
null
null
parse_routing_algorithm
null
null
null
null
null
null
null
pub struct TransferKeyResponse { /// The identifier for the Merchant Account #[schema(example = 32)] pub total_transferred: usize, }
crates/api_models/src/admin.rs
api_models
struct_definition
33
rust
TransferKeyResponse
null
null
null
null
null
null
null
null
null
null
null
impl PaymentMethodNew { pub fn update_storage_scheme(&mut self, storage_scheme: MerchantStorageScheme) { self.updated_by = Some(storage_scheme.to_string()); } #[cfg(feature = "v1")] pub fn get_id(&self) -> &String { &self.payment_method_id } #[cfg(feature = "v2")] pub fn get_id(&self) -> &common_utils::id_type::GlobalPaymentMethodId { &self.id } }
crates/diesel_models/src/payment_method.rs
diesel_models
impl_block
104
rust
null
PaymentMethodNew
null
impl PaymentMethodNew
null
null
null
null
null
null
null
null
pub fn get_year(&self) -> &CardExpirationYear { &self.year }
crates/cards/src/lib.rs
cards
function_signature
20
rust
null
null
null
null
get_year
null
null
null
null
null
null
null
pub async fn delete_card_from_hs_locker_by_global_id<'a>( state: &routes::SessionState, id: &str, merchant_id: &id_type::MerchantId, card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp> { todo!() }
crates/router/src/core/payment_methods/cards.rs
router
function_signature
69
rust
null
null
null
null
delete_card_from_hs_locker_by_global_id
null
null
null
null
null
null
null
pub struct CeleroRefundResponse { pub status: CeleroResponseStatus, pub msg: String, pub data: Option<serde_json::Value>, // Usually null for refund responses }
crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
hyperswitch_connectors
struct_definition
41
rust
CeleroRefundResponse
null
null
null
null
null
null
null
null
null
null
null
Web Documentation: For B2B SaaS Businesses | Hyperswitch # Type: Web Doc Hyperswitch empowers B2B SaaS providers with a modular, flexible, and robust payment infrastructure designed for both their clients and end users. For B2B SaaS businesses, it is particularly valuable for onboarding large enterprises as clients who prefer to retain greater control over their customers' checkout experience. Seamless client onboarding Composable payment workflow Modular card vaulting options Global payment support with no code connector integrations Fully managed compliance and security Seamless client onboarding Simplify client onboarding to just a few clicks, with enhanced control at both the platform and client levels. Setup multiple accounts and profiles Invite your clients to configure PSPs Composable payment workflows Enable flexible workflows for direct client payments, customer acquisition payments with clients, and platform-managed end-to-end payment processing. Supported custom payment flows Modular card vaulting options Fulfill diverse client needs with customizable card vaulting options, including platform-level (unified), PSP-specific, and client-scoped vaulting. Card vaulting and tokenisation Global payment support with no code connector integrations Reduce weeks or even months of development on payment connector integrations and support for various payment methods with Hyperswitch’s no-code solution. List of 70+ supported connectors and 150+ payment methods How to configure a connector in few clicks Fully managed compliance and security Enjoy hassle-free compliance with evolving regulatory standards, maintaining top-notch security without added complexity. Compliance and data security Data privacy PCI compliance For E-Commerce Businesses 11 months ago Was this helpful?
https://docs.hyperswitch.io/use-cases/for-b2b-saas-businesses
null
web_doc_file
352
doc
null
null
null
null
null
web
null
null
null
https://docs.hyperswitch.io/use-cases/for-b2b-saas-businesses
For B2B SaaS Businesses | Hyperswitch
null
pub fn get_challenge_request(&self) -> Option<String> { if let Self::Challenge(challenge_params) = self { challenge_params.challenge_request.clone() } else { None } }
crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
hyperswitch_domain_models
function_signature
45
rust
null
null
null
null
get_challenge_request
null
null
null
null
null
null
null
/// Build profile, either debug or release. /// /// Example: `release`. #[macro_export] macro_rules! profile { () => { env!("CARGO_PROFILE") }; }
crates/router_env/src/env.rs
router_env
macro
40
rust
null
null
null
null
null
null
null
null
declarative
null
null
null
File: crates/router/tests/connectors/bankofamerica.rs use masking::Secret; use router::types::{self, domain, storage::enums}; use test_utils::connector_auth; use crate::utils::{self, ConnectorActions}; #[derive(Clone, Copy)] struct BankofamericaTest; impl ConnectorActions for BankofamericaTest {} impl utils::Connector for BankofamericaTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Bankofamerica; utils::construct_connector_data_old( Box::new(Bankofamerica::new()), // Remove `dummy_connector` feature gate from module in `main.rs` when updating this to use actual connector variant types::Connector::DummyConnector1, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .bankofamerica .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "bankofamerica".to_string() } } static CONNECTOR: BankofamericaTest = BankofamericaTest {}; fn get_default_payment_info() -> Option<utils::PaymentInfo> { None } fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { None } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info()) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( payment_method_details(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), get_default_payment_info(), ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(payment_method_details(), get_default_payment_info()) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), get_default_payment_info(), ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( payment_method_details(), Some(types::PaymentsCancelData { connector_transaction_id: String::from(""), cancellation_reason: Some("requested_by_customer".to_string()), ..Default::default() }), get_default_payment_info(), ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_manually_captured_refund() { let refund_response = CONNECTOR .capture_payment_and_refund( payment_method_details(), None, None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), capture_method: Some(enums::CaptureMethod::Automatic), ..Default::default() }), get_default_payment_info(), ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates multiple refunds against a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_succeeded_payment_multiple_times() { CONNECTOR .make_payment_and_multiple_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await; } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund(payment_method_details(), None, get_default_payment_info()) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's security code is invalid.".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration month is invalid.".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Your card's expiration year is invalid.".to_string(), ); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(payment_method_details(), get_default_payment_info()) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .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." ); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, get_default_payment_info()) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("No such payment_intent: '123456789'") ); } // 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 .make_payment_and_refund( payment_method_details(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Refund amount (₹1.50) is greater than charge amount (₹1.00)", ); } // Connector dependent test cases goes here // [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
crates/router/tests/connectors/bankofamerica.rs
router
full_file
2,972
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct LockerMockUpNew { pub card_id: String, pub external_id: String, pub card_fingerprint: String, pub card_global_fingerprint: String, pub merchant_id: common_utils::id_type::MerchantId, pub card_number: String, pub card_exp_year: String, pub card_exp_month: String, pub name_on_card: Option<String>, pub card_cvc: Option<String>, pub payment_method_id: Option<String>, pub customer_id: Option<common_utils::id_type::CustomerId>, pub nickname: Option<String>, pub enc_card_data: Option<String>, }
crates/diesel_models/src/locker_mock_up.rs
diesel_models
struct_definition
134
rust
LockerMockUpNew
null
null
null
null
null
null
null
null
null
null
null
pub struct BillingConnectorPaymentsSyncResponseData( revenue_recovery_response::BillingConnectorPaymentsSyncResponse, );
crates/router/src/core/webhooks/recovery_incoming.rs
router
struct_definition
21
rust
BillingConnectorPaymentsSyncResponseData
null
null
null
null
null
null
null
null
null
null
null
pub async fn delete_connector( state: SessionState, merchant_id: id_type::MerchantId, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> RouterResponse<api::MerchantConnectorDeleteResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let _merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?; let mca = db .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, &merchant_id, &merchant_connector_id, &key_store, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; let is_deleted = db .delete_merchant_connector_account_by_merchant_id_merchant_connector_id( &merchant_id, &merchant_connector_id, ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: merchant_connector_id.get_string_repr().to_string(), })?; // delete the mca from the config as well let merchant_default_config_delete = MerchantDefaultConfigUpdate { routable_connector: &Some( common_enums::RoutableConnectors::from_str(&mca.connector_name).map_err(|_| { errors::ApiErrorResponse::InvalidDataValue { field_name: "connector_name", } })?, ), merchant_connector_id: &mca.get_id(), store: db, merchant_id: &merchant_id, profile_id: &mca.profile_id, transaction_type: &mca.connector_type.into(), }; merchant_default_config_delete .retrieve_and_delete_from_default_fallback_routing_algorithm_if_routable_connector_exists() .await?; let response = api::MerchantConnectorDeleteResponse { merchant_id, merchant_connector_id, deleted: is_deleted, }; Ok(service_api::ApplicationResponse::Json(response)) }
crates/router/src/core/admin.rs
router
function_signature
529
rust
null
null
null
null
delete_connector
null
null
null
null
null
null
null
pub async fn payouts_list_core( state: SessionState, merchant_context: domain::MerchantContext, profile_id_list: Option<Vec<id_type::ProfileId>>, constraints: payouts::PayoutListConstraints, ) -> RouterResponse<payouts::PayoutListResponse> { validator::validate_payout_list_request(&constraints)?; let merchant_id = merchant_context.get_merchant_account().get_id(); let db = state.store.as_ref(); let payouts = helpers::filter_by_constraints( db, &constraints, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?; let payouts = core_utils::filter_objects_based_on_profile_id_list(profile_id_list, payouts); let mut pi_pa_tuple_vec = PayoutActionData::new(); for payout in payouts { match db .find_payout_attempt_by_merchant_id_payout_attempt_id( merchant_id, &utils::get_payout_attempt_id( payout.payout_id.get_string_repr(), payout.attempt_count, ), storage_enums::MerchantStorageScheme::PostgresOnly, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) { Ok(payout_attempt) => { let domain_customer = match payout.customer_id.clone() { #[cfg(feature = "v1")] Some(customer_id) => db .find_customer_by_customer_id_merchant_id( &(&state).into(), &customer_id, merchant_id, merchant_context.get_merchant_key_store(), merchant_context.get_merchant_account().storage_scheme, ) .await .map_err(|err| { let err_msg = format!( "failed while fetching customer for customer_id - {customer_id:?}", ); logger::warn!(?err, err_msg); }) .ok(), _ => None, }; let payout_id_as_payment_id_type = id_type::PaymentId::wrap(payout.payout_id.get_string_repr().to_string()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "payout_id contains invalid data".to_string(), }) .attach_printable("Error converting payout_id to PaymentId type")?; let payment_addr = payment_helpers::create_or_find_address_for_payment_by_request( &state, None, payout.address_id.as_deref(), merchant_id, payout.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payout_id_as_payment_id_type, merchant_context.get_merchant_account().storage_scheme, ) .await .transpose() .and_then(|addr| { addr.map_err(|err| { let err_msg = format!( "billing_address missing for address_id : {:?}", payout.address_id ); logger::warn!(?err, err_msg); }) .ok() .as_ref() .map(domain_models::address::Address::from) .map(payment_enums::Address::from) }); pi_pa_tuple_vec.push(( payout.to_owned(), payout_attempt.to_owned(), domain_customer, payment_addr, )); } Err(err) => { let err_msg = format!( "failed while fetching payout_attempt for payout_id - {:?}", payout.payout_id ); logger::warn!(?err, err_msg); } } } let data: Vec<api::PayoutCreateResponse> = pi_pa_tuple_vec .into_iter() .map(ForeignFrom::foreign_from) .collect(); Ok(services::ApplicationResponse::Json( api::PayoutListResponse { size: data.len(), data, total_count: None, }, )) }
crates/router/src/core/payouts.rs
router
function_signature
822
rust
null
null
null
null
payouts_list_core
null
null
null
null
null
null
null
pub struct CardTestingGuardConfig { pub is_card_ip_blocking_enabled: bool, pub card_ip_blocking_threshold: i32, pub is_guest_user_card_blocking_enabled: bool, pub guest_user_card_blocking_threshold: i32, pub is_customer_id_blocking_enabled: bool, pub customer_id_blocking_threshold: i32, pub card_testing_guard_expiry: i32, }
crates/diesel_models/src/business_profile.rs
diesel_models
struct_definition
84
rust
CardTestingGuardConfig
null
null
null
null
null
null
null
null
null
null
null
File: crates/router/tests/connectors/nuvei.rs use std::str::FromStr; use masking::Secret; use router::types::{self, storage::enums}; use serde_json::json; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct NuveiTest; impl ConnectorActions for NuveiTest {} impl utils::Connector for NuveiTest { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Nuvei; utils::construct_connector_data_old( Box::new(Nuvei::new()), types::Connector::Nuvei, types::api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .nuvei .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "nuvei".to_string() } } static CONNECTOR: NuveiTest = NuveiTest {}; fn get_payment_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4444 3333 2222 1111").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }) } // Cards Positive Tests // Creates a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_only_authorize_payment() { let response = CONNECTOR .authorize_payment(get_payment_data(), None) .await .expect("Authorize payment response"); assert_eq!(response.status, enums::AttemptStatus::Authorized); } // Captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment(get_payment_data(), None, None) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Partially captures a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_capture_authorized_payment() { let response = CONNECTOR .authorize_and_capture_payment( get_payment_data(), Some(types::PaymentsCaptureData { amount_to_capture: 50, ..utils::PaymentCaptureType::default().0 }), None, ) .await .expect("Capture payment response"); assert_eq!(response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_sync_authorized_payment() { let authorize_response = CONNECTOR .authorize_payment(get_payment_data(), None) .await .expect("Authorize payment response"); let txn_id = utils::get_connector_transaction_id(authorize_response.response); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Authorized, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), connector_meta: Some(json!({ "session_token": authorize_response.session_token.unwrap() })), ..Default::default() }), None, ) .await .expect("PSync response"); assert_eq!(response.status, enums::AttemptStatus::Authorized,); } // Voids a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_void_authorized_payment() { let response = CONNECTOR .authorize_and_void_payment( get_payment_data(), Some(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), amount: Some(100), currency: Some(enums::Currency::USD), ..Default::default() }), None, ) .await .expect("Void payment response"); assert_eq!(response.status, enums::AttemptStatus::Voided); } // Refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund(get_payment_data(), None, None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the manual capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_manually_captured_payment() { let response = CONNECTOR .capture_payment_and_refund( get_payment_data(), None, Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), None) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), None) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), connector_meta: Some(json!({ "session_token": authorize_response.session_token.unwrap() })), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund(get_payment_data(), None, None) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Partially refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_partially_refund_succeeded_payment() { let refund_response = CONNECTOR .make_payment_and_refund( get_payment_data(), Some(types::RefundsData { refund_amount: 50, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( refund_response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Missing or invalid CardData data. Invalid credit card number.".to_string(), ); } // Creates a payment with incorrect CVC. #[actix_web::test] async fn should_fail_payment_for_incorrect_cvc() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_cvc: Secret::new("12345".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "cardData.CVV is invalid".to_string(), ); } // Creates a payment with incorrect expiry month. #[actix_web::test] async fn should_fail_payment_for_invalid_exp_month() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_exp_month: Secret::new("20".to_string()), ..utils::CCardType::default().0 }), ..utils::PaymentAuthorizeType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Invalid expired date".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_succeed_payment_for_incorrect_expiry_year() { let response = CONNECTOR .make_payment( Some(types::PaymentsAuthorizeData { payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card { card_number: cards::CardNumber::from_str("4000027891380961").unwrap(), card_exp_year: Secret::new("2000".to_string()), ..utils::CCardType::default().0 }), ..get_payment_data().unwrap() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Voids a payment using automatic capture flow (Non 3DS). #[actix_web::test] async fn should_fail_void_payment_for_auto_capture() { let authorize_response = CONNECTOR .make_payment(get_payment_data(), None) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let void_response = CONNECTOR .void_payment( txn_id.unwrap(), Some(types::PaymentsCancelData { cancellation_reason: Some("requested_by_customer".to_string()), amount: Some(100), currency: Some(enums::Currency::USD), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(void_response.status, enums::AttemptStatus::Voided); } // Captures a payment using invalid connector payment id. #[actix_web::test] async fn should_fail_capture_for_invalid_payment() { let capture_response = CONNECTOR .capture_payment("123456789".to_string(), None, None) .await .unwrap(); assert_eq!( capture_response.response.unwrap_err().message, String::from("Invalid relatedTransactionId") ); } // Refunds a payment with refund amount higher than payment amount. #[actix_web::test] async fn should_accept_refund_amount_higher_than_payment_amount() { let response = CONNECTOR .make_payment_and_refund( get_payment_data(), Some(types::RefundsData { refund_amount: 150, ..utils::PaymentRefundType::default().0 }), None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); }
crates/router/tests/connectors/nuvei.rs
router
full_file
2,754
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct PaypalPaymentsRequest { intent: PaypalPaymentIntent, purchase_units: Vec<PurchaseUnitRequest>, payment_source: Option<PaymentSourceItem>, }
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
struct_definition
34
rust
PaypalPaymentsRequest
null
null
null
null
null
null
null
null
null
null
null
pub struct BillingConnectorInvoiceSyncFlowData;
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
hyperswitch_domain_models
struct_definition
9
rust
BillingConnectorInvoiceSyncFlowData
null
null
null
null
null
null
null
null
null
null
null
pub struct LineItem { id: Option<String>, quantity: Option<u16>, product_tax_code: Option<String>, unit_price: Option<FloatMajorUnit>, }
crates/hyperswitch_connectors/src/connectors/taxjar/transformers.rs
hyperswitch_connectors
struct_definition
37
rust
LineItem
null
null
null
null
null
null
null
null
null
null
null
pub fn list_payment_methods() {}
crates/openapi/src/routes/payments.rs
openapi
function_signature
7
rust
null
null
null
null
list_payment_methods
null
null
null
null
null
null
null
pub struct BitpayAuthType { pub(super) api_key: Secret<String>, }
crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
hyperswitch_connectors
struct_definition
18
rust
BitpayAuthType
null
null
null
null
null
null
null
null
null
null
null
| common_enums::PaymentMethodType::ClassicReward | common_enums::PaymentMethodType::Credit | common_enums::PaymentMethodType::CryptoCurrency | common_enums::PaymentMethodType::Cashapp | common_enums::PaymentMethodType::Dana | common_enums::PaymentMethodType::DanamonVa | common_enums::PaymentMethodType::Debit | common_enums::PaymentMethodType::DirectCarrierBilling | common_enums::PaymentMethodType::Efecty | common_enums::PaymentMethodType::Eft | common_enums::PaymentMethodType::Eps | common_enums::PaymentMethodType::Evoucher | common_enums::PaymentMethodType::Giropay | common_enums::PaymentMethodType::Givex | common_enums::PaymentMethodType::GooglePay | common_enums::PaymentMethodType::GoPay | common_enums::PaymentMethodType::Gcash | common_enums::PaymentMethodType::Ideal | common_enums::PaymentMethodType::Interac | common_enums::PaymentMethodType::Indomaret | common_enums::PaymentMethodType::Klarna | common_enums::PaymentMethodType::KakaoPay | common_enums::PaymentMethodType::MandiriVa | common_enums::PaymentMethodType::Knet | common_enums::PaymentMethodType::MbWay | common_enums::PaymentMethodType::MobilePay | common_enums::PaymentMethodType::Momo | common_enums::PaymentMethodType::MomoAtm | common_enums::PaymentMethodType::Multibanco | common_enums::PaymentMethodType::LocalBankRedirect | common_enums::PaymentMethodType::OnlineBankingThailand | common_enums::PaymentMethodType::OnlineBankingCzechRepublic | common_enums::PaymentMethodType::OnlineBankingFinland | common_enums::PaymentMethodType::OnlineBankingFpx | common_enums::PaymentMethodType::OnlineBankingPoland | common_enums::PaymentMethodType::OnlineBankingSlovakia | common_enums::PaymentMethodType::Oxxo | common_enums::PaymentMethodType::PagoEfectivo | common_enums::PaymentMethodType::PermataBankTransfer | common_enums::PaymentMethodType::OpenBankingUk | common_enums::PaymentMethodType::PayBright | common_enums::PaymentMethodType::Paypal | common_enums::PaymentMethodType::Paze | common_enums::PaymentMethodType::Pix | common_enums::PaymentMethodType::PaySafeCard | common_enums::PaymentMethodType::Przelewy24 | common_enums::PaymentMethodType::Pse | common_enums::PaymentMethodType::RedCompra | common_enums::PaymentMethodType::RedPagos | common_enums::PaymentMethodType::SamsungPay | common_enums::PaymentMethodType::Sepa | common_enums::PaymentMethodType::SepaBankTransfer | common_enums::PaymentMethodType::Sofort | common_enums::PaymentMethodType::Swish | common_enums::PaymentMethodType::TouchNGo | common_enums::PaymentMethodType::Trustly | common_enums::PaymentMethodType::Twint | common_enums::PaymentMethodType::UpiCollect | common_enums::PaymentMethodType::UpiIntent | common_enums::PaymentMethodType::Venmo | common_enums::PaymentMethodType::Vipps | common_enums::PaymentMethodType::Walley | common_enums::PaymentMethodType::WeChatPay | common_enums::PaymentMethodType::SevenEleven | common_enums::PaymentMethodType::Lawson | common_enums::PaymentMethodType::LocalBankTransfer | common_enums::PaymentMethodType::InstantBankTransfer | common_enums::PaymentMethodType::InstantBankTransferFinland | common_enums::PaymentMethodType::InstantBankTransferPoland | common_enums::PaymentMethodType::MiniStop | common_enums::PaymentMethodType::FamilyMart | common_enums::PaymentMethodType::Seicomart | common_enums::PaymentMethodType::PayEasy | common_enums::PaymentMethodType::Mifinity | common_enums::PaymentMethodType::Fps | common_enums::PaymentMethodType::DuitNow | common_enums::PaymentMethodType::PromptPay | common_enums::PaymentMethodType::VietQr | common_enums::PaymentMethodType::Flexiti | common_enums::PaymentMethodType::OpenBankingPIS | common_enums::PaymentMethodType::IndonesianBankTransfer | common_enums::PaymentMethodType::RevolutPay | common_enums::PaymentMethodType::Breadpay, ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", })), #[cfg(feature = "v2")] ( common_enums::PaymentExperience::DisplayQrCode | common_enums::PaymentExperience::DisplayWaitScreen | common_enums::PaymentExperience::InvokePaymentApp | common_enums::PaymentExperience::InvokeSdkClient | common_enums::PaymentExperience::LinkWallet | common_enums::PaymentExperience::OneClick | common_enums::PaymentExperience::RedirectToUrl | common_enums::PaymentExperience::CollectOtp, common_enums::PaymentMethodType::Ach | common_enums::PaymentMethodType::Bluecode | common_enums::PaymentMethodType::Affirm | common_enums::PaymentMethodType::AfterpayClearpay | common_enums::PaymentMethodType::Alfamart | common_enums::PaymentMethodType::AliPay | common_enums::PaymentMethodType::AliPayHk | common_enums::PaymentMethodType::Alma | common_enums::PaymentMethodType::AmazonPay | common_enums::PaymentMethodType::Paysera | common_enums::PaymentMethodType::Skrill | common_enums::PaymentMethodType::ApplePay | common_enums::PaymentMethodType::Atome | common_enums::PaymentMethodType::Bacs | common_enums::PaymentMethodType::BancontactCard | common_enums::PaymentMethodType::Becs | common_enums::PaymentMethodType::Benefit | common_enums::PaymentMethodType::Bizum | common_enums::PaymentMethodType::Blik | common_enums::PaymentMethodType::Boleto | common_enums::PaymentMethodType::BcaBankTransfer | common_enums::PaymentMethodType::BhnCardNetwork | common_enums::PaymentMethodType::BniVa | common_enums::PaymentMethodType::BriVa | common_enums::PaymentMethodType::CardRedirect | common_enums::PaymentMethodType::CimbVa | common_enums::PaymentMethodType::ClassicReward | common_enums::PaymentMethodType::Credit | common_enums::PaymentMethodType::Card | common_enums::PaymentMethodType::CryptoCurrency | common_enums::PaymentMethodType::Cashapp | common_enums::PaymentMethodType::Dana | common_enums::PaymentMethodType::DanamonVa | common_enums::PaymentMethodType::Debit | common_enums::PaymentMethodType::DirectCarrierBilling | common_enums::PaymentMethodType::Efecty | common_enums::PaymentMethodType::Eft | common_enums::PaymentMethodType::Eps | common_enums::PaymentMethodType::Evoucher | common_enums::PaymentMethodType::Giropay | common_enums::PaymentMethodType::Givex | common_enums::PaymentMethodType::GooglePay | common_enums::PaymentMethodType::GoPay | common_enums::PaymentMethodType::Gcash | common_enums::PaymentMethodType::Ideal | common_enums::PaymentMethodType::Interac | common_enums::PaymentMethodType::Indomaret | common_enums::PaymentMethodType::Klarna | common_enums::PaymentMethodType::KakaoPay | common_enums::PaymentMethodType::MandiriVa | common_enums::PaymentMethodType::Knet | common_enums::PaymentMethodType::MbWay | common_enums::PaymentMethodType::MobilePay | common_enums::PaymentMethodType::Momo | common_enums::PaymentMethodType::MomoAtm | common_enums::PaymentMethodType::Multibanco | common_enums::PaymentMethodType::LocalBankRedirect | common_enums::PaymentMethodType::OnlineBankingThailand | common_enums::PaymentMethodType::OnlineBankingCzechRepublic | common_enums::PaymentMethodType::OnlineBankingFinland | common_enums::PaymentMethodType::OnlineBankingFpx | common_enums::PaymentMethodType::OnlineBankingPoland | common_enums::PaymentMethodType::OnlineBankingSlovakia | common_enums::PaymentMethodType::Oxxo | common_enums::PaymentMethodType::PagoEfectivo | common_enums::PaymentMethodType::PermataBankTransfer | common_enums::PaymentMethodType::OpenBankingUk | common_enums::PaymentMethodType::PayBright | common_enums::PaymentMethodType::Paypal | common_enums::PaymentMethodType::Paze | common_enums::PaymentMethodType::Pix | common_enums::PaymentMethodType::PaySafeCard | common_enums::PaymentMethodType::Przelewy24 | common_enums::PaymentMethodType::Pse | common_enums::PaymentMethodType::RedCompra | common_enums::PaymentMethodType::RedPagos | common_enums::PaymentMethodType::SamsungPay | common_enums::PaymentMethodType::Sepa | common_enums::PaymentMethodType::SepaBankTransfer | common_enums::PaymentMethodType::Sofort | common_enums::PaymentMethodType::Swish | common_enums::PaymentMethodType::TouchNGo | common_enums::PaymentMethodType::Trustly | common_enums::PaymentMethodType::Twint | common_enums::PaymentMethodType::UpiCollect | common_enums::PaymentMethodType::UpiIntent | common_enums::PaymentMethodType::Venmo | common_enums::PaymentMethodType::Vipps | common_enums::PaymentMethodType::Walley | common_enums::PaymentMethodType::WeChatPay | common_enums::PaymentMethodType::SevenEleven | common_enums::PaymentMethodType::Lawson | common_enums::PaymentMethodType::LocalBankTransfer | common_enums::PaymentMethodType::InstantBankTransfer | common_enums::PaymentMethodType::InstantBankTransferFinland | common_enums::PaymentMethodType::InstantBankTransferPoland | common_enums::PaymentMethodType::MiniStop | common_enums::PaymentMethodType::FamilyMart | common_enums::PaymentMethodType::Seicomart | common_enums::PaymentMethodType::PayEasy | common_enums::PaymentMethodType::Mifinity | common_enums::PaymentMethodType::Fps | common_enums::PaymentMethodType::DuitNow | common_enums::PaymentMethodType::PromptPay | common_enums::PaymentMethodType::VietQr | common_enums::PaymentMethodType::Flexiti | common_enums::PaymentMethodType::OpenBankingPIS | common_enums::PaymentMethodType::RevolutPay | common_enums::PaymentMethodType::Breadpay | common_enums::PaymentMethodType::IndonesianBankTransfer | common_enums::PaymentMethodType::Skrill, ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { message: payment_method_type.to_string(), connector: "klarna", })), } } PaymentMethodData::Card(_) | PaymentMethodData::CardRedirect(_) | PaymentMethodData::Wallet(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::MandatePayment | PaymentMethodData::Reward | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::OpenBanking(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::NetworkToken(_) | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => { Err(report!(errors::ConnectorError::NotImplemented( get_unimplemented_payment_method_error_message(req.connector.as_str(),), ))) } } } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = klarna::KlarnaRouterData::from((amount, req)); let connector_req = klarna::KlarnaPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: klarna::KlarnaAuthResponse = res .response .parse_struct("KlarnaPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Klarna { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let order_id = req.request.connector_transaction_id.clone(); let endpoint = build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!( "{endpoint}ordermanagement/v1/orders/{order_id}/cancel" )) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, _event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { logger::debug!("Expected zero bytes response, skipped parsing of the response"); let status = if res.status_code == 204 { enums::AttemptStatus::Voided } else { enums::AttemptStatus::VoidFailed }; Ok(PaymentsCancelRouterData { status, ..data.clone() }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::Refund for Klarna {} impl api::RefundExecute for Klarna {} impl api::RefundSync for Klarna {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Klarna { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let order_id = req.request.connector_transaction_id.clone(); let endpoint = build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!( "{endpoint}ordermanagement/v1/orders/{order_id}/refunds", )) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = klarna::KlarnaRouterData::from((amount, req)); let connector_req = klarna::KlarnaRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { match res.headers { Some(headers) => { let refund_id = get_http_header("Refund-Id", &headers) .attach_printable("Missing refund id in headers") .change_context(errors::ConnectorError::ResponseHandlingFailed)?; let response = klarna::KlarnaRefundResponse { refund_id: refund_id.to_owned(), }; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } None => Err(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("Expected headers, but received no headers in response")?, } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Klarna { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let order_id = req.request.connector_transaction_id.clone(); let refund_id = req.request.get_connector_refund_id()?; let endpoint = build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?; Ok(format!( "{endpoint}ordermanagement/v1/orders/{order_id}/refunds/{refund_id}" )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: klarna::KlarnaRefundSyncResponse = res .response .parse_struct("klarna KlarnaRefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl IncomingWebhook for Klarna { fn get_webhook_object_reference_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> { Ok(IncomingWebhookEvent::EventNotSupported) } fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static KLARNA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, enums::CaptureMethod::SequentialAutomatic, ]; let mut klarna_supported_payment_methods = SupportedPaymentMethods::new(); klarna_supported_payment_methods.add( enums::PaymentMethod::PayLater, enums::PaymentMethodType::Klarna, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods, specific_features: None, }, ); klarna_supported_payment_methods }); static KLARNA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Klarna", description: "Klarna provides payment processing services for the e-commerce industry, managing store claims and customer payments.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Live, }; static KLARNA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Klarna { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&KLARNA_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*KLARNA_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&KLARNA_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/klarna.rs#chunk1
hyperswitch_connectors
chunk
5,968
null
null
null
null
null
null
null
null
null
null
null
null
null
impl IncomingWebhook for Stripe { fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { let mut security_header_kvs = get_signature_elements_from_header(request.headers)?; let signature = security_header_kvs .remove("v1") .ok_or(ConnectorError::WebhookSignatureNotFound)?; hex::decode(signature).change_context(ConnectorError::WebhookSignatureNotFound) } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { let mut security_header_kvs = get_signature_elements_from_header(request.headers)?; let timestamp = security_header_kvs .remove("t") .ok_or(ConnectorError::WebhookSignatureNotFound)?; Ok(format!( "{}.{}", String::from_utf8_lossy(&timestamp), String::from_utf8_lossy(request.body) ) .into_bytes()) } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") .change_context(ConnectorError::WebhookReferenceIdNotFound)?; Ok(match details.event_data.event_object.object { stripe::WebhookEventObjectType::PaymentIntent => { match details .event_data .event_object .metadata .and_then(|meta_data| meta_data.order_id) { // if order_id is present Some(order_id) => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(order_id), ), // else used connector_transaction_id None => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details.event_data.event_object.id, ), ), } } stripe::WebhookEventObjectType::Charge => { match details .event_data .event_object .metadata .and_then(|meta_data| meta_data.order_id) { // if order_id is present Some(order_id) => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId(order_id), ), // else used connector_transaction_id None => api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details .event_data .event_object .payment_intent .ok_or(ConnectorError::WebhookReferenceIdNotFound)?, ), ), } } stripe::WebhookEventObjectType::Dispute => { api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( details .event_data .event_object .payment_intent .ok_or(ConnectorError::WebhookReferenceIdNotFound)?, ), ) } stripe::WebhookEventObjectType::Source => { api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PreprocessingId( details.event_data.event_object.id, ), ) } stripe::WebhookEventObjectType::Refund => { match details .event_data .event_object .metadata .clone() .and_then(|meta_data| meta_data.order_id) { // if meta_data is present Some(order_id) => { // Issue: 2076 match details .event_data .event_object .metadata .and_then(|meta_data| meta_data.is_refund_id_as_reference) { // if the order_id is refund_id Some(_) => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::RefundId(order_id), ), // if the order_id is payment_id // since payment_id was being passed before the deployment of this pr _ => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId( details.event_data.event_object.id, ), ), } } // else use connector_transaction_id None => api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId( details.event_data.event_object.id, ), ), } } }) } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { let details: stripe::WebhookEventTypeBody = request .body .parse_struct("WebhookEventTypeBody") .change_context(ConnectorError::WebhookReferenceIdNotFound)?; Ok(match details.event_type { stripe::WebhookEventType::PaymentIntentFailed => { IncomingWebhookEvent::PaymentIntentFailure } stripe::WebhookEventType::PaymentIntentSucceed => { IncomingWebhookEvent::PaymentIntentSuccess } stripe::WebhookEventType::PaymentIntentCanceled => { IncomingWebhookEvent::PaymentIntentCancelled } stripe::WebhookEventType::PaymentIntentAmountCapturableUpdated => { IncomingWebhookEvent::PaymentIntentAuthorizationSuccess } stripe::WebhookEventType::ChargeSucceeded => { if let Some(stripe::WebhookPaymentMethodDetails { payment_method: stripe::WebhookPaymentMethodType::AchCreditTransfer | stripe::WebhookPaymentMethodType::MultibancoBankTransfers, }) = details.event_data.event_object.payment_method_details { IncomingWebhookEvent::PaymentIntentSuccess } else { IncomingWebhookEvent::EventNotSupported } } stripe::WebhookEventType::ChargeRefundUpdated => details .event_data .event_object .status .map(|status| match status { stripe::WebhookEventStatus::Succeeded => IncomingWebhookEvent::RefundSuccess, stripe::WebhookEventStatus::Failed => IncomingWebhookEvent::RefundFailure, _ => IncomingWebhookEvent::EventNotSupported, }) .unwrap_or(IncomingWebhookEvent::EventNotSupported), stripe::WebhookEventType::SourceChargeable => IncomingWebhookEvent::SourceChargeable, stripe::WebhookEventType::DisputeCreated => IncomingWebhookEvent::DisputeOpened, stripe::WebhookEventType::DisputeClosed => IncomingWebhookEvent::DisputeCancelled, stripe::WebhookEventType::DisputeUpdated => details .event_data .event_object .status .map(Into::into) .unwrap_or(IncomingWebhookEvent::EventNotSupported), stripe::WebhookEventType::PaymentIntentPartiallyFunded => { IncomingWebhookEvent::PaymentIntentPartiallyFunded } stripe::WebhookEventType::PaymentIntentRequiresAction => { IncomingWebhookEvent::PaymentActionRequired } stripe::WebhookEventType::ChargeDisputeFundsWithdrawn => { IncomingWebhookEvent::DisputeLost } stripe::WebhookEventType::ChargeDisputeFundsReinstated => { IncomingWebhookEvent::DisputeWon } stripe::WebhookEventType::Unknown | stripe::WebhookEventType::ChargeCaptured | stripe::WebhookEventType::ChargeExpired | stripe::WebhookEventType::ChargeFailed | stripe::WebhookEventType::ChargePending | stripe::WebhookEventType::ChargeUpdated | stripe::WebhookEventType::ChargeRefunded | stripe::WebhookEventType::PaymentIntentCreated | stripe::WebhookEventType::PaymentIntentProcessing | stripe::WebhookEventType::SourceTransactionCreated => { IncomingWebhookEvent::EventNotSupported } }) } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") .change_context(ConnectorError::WebhookBodyDecodingFailed)?; Ok(Box::new(details.event_data.event_object)) } fn get_dispute_details( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<DisputePayload, ConnectorError> { let details: stripe::WebhookEvent = request .body .parse_struct("WebhookEvent") .change_context(ConnectorError::WebhookBodyDecodingFailed)?; let amt = details.event_data.event_object.amount.ok_or_else(|| { ConnectorError::MissingRequiredField { field_name: "amount", } })?; Ok(DisputePayload { amount: utils::convert_amount( self.amount_converter_webhooks, amt, details.event_data.event_object.currency, )?, currency: details.event_data.event_object.currency, dispute_stage: api_models::enums::DisputeStage::Dispute, connector_dispute_id: details.event_data.event_object.id, connector_reason: details.event_data.event_object.reason, connector_reason_code: None, challenge_required_by: details .event_data .event_object .evidence_details .map(|payload| payload.due_by), connector_status: details .event_data .event_object .status .ok_or(ConnectorError::WebhookResourceObjectNotFound)? .to_string(), created_at: Some(details.event_data.event_object.created), updated_at: None, }) } }
crates/hyperswitch_connectors/src/connectors/stripe.rs
hyperswitch_connectors
impl_block
2,324
rust
null
Stripe
IncomingWebhook for
impl IncomingWebhook for for Stripe
null
null
null
null
null
null
null
null
pub trait AuthEventMetric<T> where T: AnalyticsDataSource + AuthEventMetricAnalytics, { async fn load_metrics( &self, auth: &AuthInfo, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>>; }
crates/analytics/src/auth_events/metrics.rs
analytics
trait_definition
97
rust
null
null
AuthEventMetric
null
null
null
null
null
null
null
null
null
impl ConnectorSpecifications for Hyperwallet { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&HYPERWALLET_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*HYPERWALLET_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&HYPERWALLET_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/hyperwallet.rs
hyperswitch_connectors
impl_block
114
rust
null
Hyperwallet
ConnectorSpecifications for
impl ConnectorSpecifications for for Hyperwallet
null
null
null
null
null
null
null
null
impl UserKeyStore { pub async fn get_all_user_key_stores( conn: &PgPooledConn, from: u32, limit: u32, ) -> StorageResult<Vec<Self>> { generics::generic_filter::< <Self as HasTable>::Table, _, <<Self as HasTable>::Table as diesel::Table>::PrimaryKey, _, >( conn, dsl::user_id.ne_all(vec!["".to_string()]), Some(limit.into()), Some(from.into()), None, ) .await } pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> { generics::generic_find_one::<<Self as HasTable>::Table, _, _>( conn, dsl::user_id.eq(user_id.to_owned()), ) .await } }
crates/diesel_models/src/query/user_key_store.rs
diesel_models
impl_block
198
rust
null
UserKeyStore
null
impl UserKeyStore
null
null
null
null
null
null
null
null
pub struct SyncCardDetails { pub alias: Option<String>, }
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
hyperswitch_connectors
struct_definition
14
rust
SyncCardDetails
null
null
null
null
null
null
null
null
null
null
null
pub struct PaymentLinkStatusData { pub js_script: String, pub css_script: String, }
crates/hyperswitch_domain_models/src/api.rs
hyperswitch_domain_models
struct_definition
22
rust
PaymentLinkStatusData
null
null
null
null
null
null
null
null
null
null
null
impl ConnectorValidation for Mifinity { //TODO: implement functions when support enabled }
crates/hyperswitch_connectors/src/connectors/mifinity.rs
hyperswitch_connectors
impl_block
19
rust
null
Mifinity
ConnectorValidation for
impl ConnectorValidation for for Mifinity
null
null
null
null
null
null
null
null
pub struct StripeUpi { pub vpa_id: masking::Secret<String, UpiVpaMaskingStrategy>, }
crates/router/src/compatibility/stripe/payment_intents/types.rs
router
struct_definition
26
rust
StripeUpi
null
null
null
null
null
null
null
null
null
null
null
OpenAPI Block Path: components.schemas.SamsungPayCardBrand { "type": "string", "enum": [ "visa", "mastercard", "amex", "discover", "unknown" ] }
./hyperswitch/api-reference/v1/openapi_spec_v1.json
null
openapi_block
52
.json
null
null
null
null
null
openapi_spec
components
[ "schemas", "SamsungPayCardBrand" ]
null
null
null
null
Ok(()) } Err(err) => { logger::error!("open_router_update_gateway_score_error: {:?}", err); Err(errors::RoutingError::OpenRouterError( "Failed to update gateway score in open_router".into(), )) } }?; Ok(()) } /// success based dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[instrument(skip_all)] #[allow(clippy::too_many_arguments)] pub async fn perform_success_based_routing<F, D>( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, success_based_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, success_based_algo_ref: api_routing::SuccessBasedAlgorithm, payment_data: &mut D, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { if success_based_algo_ref.enabled_feature == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection { logger::debug!( "performing success_based_routing for profile {}", profile_id.get_string_repr() ); let client = &state .grpc_client .dynamic_routing .as_ref() .ok_or(errors::RoutingError::SuccessRateClientInitializationError) .attach_printable("dynamic routing gRPC client not found")? .success_rate_client; let success_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::< api_routing::SuccessBasedRoutingConfig, >( state, profile_id, success_based_algo_ref .algorithm_id_with_timestamp .algorithm_id .ok_or(errors::RoutingError::GenericNotFoundError { field: "success_based_routing_algorithm_id".to_string(), }) .attach_printable("success_based_routing_algorithm_id not found in profile_id")?, ) .await .change_context(errors::RoutingError::SuccessBasedRoutingConfigError) .attach_printable("unable to fetch success_rate based dynamic routing configs")?; let success_based_routing_config_params = success_based_routing_config_params_interpolator .get_string_val( success_based_routing_configs .params .as_ref() .ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)?, ); let event_request = utils::CalSuccessRateEventRequest { id: profile_id.get_string_repr().to_string(), params: success_based_routing_config_params.clone(), labels: routable_connectors .iter() .map(|conn_choice| conn_choice.to_string()) .collect::<Vec<_>>(), config: success_based_routing_configs .config .as_ref() .map(utils::CalSuccessRateConfigEventRequest::from), }; let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), state.request_id, payment_id.get_string_repr().to_string(), profile_id.to_owned(), merchant_id.to_owned(), "IntelligentRouter: CalculateSuccessRate".to_string(), Some(event_request.clone()), true, false, ); let closure = || async { let success_based_connectors_result = client .calculate_success_rate( profile_id.get_string_repr().into(), success_based_routing_configs, success_based_routing_config_params, routable_connectors, state.get_grpc_headers(), ) .await .change_context(errors::RoutingError::SuccessRateCalculationError) .attach_printable( "unable to calculate/fetch success rate from dynamic routing service", ); match success_based_connectors_result { Ok(success_response) => { let updated_resp = utils::CalSuccessRateEventResponse::try_from( &success_response, ) .change_context(errors::RoutingError::RoutingEventsError { message: "unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse".to_string(), status_code: 500 }) .attach_printable( "unable to convert SuccessBasedConnectors to CalSuccessRateEventResponse", )?; Ok(Some(updated_resp)) } Err(e) => { logger::error!( "unable to calculate/fetch success rate from dynamic routing service: {:?}", e.current_context() ); Err(error_stack::report!( errors::RoutingError::SuccessRateCalculationError )) } } }; let events_response = routing_events_wrapper .construct_event_builder( "SuccessRateCalculator.FetchSuccessRate".to_string(), RoutingEngine::IntelligentRouter, ApiMethod::Grpc, )? .trigger_event(state, closure) .await?; let success_based_connectors: utils::CalSuccessRateEventResponse = events_response .response .ok_or(errors::RoutingError::SuccessRateCalculationError)?; // Need to log error case let mut routing_event = events_response .event .ok_or(errors::RoutingError::RoutingEventsError { message: "SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" .to_string(), status_code: 500, })?; routing_event.set_routing_approach(success_based_connectors.routing_approach.to_string()); payment_data.set_routing_approach_in_attempt(Some(common_enums::RoutingApproach::from( success_based_connectors.routing_approach, ))); let mut connectors = Vec::with_capacity(success_based_connectors.labels_with_score.len()); for label_with_score in success_based_connectors.labels_with_score { let (connector, merchant_connector_id) = label_with_score.label .split_once(':') .ok_or(errors::RoutingError::InvalidSuccessBasedConnectorLabel(label_with_score.label.to_string())) .attach_printable( "unable to split connector_name and mca_id from the label obtained by the dynamic routing service", )?; connectors.push(api_routing::RoutableConnectorChoice { choice_kind: api_routing::RoutableChoiceKind::FullStruct, connector: common_enums::RoutableConnectors::from_str(connector) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "RoutableConnectors".to_string(), }) .attach_printable("unable to convert String to RoutableConnectors")?, merchant_connector_id: Some( common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "MerchantConnectorAccountId".to_string(), }) .attach_printable("unable to convert MerchantConnectorAccountId from string")?, ), }); } logger::debug!(success_based_routing_connectors=?connectors); routing_event.set_status_code(200); routing_event.set_routable_connectors(connectors.clone()); state.event_handler().log_event(&routing_event); Ok(connectors) } else { Ok(routable_connectors) } } /// elimination dynamic routing #[cfg(all(feature = "v1", feature = "dynamic_routing"))] pub async fn perform_elimination_routing( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, elimination_routing_configs_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, elimination_algo_ref: api_routing::EliminationRoutingAlgorithm, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> { if elimination_algo_ref.enabled_feature == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection { logger::debug!( "performing elimination_routing for profile {}", profile_id.get_string_repr() ); let client = &state .grpc_client .dynamic_routing .as_ref() .ok_or(errors::RoutingError::EliminationClientInitializationError) .attach_printable("dynamic routing gRPC client not found")? .elimination_based_client; let elimination_routing_config = routing::helpers::fetch_dynamic_routing_configs::< api_routing::EliminationRoutingConfig, >( state, profile_id, elimination_algo_ref .algorithm_id_with_timestamp .algorithm_id .ok_or(errors::RoutingError::GenericNotFoundError { field: "elimination_routing_algorithm_id".to_string(), }) .attach_printable( "elimination_routing_algorithm_id not found in business_profile", )?, ) .await .change_context(errors::RoutingError::EliminationRoutingConfigError) .attach_printable("unable to fetch elimination dynamic routing configs")?; let elimination_routing_config_params = elimination_routing_configs_params_interpolator .get_string_val( elimination_routing_config .params .as_ref() .ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)?, ); let event_request = utils::EliminationRoutingEventRequest { id: profile_id.get_string_repr().to_string(), params: elimination_routing_config_params.clone(), labels: routable_connectors .iter() .map(|conn_choice| conn_choice.to_string()) .collect::<Vec<_>>(), config: elimination_routing_config .elimination_analyser_config .as_ref() .map(utils::EliminationRoutingEventBucketConfig::from), }; let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), state.request_id, payment_id.get_string_repr().to_string(), profile_id.to_owned(), merchant_id.to_owned(), "IntelligentRouter: PerformEliminationRouting".to_string(), Some(event_request.clone()), true, false, ); let closure = || async { let elimination_based_connectors_result = client .perform_elimination_routing( profile_id.get_string_repr().to_string(), elimination_routing_config_params, routable_connectors.clone(), elimination_routing_config.elimination_analyser_config, state.get_grpc_headers(), ) .await .change_context(errors::RoutingError::EliminationRoutingCalculationError) .attach_printable( "unable to analyze/fetch elimination routing from dynamic routing service", ); match elimination_based_connectors_result { Ok(elimination_response) => Ok(Some(utils::EliminationEventResponse::from( &elimination_response, ))), Err(e) => { logger::error!( "unable to analyze/fetch elimination routing from dynamic routing service: {:?}", e.current_context() ); Err(error_stack::report!( errors::RoutingError::EliminationRoutingCalculationError )) } } }; let events_response = routing_events_wrapper .construct_event_builder( "EliminationAnalyser.GetEliminationStatus".to_string(), RoutingEngine::IntelligentRouter, ApiMethod::Grpc, )? .trigger_event(state, closure) .await?; let elimination_based_connectors: utils::EliminationEventResponse = events_response .response .ok_or(errors::RoutingError::EliminationRoutingCalculationError)?; let mut routing_event = events_response .event .ok_or(errors::RoutingError::RoutingEventsError { message: "Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" .to_string(), status_code: 500, })?; routing_event.set_routing_approach(utils::RoutingApproach::Elimination.to_string()); let mut connectors = Vec::with_capacity(elimination_based_connectors.labels_with_status.len()); let mut eliminated_connectors = Vec::with_capacity(elimination_based_connectors.labels_with_status.len()); let mut non_eliminated_connectors = Vec::with_capacity(elimination_based_connectors.labels_with_status.len()); for labels_with_status in elimination_based_connectors.labels_with_status { let (connector, merchant_connector_id) = labels_with_status.label .split_once(':') .ok_or(errors::RoutingError::InvalidEliminationBasedConnectorLabel(labels_with_status.label.to_string())) .attach_printable( "unable to split connector_name and mca_id from the label obtained by the elimination based dynamic routing service", )?; let routable_connector = api_routing::RoutableConnectorChoice { choice_kind: api_routing::RoutableChoiceKind::FullStruct, connector: common_enums::RoutableConnectors::from_str(connector) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "RoutableConnectors".to_string(), }) .attach_printable("unable to convert String to RoutableConnectors")?, merchant_connector_id: Some( common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "MerchantConnectorAccountId".to_string(), }) .attach_printable("unable to convert MerchantConnectorAccountId from string")?, ), }; if labels_with_status .elimination_information .is_some_and(|elimination_info| { elimination_info .entity .is_some_and(|entity_info| entity_info.is_eliminated) }) { eliminated_connectors.push(routable_connector); } else { non_eliminated_connectors.push(routable_connector); } connectors.extend(non_eliminated_connectors.clone()); connectors.extend(eliminated_connectors.clone()); } logger::debug!(dynamic_eliminated_connectors=?eliminated_connectors); logger::debug!(dynamic_elimination_based_routing_connectors=?connectors); routing_event.set_status_code(200); routing_event.set_routable_connectors(connectors.clone()); state.event_handler().log_event(&routing_event); Ok(connectors) } else { Ok(routable_connectors) } } #[cfg(all(feature = "v1", feature = "dynamic_routing"))] #[allow(clippy::too_many_arguments)] pub async fn perform_contract_based_routing<F, D>( state: &SessionState, routable_connectors: Vec<api_routing::RoutableConnectorChoice>, profile_id: &common_utils::id_type::ProfileId, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator, contract_based_algo_ref: api_routing::ContractRoutingAlgorithm, payment_data: &mut D, ) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone, { if contract_based_algo_ref.enabled_feature == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection { logger::debug!( "performing contract_based_routing for profile {}", profile_id.get_string_repr() ); let client = &state .grpc_client .dynamic_routing .as_ref() .ok_or(errors::RoutingError::ContractRoutingClientInitializationError) .attach_printable("dynamic routing gRPC client not found")? .contract_based_client; let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::< api_routing::ContractBasedRoutingConfig, >( state, profile_id, contract_based_algo_ref .algorithm_id_with_timestamp .algorithm_id .ok_or(errors::RoutingError::GenericNotFoundError { field: "contract_based_routing_algorithm_id".to_string(), }) .attach_printable("contract_based_routing_algorithm_id not found in profile_id")?, ) .await .change_context(errors::RoutingError::ContractBasedRoutingConfigError) .attach_printable("unable to fetch contract based dynamic routing configs")?; let label_info = contract_based_routing_configs .label_info .clone() .ok_or(errors::RoutingError::ContractBasedRoutingConfigError) .attach_printable("Label information not found in contract routing configs")?; let contract_based_connectors = routable_connectors .clone() .into_iter() .filter(|conn| { label_info .iter() .any(|info| Some(info.mca_id.clone()) == conn.merchant_connector_id.clone()) }) .collect::<Vec<_>>(); let mut other_connectors = routable_connectors .into_iter() .filter(|conn| { label_info .iter() .all(|info| Some(info.mca_id.clone()) != conn.merchant_connector_id.clone()) }) .collect::<Vec<_>>(); let event_request = utils::CalContractScoreEventRequest { id: profile_id.get_string_repr().to_string(), params: "".to_string(), labels: contract_based_connectors .iter() .map(|conn_choice| conn_choice.to_string()) .collect::<Vec<_>>(), config: Some(contract_based_routing_configs.clone()), }; let routing_events_wrapper = utils::RoutingEventsWrapper::new( state.tenant.tenant_id.clone(), state.request_id, payment_id.get_string_repr().to_string(), profile_id.to_owned(), merchant_id.to_owned(), "IntelligentRouter: PerformContractRouting".to_string(), Some(event_request.clone()), true, false, ); let closure = || async { let contract_based_connectors_result = client .calculate_contract_score( profile_id.get_string_repr().into(), contract_based_routing_configs.clone(), "".to_string(), contract_based_connectors, state.get_grpc_headers(), ) .await .attach_printable( "unable to calculate/fetch contract score from dynamic routing service", ); let contract_based_connectors = match contract_based_connectors_result { Ok(resp) => Some(utils::CalContractScoreEventResponse::from(&resp)), Err(err) => match err.current_context() { DynamicRoutingError::ContractNotFound => { client .update_contracts( profile_id.get_string_repr().into(), label_info, "".to_string(), vec![], u64::default(), state.get_grpc_headers(), ) .await .change_context(errors::RoutingError::ContractScoreUpdationError) .attach_printable( "unable to update contract based routing window in dynamic routing service", )?; return Err((errors::RoutingError::ContractScoreCalculationError { err: err.to_string(), }) .into()); } _ => { return Err((errors::RoutingError::ContractScoreCalculationError { err: err.to_string(), }) .into()) } }, }; Ok(contract_based_connectors) }; let events_response = routing_events_wrapper .construct_event_builder( "ContractScoreCalculator.FetchContractScore".to_string(), RoutingEngine::IntelligentRouter, ApiMethod::Grpc, )? .trigger_event(state, closure) .await?; let contract_based_connectors: utils::CalContractScoreEventResponse = events_response .response .ok_or(errors::RoutingError::ContractScoreCalculationError { err: "CalContractScoreEventResponse not found".to_string(), })?; let mut routing_event = events_response .event .ok_or(errors::RoutingError::RoutingEventsError { message: "ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse" .to_string(), status_code: 500, })?; payment_data.set_routing_approach_in_attempt(Some( common_enums::RoutingApproach::ContractBasedRouting, )); let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len()); for label_with_score in contract_based_connectors.labels_with_score { let (connector, merchant_connector_id) = label_with_score.label .split_once(':') .ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string())) .attach_printable( "unable to split connector_name and mca_id from the label obtained by the dynamic routing service", )?; connectors.push(api_routing::RoutableConnectorChoice { choice_kind: api_routing::RoutableChoiceKind::FullStruct, connector: common_enums::RoutableConnectors::from_str(connector) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "RoutableConnectors".to_string(), }) .attach_printable("unable to convert String to RoutableConnectors")?, merchant_connector_id: Some( common_utils::id_type::MerchantConnectorAccountId::wrap( merchant_connector_id.to_string(), ) .change_context(errors::RoutingError::GenericConversionError { from: "String".to_string(), to: "MerchantConnectorAccountId".to_string(), }) .attach_printable("unable to convert MerchantConnectorAccountId from string")?, ), }); } connectors.append(&mut other_connectors); logger::debug!(contract_based_routing_connectors=?connectors); routing_event.set_status_code(200); routing_event.set_routable_connectors(connectors.clone()); routing_event.set_routing_approach(api_routing::RoutingApproach::ContractBased.to_string()); state.event_handler().log_event(&routing_event); Ok(connectors) } else { Ok(routable_connectors) } }
crates/router/src/core/payments/routing.rs#chunk2
router
chunk
4,836
null
null
null
null
null
null
null
null
null
null
null
null
null
Web Documentation: Account setup | Hyperswitch # Type: Web Doc This guide is aimed at helping you create a Hyperswitch account and create payment processors as per your requirement. You can choose any of the following methods for this: Via Control Centre Hosted on Sandbox/Self Hosted Sign up to the control center and configure your Hyperswitch account as per your liking Via Postman collection Run curls in postman and create merchant account and processors through postman 7 months ago Was this helpful?
https://docs.hyperswitch.io/hyperswitch-open-source/account-setup
null
web_doc_file
109
doc
null
null
null
null
null
web
null
null
null
https://docs.hyperswitch.io/hyperswitch-open-source/account-setup
Account setup | Hyperswitch
null
pub struct NexinetsRefundRequest { pub initial_amount: i64, pub currency: enums::Currency, }
crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
hyperswitch_connectors
struct_definition
27
rust
NexinetsRefundRequest
null
null
null
null
null
null
null
null
null
null
null
pub async fn connector_create() {}
crates/openapi/src/routes/merchant_connector_account.rs
openapi
function_signature
7
rust
null
null
null
null
connector_create
null
null
null
null
null
null
null
pub struct AmazonpayErrorResponse { pub reason_code: String, pub message: String, }
crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
hyperswitch_connectors
struct_definition
20
rust
AmazonpayErrorResponse
null
null
null
null
null
null
null
null
null
null
null
impl api::RefundExecute for Datatrans {}
crates/hyperswitch_connectors/src/connectors/datatrans.rs
hyperswitch_connectors
impl_block
11
rust
null
Datatrans
api::RefundExecute for
impl api::RefundExecute for for Datatrans
null
null
null
null
null
null
null
null
pub struct VoltPsyncResponse { status: VoltPaymentStatus, id: String, merchant_internal_reference: Option<String>, }
crates/hyperswitch_connectors/src/connectors/volt/transformers.rs
hyperswitch_connectors
struct_definition
28
rust
VoltPsyncResponse
null
null
null
null
null
null
null
null
null
null
null
impl<T: DatabaseStore + 'static> PaymentMethodsStorageInterface for KVRouterStore<T> {}
crates/payment_methods/src/state.rs
payment_methods
impl_block
20
rust
null
KVRouterStore
PaymentMethodsStorageInterface for
impl PaymentMethodsStorageInterface for for KVRouterStore
null
null
null
null
null
null
null
null
File: crates/external_services/src/managers.rs //! Config and client managers pub mod encryption_management; pub mod secrets_management;
crates/external_services/src/managers.rs
external_services
full_file
27
null
null
null
null
null
null
null
null
null
null
null
null
null
pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static { fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; }
crates/pm_auth/src/types/api.rs
pm_auth
trait_definition
40
rust
null
null
ConnectorIntegrationAny
null
null
null
null
null
null
null
null
null
impl ApiEventMetric for PaymentsRedirectResponseData { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentRedirectionResponse { payment_id: self.payment_id.clone(), }) } }
crates/router/src/events/api_logs.rs
router
impl_block
52
rust
null
PaymentsRedirectResponseData
ApiEventMetric for
impl ApiEventMetric for for PaymentsRedirectResponseData
null
null
null
null
null
null
null
null
pub struct PaysafeCaptureRequest { pub merchant_ref_num: String, #[serde(skip_serializing_if = "Option::is_none")] pub amount: Option<MinorUnit>, }
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
hyperswitch_connectors
struct_definition
39
rust
PaysafeCaptureRequest
null
null
null
null
null
null
null
null
null
null
null
impl common_utils::events::ApiEventMetric for RelayRequest {}
crates/api_models/src/relay.rs
api_models
impl_block
13
rust
null
RelayRequest
common_utils::events::ApiEventMetric for
impl common_utils::events::ApiEventMetric for for RelayRequest
null
null
null
null
null
null
null
null
pub async fn organization_update( state: web::Data<AppState>, req: HttpRequest, org_id: web::Path<common_utils::id_type::OrganizationId>, json_payload: web::Json<admin::OrganizationUpdateRequest>, ) -> HttpResponse { let flow = Flow::OrganizationUpdate; let organization_id = org_id.into_inner(); let org_id = admin::OrganizationId { organization_id: organization_id.clone(), }; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, _, req, _| update_organization(state, org_id.clone(), req), auth::auth_type( &auth::PlatformOrgAdminAuth { is_admin_auth_allowed: true, organization_id: Some(organization_id.clone()), }, &auth::JWTAuthOrganizationFromRoute { organization_id, required_permission: Permission::OrganizationAccountWrite, }, req.headers(), ), api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/routes/admin.rs
router
function_signature
223
rust
null
null
null
null
organization_update
null
null
null
null
null
null
null
impl NewUserOrganization { pub async fn insert_org_in_db(self, state: SessionState) -> UserResult<Organization> { state .accounts_store .insert_organization(self.0) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { e.change_context(UserErrors::DuplicateOrganizationId) } else { e.change_context(UserErrors::InternalServerError) } }) .attach_printable("Error while inserting organization") } pub fn get_organization_id(&self) -> id_type::OrganizationId { self.0.get_organization_id() } }
crates/router/src/types/domain/user.rs
router
impl_block
137
rust
null
NewUserOrganization
null
impl NewUserOrganization
null
null
null
null
null
null
null
null
pub async fn complete_payout_retrieve( state: &SessionState, merchant_context: &domain::MerchantContext, connector_call_type: api::ConnectorCallType, payout_data: &mut PayoutData, ) -> RouterResult<()> { todo!() }
crates/router/src/core/payouts.rs
router
function_signature
58
rust
null
null
null
null
complete_payout_retrieve
null
null
null
null
null
null
null
pub struct Connectors { pub aci: ConnectorParams, pub authipay: ConnectorParams, pub adyen: AdyenParamsWithThreeBaseUrls, pub adyenplatform: ConnectorParams, pub affirm: ConnectorParams, pub airwallex: ConnectorParams, pub amazonpay: ConnectorParams, pub applepay: ConnectorParams, pub archipel: ConnectorParams, pub authorizedotnet: ConnectorParams, pub bambora: ConnectorParams, pub bamboraapac: ConnectorParams, pub bankofamerica: ConnectorParams, pub barclaycard: ConnectorParams, pub billwerk: ConnectorParams, pub bitpay: ConnectorParams, pub blackhawknetwork: ConnectorParams, pub bluecode: ConnectorParams, pub bluesnap: ConnectorParamsWithSecondaryBaseUrl, pub boku: ConnectorParams, pub braintree: ConnectorParams, pub breadpay: ConnectorParams, pub cashtocode: ConnectorParams, pub celero: ConnectorParams, pub chargebee: ConnectorParams, pub checkbook: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub ctp_visa: NoParams, pub custombilling: NoParams, pub cybersource: ConnectorParams, pub datatrans: ConnectorParamsWithSecondaryBaseUrl, pub deutschebank: ConnectorParams, pub digitalvirgo: ConnectorParams, pub dlocal: ConnectorParams, #[cfg(feature = "dummy_connector")] pub dummyconnector: ConnectorParams, pub dwolla: ConnectorParams, pub ebanx: ConnectorParams, pub elavon: ConnectorParams, pub facilitapay: ConnectorParams, pub fiserv: ConnectorParams, pub fiservemea: ConnectorParams, pub fiuu: ConnectorParamsWithThreeUrls, pub flexiti: ConnectorParams, pub forte: ConnectorParams, pub getnet: ConnectorParams, pub globalpay: ConnectorParams, pub globepay: ConnectorParams, pub gocardless: ConnectorParams, pub gpayments: ConnectorParams, pub helcim: ConnectorParams, pub hipay: ConnectorParamsWithThreeUrls, pub hyperswitch_vault: ConnectorParams, pub hyperwallet: ConnectorParams, pub iatapay: ConnectorParams, pub inespay: ConnectorParams, pub itaubank: ConnectorParams, pub jpmorgan: ConnectorParams, pub juspaythreedsserver: ConnectorParams, pub katapult: ConnectorParams, pub klarna: ConnectorParams, pub mifinity: ConnectorParams, pub mollie: ConnectorParams, pub moneris: ConnectorParams, pub mpgs: ConnectorParams, pub multisafepay: ConnectorParams, pub netcetera: ConnectorParams, pub nexinets: ConnectorParams, pub nexixpay: ConnectorParams, pub nmi: ConnectorParams, pub nomupay: ConnectorParams, pub noon: ConnectorParamsWithModeType, pub nordea: ConnectorParams, pub novalnet: ConnectorParams, pub nuvei: ConnectorParams, pub opayo: ConnectorParams, pub opennode: ConnectorParams, pub paybox: ConnectorParamsWithSecondaryBaseUrl, pub payeezy: ConnectorParams, pub payload: ConnectorParams, pub payme: ConnectorParams, pub payone: ConnectorParams, pub paypal: ConnectorParams, pub paysafe: ConnectorParams, pub paystack: ConnectorParams, pub paytm: ConnectorParams, pub payu: ConnectorParams, pub phonepe: ConnectorParams, pub placetopay: ConnectorParams, pub plaid: ConnectorParams, pub powertranz: ConnectorParams, pub prophetpay: ConnectorParams, pub rapyd: ConnectorParams, pub razorpay: ConnectorParamsWithKeys, pub recurly: ConnectorParams, pub redsys: ConnectorParams, pub riskified: ConnectorParams, pub santander: ConnectorParams, pub shift4: ConnectorParams, pub sift: ConnectorParams, pub silverflow: ConnectorParams, pub signifyd: ConnectorParams, pub square: ConnectorParams, pub stax: ConnectorParams, pub stripe: ConnectorParamsWithFileUploadUrl, pub stripebilling: ConnectorParams, pub taxjar: ConnectorParams, pub threedsecureio: ConnectorParams, pub thunes: ConnectorParams, pub tokenio: ConnectorParams, pub trustpay: ConnectorParamsWithMoreUrls, pub trustpayments: ConnectorParams, pub tsys: ConnectorParams, pub unified_authentication_service: ConnectorParams, pub vgs: ConnectorParams, pub volt: ConnectorParams, pub wellsfargo: ConnectorParams, pub wellsfargopayout: ConnectorParams, pub wise: ConnectorParams, pub worldline: ConnectorParams, pub worldpay: ConnectorParams, pub worldpayvantiv: ConnectorParamsWithThreeUrls, pub worldpayxml: ConnectorParams, pub xendit: ConnectorParams, pub zen: ConnectorParams, pub zsl: ConnectorParams, }
crates/hyperswitch_domain_models/src/connector_endpoints.rs
hyperswitch_domain_models
struct_definition
1,135
rust
Connectors
null
null
null
null
null
null
null
null
null
null
null
pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()
crates/common_utils/src/signals.rs
common_utils
function_signature
23
rust
null
null
null
null
signal_handler
null
null
null
null
null
null
null
pub struct PaymentsCaptureData { pub amount_to_capture: i64, pub currency: storage_enums::Currency, pub connector_transaction_id: String, pub payment_amount: i64, pub multiple_capture_data: Option<MultipleCaptureRequestData>, pub connector_meta: Option<serde_json::Value>, pub browser_info: Option<BrowserInformation>, pub metadata: Option<serde_json::Value>, // This metadata is used to store the metadata shared during the payment intent request. pub capture_method: Option<storage_enums::CaptureMethod>, pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, // New amount for amount frame work pub minor_payment_amount: MinorUnit, pub minor_amount_to_capture: MinorUnit, pub integrity_object: Option<CaptureIntegrityObject>, pub webhook_url: Option<String>, }
crates/hyperswitch_domain_models/src/router_request_types.rs
hyperswitch_domain_models
struct_definition
185
rust
PaymentsCaptureData
null
null
null
null
null
null
null
null
null
null
null
pub fn get_index_for_correct_recovery_code( candidate: &Secret<String>, recovery_codes: &[Secret<String>], ) -> CustomResult<Option<usize>, UserErrors> { for (index, recovery_code) in recovery_codes.iter().enumerate() { let is_match = is_correct_password(candidate, recovery_code)?; if is_match { return Ok(Some(index)); } } Ok(None) }
crates/router/src/utils/user/password.rs
router
function_signature
85
rust
null
null
null
null
get_index_for_correct_recovery_code
null
null
null
null
null
null
null
pub struct WellsfargoAuthorizationOptions { initiator: Option<WellsfargoPaymentInitiator>, merchant_intitiated_transaction: Option<MerchantInitiatedTransaction>, }
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
hyperswitch_connectors
struct_definition
35
rust
WellsfargoAuthorizationOptions
null
null
null
null
null
null
null
null
null
null
null
pub async fn retrieve_payment_method_from_vault_using_payment_token( state: &routes::SessionState, merchant_context: &domain::MerchantContext, profile: &domain::Profile, payment_token: &String, payment_method_type: &common_enums::PaymentMethod, ) -> RouterResult<(domain::PaymentMethod, domain::PaymentMethodVaultingData)> { let pm_token_data = utils::retrieve_payment_token_data( state, payment_token.to_string(), Some(payment_method_type), ) .await?; let payment_method_id = match pm_token_data { storage::PaymentTokenData::PermanentCard(card_token_data) => { card_token_data.payment_method_id } storage::PaymentTokenData::TemporaryGeneric(_) => { Err(errors::ApiErrorResponse::NotImplemented { message: errors::NotImplementedMessage::Reason( "TemporaryGeneric Token not implemented".to_string(), ), })? } storage::PaymentTokenData::AuthBankDebit(_) => { Err(errors::ApiErrorResponse::NotImplemented { message: errors::NotImplementedMessage::Reason( "AuthBankDebit Token not implemented".to_string(), ), })? } }; let db = &*state.store; let key_manager_state = &state.into(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let payment_method = db .find_payment_method( key_manager_state, merchant_context.get_merchant_key_store(), &payment_method_id, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let vault_data = retrieve_payment_method_from_vault(state, merchant_context, profile, &payment_method) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to retrieve payment method from vault")? .data; Ok((payment_method, vault_data)) }
crates/router/src/core/payment_methods/vault.rs
router
function_signature
415
rust
null
null
null
null
retrieve_payment_method_from_vault_using_payment_token
null
null
null
null
null
null
null
File: crates/api_models/src/proxy.rs Public functions: 2 Public structs: 3 use std::collections::HashMap; use common_utils::request::Method; use reqwest::header::HeaderMap; use serde::{Deserialize, Serialize}; use serde_json::Value; use utoipa::ToSchema; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Headers(pub HashMap<String, String>); impl Headers { pub fn as_map(&self) -> &HashMap<String, String> { &self.0 } pub fn from_header_map(headers: Option<&HeaderMap>) -> Self { headers .map(|h| { let map = h .iter() .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())) .collect(); Self(map) }) .unwrap_or_else(|| Self(HashMap::new())) } } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct ProxyRequest { /// The request body that needs to be forwarded pub request_body: Value, /// The destination URL where the request needs to be forwarded #[schema(value_type = String, example = "https://api.example.com/endpoint")] pub destination_url: url::Url, /// The headers that need to be forwarded #[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub headers: Headers, /// The method that needs to be used for the request #[schema(value_type = Method, example = "Post")] pub method: Method, /// The vault token that is used to fetch sensitive data from the vault pub token: String, /// The type of token that is used to fetch sensitive data from the vault #[schema(value_type = TokenType, example = "payment_method_id")] pub token_type: TokenType, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum TokenType { TokenizationId, PaymentMethodId, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct ProxyResponse { /// The response received from the destination pub response: Value, /// The status code of the response pub status_code: u16, /// The headers of the response #[schema(value_type = Object, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub response_headers: Headers, } impl common_utils::events::ApiEventMetric for ProxyRequest {} impl common_utils::events::ApiEventMetric for ProxyResponse {}
crates/api_models/src/proxy.rs
api_models
full_file
584
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct DatatransSuccessResponse { pub transaction_id: String, pub acquirer_authorization_code: String, }
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
hyperswitch_connectors
struct_definition
26
rust
DatatransSuccessResponse
null
null
null
null
null
null
null
null
null
null
null
pub async fn update_payment_method_and_last_used( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, db: &dyn db::StorageInterface, pm: domain::PaymentMethod, payment_method_update: Option<Encryption>, storage_scheme: MerchantStorageScheme, card_scheme: Option<String>, ) -> errors::CustomResult<(), errors::VaultError> { let pm_update = payment_method::PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed { payment_method_data: payment_method_update, scheme: card_scheme, last_used_at: common_utils::date_time::now(), }; db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme) .await .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?; Ok(()) }
crates/router/src/core/payment_methods/cards.rs
router
function_signature
179
rust
null
null
null
null
update_payment_method_and_last_used
null
null
null
null
null
null
null
File: crates/test_utils/tests/connectors/checkout_ui.rs use serial_test::serial; use thirtyfour::{prelude::*, WebDriver}; use crate::{selenium::*, tester}; struct CheckoutSeleniumTest; impl SeleniumTest for CheckoutSeleniumTest { fn get_connector_name(&self) -> String { "checkout".to_string() } } async fn should_make_frictionless_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { let mycon = CheckoutSeleniumTest {}; mycon .make_redirection_payment( c, vec![ Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/18"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Assert(Assert::IsPresent("Google Search")), Event::Trigger(Trigger::Sleep(5)), //url gets updated only after some time, so need this timeout to solve the issue Event::Assert(Assert::ContainsAny( Selector::QueryParamStr, vec!["status=succeeded", "status=processing"], )), ], ) .await?; Ok(()) } async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { let mycon = CheckoutSeleniumTest {}; mycon .make_redirection_payment( c, vec![ Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/20"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Trigger(Trigger::Sleep(5)), //url gets updated only after some time, so need this timeout to solve the issue Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))), Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")), Event::Trigger(Trigger::Click(By::Id("txtButton"))), Event::Trigger(Trigger::Sleep(2)), Event::Assert(Assert::IsPresent("Google")), Event::Assert(Assert::ContainsAny( Selector::QueryParamStr, vec!["status=succeeded", "status=processing"], )), ], ) .await?; Ok(()) } async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> { let mycon = CheckoutSeleniumTest {}; mycon .make_redirection_payment( c, vec![ Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/73"))), Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), Event::Trigger(Trigger::Sleep(10)), //url gets updated only after some time, so need this timeout to solve the issue Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))), Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")), Event::Trigger(Trigger::Click(By::Id("txtButton"))), Event::Assert(Assert::IsPresent("Google")), Event::Assert(Assert::ContainsAny( Selector::QueryParamStr, vec!["status=succeeded", "status=processing"], )), ], ) .await?; Ok(()) } #[test] #[serial] fn should_make_frictionless_3ds_payment_test() { tester!(should_make_frictionless_3ds_payment); } #[test] #[serial] fn should_make_3ds_payment_test() { tester!(should_make_3ds_payment); } #[test] #[serial] #[ignore] fn should_make_gpay_payment_test() { tester!(should_make_gpay_payment); }
crates/test_utils/tests/connectors/checkout_ui.rs
test_utils
full_file
809
null
null
null
null
null
null
null
null
null
null
null
null
null
pub struct MandatePaymentInformation { payment_instrument: WellsfargoPaymentInstrument, }
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
hyperswitch_connectors
struct_definition
19
rust
MandatePaymentInformation
null
null
null
null
null
null
null
null
null
null
null
File: crates/router/src/core/fraud_check/types.rs Public structs: 12 use api_models::{ enums as api_enums, enums::{PaymentMethod, PaymentMethodType}, payments::Amount, refunds::RefundResponse, }; use common_enums::FrmSuggestion; use common_utils::pii::SecretSerdeValue; use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent}; pub use hyperswitch_domain_models::{ router_request_types::fraud_check::{ Address, Destination, FrmFulfillmentRequest, FulfillmentStatus, Fulfillments, Product, }, types::OrderDetailsWithAmount, }; use masking::Serialize; use serde::Deserialize; use utoipa::ToSchema; use super::operation::BoxedFraudCheckOperation; use crate::types::{ domain::MerchantAccount, storage::{enums as storage_enums, fraud_check::FraudCheck}, PaymentAddress, }; #[derive(Clone, Default, Debug)] pub struct PaymentIntentCore { pub payment_id: common_utils::id_type::PaymentId, } #[derive(Clone, Debug)] pub struct PaymentAttemptCore { pub attempt_id: String, pub payment_details: Option<PaymentDetails>, pub amount: Amount, } #[derive(Clone, Debug, Serialize)] pub struct PaymentDetails { pub amount: i64, pub currency: Option<storage_enums::Currency>, pub payment_method: Option<PaymentMethod>, pub payment_method_type: Option<PaymentMethodType>, pub refund_transaction_id: Option<String>, } #[derive(Clone, Default, Debug)] pub struct FrmMerchantAccount { pub merchant_id: common_utils::id_type::MerchantId, } #[derive(Clone, Debug)] pub struct FrmData { pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub merchant_account: MerchantAccount, pub fraud_check: FraudCheck, pub address: PaymentAddress, pub connector_details: ConnectorDetailsCore, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub refund: Option<RefundResponse>, pub frm_metadata: Option<SecretSerdeValue>, } #[derive(Debug)] pub struct FrmInfo<F, D> { pub fraud_check_operation: BoxedFraudCheckOperation<F, D>, pub frm_data: Option<FrmData>, pub suggested_action: Option<FrmSuggestion>, } #[derive(Clone, Debug)] pub struct ConnectorDetailsCore { pub connector_name: String, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Clone)] pub struct PaymentToFrmData { pub amount: Amount, pub payment_intent: PaymentIntent, pub payment_attempt: PaymentAttempt, pub merchant_account: MerchantAccount, pub address: PaymentAddress, pub connector_details: ConnectorDetailsCore, pub order_details: Option<Vec<OrderDetailsWithAmount>>, pub frm_metadata: Option<SecretSerdeValue>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FrmConfigsObject { pub frm_enabled_pm: Option<PaymentMethod>, pub frm_enabled_gateway: Option<api_models::enums::Connector>, pub frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes, } #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct FrmFulfillmentSignifydApiRequest { ///unique order_id for the order_details in the transaction #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")] pub order_id: String, ///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED #[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")] pub fulfillment_status: Option<FulfillmentStatus>, ///contains details of the fulfillment #[schema(value_type = Vec<Fulfillments>)] pub fulfillments: Vec<Fulfillments>, } #[derive(Debug, ToSchema, Clone, Serialize)] pub struct FrmFulfillmentResponse { ///unique order_id for the transaction #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")] pub order_id: String, ///shipment_ids used in the fulfillment overall...also data from previous fulfillments for the same transactions/order is sent #[schema(example = r#"["ship_101", "ship_102"]"#)] pub shipment_ids: Vec<String>, } #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde_with::skip_serializing_none] #[serde(rename_all = "camelCase")] pub struct FrmFulfillmentSignifydApiResponse { ///unique order_id for the transaction #[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")] pub order_id: String, ///shipment_ids used in the fulfillment overall...also data from previous fulfillments for the same transactions/order is sent #[schema(example = r#"["ship_101","ship_102"]"#)] pub shipment_ids: Vec<String>, } pub const CANCEL_INITIATED: &str = "Cancel Initiated with the processor";
crates/router/src/core/fraud_check/types.rs
router
full_file
1,160
null
null
null
null
null
null
null
null
null
null
null
null
null
impl Novalnet { pub fn new() -> &'static Self { &Self { amount_converter: &StringMinorUnitForConnector, } } }
crates/hyperswitch_connectors/src/connectors/novalnet.rs
hyperswitch_connectors
impl_block
35
rust
null
Novalnet
null
impl Novalnet
null
null
null
null
null
null
null
null
pub fn program<O: EuclidParsable + 'static>(input: &str) -> ParseResult<&str, ast::Program<O>> { error::context( "program", combinator::map( sequence::pair(default_output, multi::many1(skip_ws(rule::<O>))), |tup: (O, Vec<ast::Rule<O>>)| ast::Program { default_selection: tup.0, rules: tup.1, metadata: std::collections::HashMap::new(), }, ), )(input) }
crates/euclid/src/frontend/ast/parser.rs
euclid
function_signature
119
rust
null
null
null
null
program
null
null
null
null
null
null
null
pub async fn customers_delete() {}
crates/openapi/src/routes/customers.rs
openapi
function_signature
7
rust
null
null
null
null
customers_delete
null
null
null
null
null
null
null
pub async fn get_profile_connector_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Query<api_models::analytics::connector_events::ConnectorEventsRequest>, ) -> impl Responder { let flow = AnalyticsFlow::GetConnectorEvents; Box::pin(api::server_wrap( flow, state, &req, json_payload.into_inner(), |state, auth: AuthenticationData, req, _| async move { utils::check_if_profile_id_is_present_in_payment_intent( req.payment_id.clone(), &state, &auth, ) .await .change_context(AnalyticsError::AccessForbiddenError)?; connector_events_core(&state.pool, req, auth.merchant_account.get_id()) .await .map(ApplicationResponse::Json) }, &auth::JWTAuth { permission: Permission::ProfileAnalyticsRead, }, api_locking::LockAction::NotApplicable, )) .await }
crates/router/src/analytics.rs
router
function_signature
218
rust
null
null
null
null
get_profile_connector_events
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/nuvei.rs Public functions: 1 Public structs: 1 pub mod transformers; use std::sync::LazyLock; use api_models::{payments::PaymentIdType, webhooks::IncomingWebhookEvent}; use common_enums::{enums, CallConnectorAction, PaymentAction}; use common_utils::{ crypto, errors::{CustomResult, ReportSwitchExt}, ext_traits::{ByteSliceExt, BytesExt, ValueExt}, id_type, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::PaymentMethodData, router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, AuthorizeSessionToken, CompleteAuthorize, PostCaptureVoid, PreProcessing, }, router_request_types::{ AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData, PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks::{IncomingWebhook, IncomingWebhookRequestDetails}, }; use masking::ExposeInterface; use transformers as nuvei; use crate::{ constants::headers, types::ResponseRouterData, utils::{self, is_mandate_supported, PaymentMethodDataType, RouterData as _}, }; #[derive(Clone)] pub struct Nuvei { pub amount_convertor: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Nuvei { pub fn new() -> &'static Self { &Self { amount_convertor: &StringMajorUnitForConnector, } } } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nuvei where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, _req: &RouterData<Flow, Request, Response>, _connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let headers = vec![( headers::CONTENT_TYPE.to_string(), self.get_content_type().to_string().into(), )]; Ok(headers) } } impl ConnectorCommon for Nuvei { fn id(&self) -> &'static str { "nuvei" } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.nuvei.base_url.as_ref() } fn get_auth_header( &self, _auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } } impl ConnectorValidation for Nuvei { fn validate_mandate_payment( &self, pm_type: Option<enums::PaymentMethodType>, pm_data: PaymentMethodData, ) -> CustomResult<(), errors::ConnectorError> { let mandate_supported_pmd = std::collections::HashSet::from([ PaymentMethodDataType::Card, PaymentMethodDataType::GooglePay, PaymentMethodDataType::ApplePay, PaymentMethodDataType::NetworkTransactionIdAndCardDetails, ]); is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) } } impl api::Payment for Nuvei {} impl api::PaymentToken for Nuvei {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Nuvei { // Not Implemented (R) } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nuvei {} impl api::MandateSetup for Nuvei {} impl api::PaymentVoid for Nuvei {} impl api::PaymentSync for Nuvei {} impl api::PaymentCapture for Nuvei {} impl api::PaymentSession for Nuvei {} impl api::PaymentAuthorize for Nuvei {} impl api::PaymentAuthorizeSessionToken for Nuvei {} impl api::Refund for Nuvei {} impl api::RefundExecute for Nuvei {} impl api::RefundSync for Nuvei {} impl api::PaymentsCompleteAuthorize for Nuvei {} impl api::ConnectorAccessToken for Nuvei {} impl api::PaymentsPreProcessing for Nuvei {} impl api::PaymentPostCaptureVoid for Nuvei {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/payment.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::SetupMandateType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::SetupMandateType::get_headers(self, req, connectors)?) .set_body(types::SetupMandateType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>, errors::ConnectorError, > { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/payment.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsCompleteAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let meta: nuvei::NuveiMeta = utils::to_connector_meta(req.request.connector_meta.clone())?; let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, meta.session_token))?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCompleteAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/voidTransaction.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentFlowRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &PaymentsCancelPostCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCancelPostCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/voidTransaction.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsCancelPostCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiVoidRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelPostCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsPostCaptureVoidType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPostCaptureVoidType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsPostCaptureVoidType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &PaymentsCancelPostCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelPostCaptureRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nuvei {} impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/getPaymentStatus.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentSyncRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .set_body(types::PaymentsSyncType::get_request_body( self, req, connectors, )?) .build(), )) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/settleTransaction.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentFlowRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/payment.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &PaymentsAuthorizeSessionTokenRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeSessionTokenRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/getSessionToken.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsAuthorizeSessionTokenRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiSessionRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeSessionTokenRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsPreAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPreAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsPreAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeSessionTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> { let response: nuvei::NuveiSessionResponse = res.response.parse_struct("NuveiSessionResponse").switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Nuvei { fn get_headers( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/initPayment.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsPreProcessingType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsPreProcessingType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nuvei { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}ppp/api/v1/refundTransaction.do", ConnectorCommon::base_url(self, connectors) )) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = nuvei::NuveiPaymentFlowRequest::try_from(req)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: nuvei::NuveiPaymentsResponse = res .response .parse_struct("NuveiPaymentsResponse") .switch()?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nuvei {} #[async_trait::async_trait] impl IncomingWebhook for Nuvei { fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> { Ok(Box::new(crypto::Sha256)) } fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { let signature = utils::get_header_key_value("advanceResponseChecksum", request.headers)?; hex::decode(signature).change_context(errors::ConnectorError::WebhookResponseEncodingFailed) } fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &id_type::MerchantId, connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, errors::ConnectorError> { // Parse the webhook payload let webhook = serde_urlencoded::from_str::<nuvei::NuveiWebhook>(&request.query_params) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let secret_str = std::str::from_utf8(&connector_webhook_secrets.secret) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; // Generate signature based on webhook type match webhook { nuvei::NuveiWebhook::PaymentDmn(notification) => { // For payment DMNs, use the same format as before let status = notification .transaction_status .as_ref() .map(|s| format!("{s:?}").to_uppercase()) .unwrap_or_else(|| "UNKNOWN".to_string()); let to_sign = transformers::concat_strings(&[ secret_str.to_string(), notification.total_amount.unwrap_or_default(), notification.currency.unwrap_or_default(), notification.response_time_stamp.unwrap_or_default(), notification.ppp_transaction_id.unwrap_or_default(), status, notification.product_id.unwrap_or_default(), ]); Ok(to_sign.into_bytes()) } nuvei::NuveiWebhook::Chargeback(notification) => { // For chargeback notifications, use a different format based on Nuvei's documentation // Note: This is a placeholder - you'll need to adjust based on Nuvei's actual chargeback signature format let status = notification .status .as_ref() .map(|s| format!("{s:?}").to_uppercase()) .unwrap_or_else(|| "UNKNOWN".to_string()); let to_sign = transformers::concat_strings(&[ secret_str.to_string(), notification.chargeback_amount.unwrap_or_default(), notification.chargeback_currency.unwrap_or_default(), notification.ppp_transaction_id.unwrap_or_default(), status, ]); Ok(to_sign.into_bytes()) } } } fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { // Parse the webhook payload
crates/hyperswitch_connectors/src/connectors/nuvei.rs#chunk0
hyperswitch_connectors
chunk
8,172
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn create_email_client( settings: &settings::Settings<RawSecret>, ) -> Box<dyn EmailService> { match &settings.email.client_config { EmailClientConfigs::Ses { aws_ses } => Box::new( AwsSes::create( &settings.email, aws_ses, settings.proxy.https_url.to_owned(), ) .await, ), EmailClientConfigs::Smtp { smtp } => { Box::new(SmtpServer::create(&settings.email, smtp.clone()).await) } EmailClientConfigs::NoEmailClient => Box::new(NoEmailClient::create().await), } }
crates/router/src/routes/app.rs
router
function_signature
142
rust
null
null
null
null
create_email_client
null
null
null
null
null
null
null
impl api::PaymentAuthorize for Ebanx {}
crates/hyperswitch_connectors/src/connectors/ebanx.rs
hyperswitch_connectors
impl_block
10
rust
null
Ebanx
api::PaymentAuthorize for
impl api::PaymentAuthorize for for Ebanx
null
null
null
null
null
null
null
null
pub async fn get_metrics( pool: &AnalyticsProvider, ex_rates: &Option<ExchangeRates>, auth: &AuthInfo, req: GetRefundMetricRequest, ) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>> { let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> = HashMap::new(); let mut set = tokio::task::JoinSet::new(); for metric_type in req.metrics.iter().cloned() { let req = req.clone(); let pool = pool.clone(); let task_span = tracing::debug_span!( "analytics_refund_query", refund_metric = metric_type.as_ref() ); // Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference // We can optimize away this clone once that is fixed let auth_scoped = auth.to_owned(); set.spawn( async move { let data = pool .get_refund_metrics( &metric_type, &req.group_by_names.clone(), &auth_scoped, &req.filters, req.time_series.map(|t| t.granularity), &req.time_range, ) .await .change_context(AnalyticsError::UnknownError); TaskType::MetricTask(metric_type, data) } .instrument(task_span), ); } if let Some(distribution) = req.clone().distribution { let req = req.clone(); let pool = pool.clone(); let task_span = tracing::debug_span!( "analytics_refunds_distribution_query", refund_distribution = distribution.distribution_for.as_ref() ); let auth_scoped = auth.to_owned(); set.spawn( async move { let data = pool .get_refund_distribution( &distribution, &req.group_by_names.clone(), &auth_scoped, &req.filters, &req.time_series.map(|t| t.granularity), &req.time_range, ) .await .change_context(AnalyticsError::UnknownError); TaskType::DistributionTask(distribution.distribution_for, data) } .instrument(task_span), ); } while let Some(task_type) = set .join_next() .await .transpose() .change_context(AnalyticsError::UnknownError)? { match task_type { TaskType::MetricTask(metric, data) => { let data = data?; let attributes = router_env::metric_attributes!( ("metric_type", metric.to_string()), ("source", pool.to_string()), ); let value = u64::try_from(data.len()); if let Ok(val) = value { metrics::BUCKETS_FETCHED.record(val, attributes); logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); } for (id, value) in data { logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}"); let metrics_builder = metrics_accumulator.entry(id).or_default(); match metric { RefundMetrics::RefundSuccessRate | RefundMetrics::SessionizedRefundSuccessRate => metrics_builder .refund_success_rate .add_metrics_bucket(&value), RefundMetrics::RefundCount | RefundMetrics::SessionizedRefundCount => { metrics_builder.refund_count.add_metrics_bucket(&value) } RefundMetrics::RefundSuccessCount | RefundMetrics::SessionizedRefundSuccessCount => { metrics_builder.refund_success.add_metrics_bucket(&value) } RefundMetrics::RefundProcessedAmount | RefundMetrics::SessionizedRefundProcessedAmount => { metrics_builder.processed_amount.add_metrics_bucket(&value) } RefundMetrics::SessionizedRefundReason => { metrics_builder.refund_reason.add_metrics_bucket(&value) } RefundMetrics::SessionizedRefundErrorMessage => metrics_builder .refund_error_message .add_metrics_bucket(&value), } } logger::debug!( "Analytics Accumulated Results: metric: {}, results: {:#?}", metric, metrics_accumulator ); } TaskType::DistributionTask(distribution, data) => { let data = data?; let attributes = router_env::metric_attributes!( ("distribution_type", distribution.to_string()), ("source", pool.to_string()), ); let value = u64::try_from(data.len()); if let Ok(val) = value { metrics::BUCKETS_FETCHED.record(val, attributes); logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val); } for (id, value) in data { logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for distribution {distribution}"); let metrics_builder = metrics_accumulator.entry(id).or_default(); match distribution { RefundDistributions::SessionizedRefundReason => metrics_builder .refund_reason_distribution .add_distribution_bucket(&value), RefundDistributions::SessionizedRefundErrorMessage => metrics_builder .refund_error_message_distribution .add_distribution_bucket(&value), } } logger::debug!( "Analytics Accumulated Results: distribution: {}, results: {:#?}", distribution, metrics_accumulator ); } } } let mut success = 0; let mut total = 0; let mut total_refund_processed_amount = 0; let mut total_refund_processed_amount_in_usd = 0; let mut total_refund_processed_count = 0; let mut total_refund_reason_count = 0; let mut total_refund_error_message_count = 0; let query_data: Vec<RefundMetricsBucketResponse> = metrics_accumulator .into_iter() .map(|(id, val)| { let mut collected_values = val.collect(); if let Some(success_count) = collected_values.successful_refunds { success += success_count; } if let Some(total_count) = collected_values.total_refunds { total += total_count; } if let Some(amount) = collected_values.refund_processed_amount { let amount_in_usd = if let Some(ex_rates) = ex_rates { id.currency .and_then(|currency| { i64::try_from(amount) .inspect_err(|e| logger::error!("Amount conversion error: {:?}", e)) .ok() .and_then(|amount_i64| { convert(ex_rates, currency, Currency::USD, amount_i64) .inspect_err(|e| { logger::error!("Currency conversion error: {:?}", e) }) .ok() }) }) .map(|amount| (amount * rust_decimal::Decimal::new(100, 0)).to_u64()) .unwrap_or_default() } else { None }; collected_values.refund_processed_amount_in_usd = amount_in_usd; total_refund_processed_amount += amount; total_refund_processed_amount_in_usd += amount_in_usd.unwrap_or(0); } if let Some(count) = collected_values.refund_processed_count { total_refund_processed_count += count; } if let Some(total_count) = collected_values.refund_reason_count { total_refund_reason_count += total_count; } if let Some(total_count) = collected_values.refund_error_message_count { total_refund_error_message_count += total_count; } RefundMetricsBucketResponse { values: collected_values, dimensions: id, } }) .collect(); let total_refund_success_rate = match (success, total) { (s, t) if t > 0 => Some(f64::from(s) * 100.0 / f64::from(t)), _ => None, }; Ok(RefundsMetricsResponse { query_data, meta_data: [RefundsAnalyticsMetadata { total_refund_success_rate, total_refund_processed_amount: Some(total_refund_processed_amount), total_refund_processed_amount_in_usd: if ex_rates.is_some() { Some(total_refund_processed_amount_in_usd) } else { None }, total_refund_processed_count: Some(total_refund_processed_count), total_refund_reason_count: Some(total_refund_reason_count), total_refund_error_message_count: Some(total_refund_error_message_count), }], }) }
crates/analytics/src/refunds/core.rs
analytics
function_signature
1,851
rust
null
null
null
null
get_metrics
null
null
null
null
null
null
null
pub struct RiskifiedAuthType { pub secret_token: Secret<String>, pub domain_name: String, }
crates/hyperswitch_connectors/src/connectors/riskified/transformers/auth.rs
hyperswitch_connectors
struct_definition
23
rust
RiskifiedAuthType
null
null
null
null
null
null
null
null
null
null
null
File: crates/diesel_models/src/callback_mapper.rs Public structs: 1 use common_enums::enums as common_enums; use common_types::callback_mapper::CallbackMapperData; use diesel::{Identifiable, Insertable, Queryable, Selectable}; use crate::schema::callback_mapper; #[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)] #[diesel(table_name = callback_mapper, primary_key(id, type_), check_for_backend(diesel::pg::Pg))] pub struct CallbackMapper { pub id: String, pub type_: common_enums::CallbackMapperIdType, pub data: CallbackMapperData, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, }
crates/diesel_models/src/callback_mapper.rs
diesel_models
full_file
164
null
null
null
null
null
null
null
null
null
null
null
null
null
impl GenericLinkInterface for KafkaStore { async fn find_generic_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { self.diesel_store .find_generic_link_by_link_id(link_id) .await } async fn find_pm_collect_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { self.diesel_store .find_pm_collect_link_by_link_id(link_id) .await } async fn find_payout_link_by_link_id( &self, link_id: &str, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store.find_payout_link_by_link_id(link_id).await } async fn insert_generic_link( &self, generic_link: storage::GenericLinkNew, ) -> CustomResult<storage::GenericLinkState, errors::StorageError> { self.diesel_store.insert_generic_link(generic_link).await } async fn insert_pm_collect_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> { self.diesel_store .insert_pm_collect_link(pm_collect_link) .await } async fn insert_payout_link( &self, pm_collect_link: storage::GenericLinkNew, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store.insert_payout_link(pm_collect_link).await } async fn update_payout_link( &self, payout_link: storage::PayoutLink, payout_link_update: storage::PayoutLinkUpdate, ) -> CustomResult<storage::PayoutLink, errors::StorageError> { self.diesel_store .update_payout_link(payout_link, payout_link_update) .await } }
crates/router/src/db/kafka_store.rs
router
impl_block
450
rust
null
KafkaStore
GenericLinkInterface for
impl GenericLinkInterface for for KafkaStore
null
null
null
null
null
null
null
null
File: crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs Public structs: 17 use common_enums::enums; use common_utils::{ ext_traits::OptionExt, request::Method, types::{FloatMajorUnit, MinorUnit}, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types, }; use hyperswitch_interfaces::{consts::NO_ERROR_CODE, errors}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{PaymentsAuthorizeRequestData, RouterData as _}, }; #[derive(Debug, Serialize)] pub struct RapydRouterData<T> { pub amount: FloatMajorUnit, pub router_data: T, } impl<T> From<(FloatMajorUnit, T)> for RapydRouterData<T> { fn from((amount, router_data): (FloatMajorUnit, T)) -> Self { Self { amount, router_data, } } } #[derive(Default, Debug, Serialize)] pub struct RapydPaymentsRequest { pub amount: FloatMajorUnit, pub currency: enums::Currency, pub payment_method: PaymentMethod, pub payment_method_options: Option<PaymentMethodOptions>, pub merchant_reference_id: Option<String>, pub capture: Option<bool>, pub description: Option<String>, pub complete_payment_url: Option<String>, pub error_payment_url: Option<String>, } #[derive(Default, Debug, Serialize)] pub struct PaymentMethodOptions { #[serde(rename = "3d_required")] pub three_ds: bool, } #[derive(Default, Debug, Serialize)] pub struct PaymentMethod { #[serde(rename = "type")] pub pm_type: String, pub fields: Option<PaymentFields>, pub address: Option<Address>, pub digital_wallet: Option<RapydWallet>, } #[derive(Default, Debug, Serialize)] pub struct PaymentFields { pub number: cards::CardNumber, pub expiration_month: Secret<String>, pub expiration_year: Secret<String>, pub name: Secret<String>, pub cvv: Secret<String>, } #[derive(Default, Debug, Serialize)] pub struct Address { name: Secret<String>, line_1: Secret<String>, line_2: Option<Secret<String>>, line_3: Option<Secret<String>>, city: Option<String>, state: Option<Secret<String>>, country: Option<String>, zip: Option<Secret<String>>, phone_number: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RapydWallet { #[serde(rename = "type")] payment_type: String, #[serde(rename = "details")] token: Option<Secret<String>>, } impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RapydRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let (capture, payment_method_options) = match item.router_data.payment_method { enums::PaymentMethod::Card => { let three_ds_enabled = matches!( item.router_data.auth_type, enums::AuthenticationType::ThreeDs ); let payment_method_options = PaymentMethodOptions { three_ds: three_ds_enabled, }; ( Some(matches!( item.router_data.request.capture_method, Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic) | None )), Some(payment_method_options), ) } _ => (None, None), }; let payment_method = match item.router_data.request.payment_method_data { PaymentMethodData::Card(ref ccard) => { Some(PaymentMethod { pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country fields: Some(PaymentFields { number: ccard.card_number.to_owned(), expiration_month: ccard.card_exp_month.to_owned(), expiration_year: ccard.card_exp_year.to_owned(), name: item .router_data .get_optional_billing_full_name() .to_owned() .unwrap_or(Secret::new("".to_string())), cvv: ccard.card_cvc.to_owned(), }), address: None, digital_wallet: None, }) } PaymentMethodData::Wallet(ref wallet_data) => { let digital_wallet = match wallet_data { WalletData::GooglePay(data) => Some(RapydWallet { payment_type: "google_pay".to_string(), token: Some(Secret::new( data.tokenization_data .get_encrypted_google_pay_token() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "gpay wallet_token", })? .to_owned(), )), }), WalletData::ApplePay(data) => { let apple_pay_encrypted_data = data .payment_data .get_encrypted_apple_pay_payment_data_mandatory() .change_context(errors::ConnectorError::MissingRequiredField { field_name: "Apple pay encrypted data", })?; Some(RapydWallet { payment_type: "apple_pay".to_string(), token: Some(Secret::new(apple_pay_encrypted_data.to_string())), }) } _ => None, }; Some(PaymentMethod { pm_type: "by_visa_card".to_string(), //[#369] fields: None, address: None, digital_wallet, }) } _ => None, } .get_required_value("payment_method not implemented") .change_context(errors::ConnectorError::NotImplemented( "payment_method".to_owned(), ))?; let return_url = item.router_data.request.get_router_return_url()?; Ok(Self { amount: item.amount, currency: item.router_data.request.currency, payment_method, capture, payment_method_options, merchant_reference_id: Some(item.router_data.connector_request_reference_id.clone()), description: None, error_payment_url: Some(return_url.clone()), complete_payment_url: Some(return_url), }) } } #[derive(Debug, Deserialize)] pub struct RapydAuthType { pub access_key: Secret<String>, pub secret_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for RapydAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type { Ok(Self { access_key: api_key.to_owned(), secret_key: key1.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[allow(clippy::upper_case_acronyms)] pub enum RapydPaymentStatus { #[serde(rename = "ACT")] Active, #[serde(rename = "CAN")] CanceledByClientOrBank, #[serde(rename = "CLO")] Closed, #[serde(rename = "ERR")] Error, #[serde(rename = "EXP")] Expired, #[serde(rename = "REV")] ReversedByRapyd, #[default] #[serde(rename = "NEW")] New, } fn get_status(status: RapydPaymentStatus, next_action: NextAction) -> enums::AttemptStatus { match (status, next_action) { (RapydPaymentStatus::Closed, _) => enums::AttemptStatus::Charged, ( RapydPaymentStatus::Active, NextAction::ThreedsVerification | NextAction::PendingConfirmation, ) => enums::AttemptStatus::AuthenticationPending, (RapydPaymentStatus::Active, NextAction::PendingCapture | NextAction::NotApplicable) => { enums::AttemptStatus::Authorized } ( RapydPaymentStatus::CanceledByClientOrBank | RapydPaymentStatus::Expired | RapydPaymentStatus::ReversedByRapyd, _, ) => enums::AttemptStatus::Voided, (RapydPaymentStatus::Error, _) => enums::AttemptStatus::Failure, (RapydPaymentStatus::New, _) => enums::AttemptStatus::Authorizing, } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RapydPaymentsResponse { pub status: Status, pub data: Option<ResponseData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Status { pub error_code: String, pub status: Option<String>, pub message: Option<String>, pub response_code: Option<String>, pub operation_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum NextAction { #[serde(rename = "3d_verification")] ThreedsVerification, #[serde(rename = "pending_capture")] PendingCapture, #[serde(rename = "not_applicable")] NotApplicable, #[serde(rename = "pending_confirmation")] PendingConfirmation, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct ResponseData { pub id: String, pub amount: i64, pub status: RapydPaymentStatus, pub next_action: NextAction, pub redirect_url: Option<String>, pub original_amount: Option<i64>, pub is_partial: Option<bool>, pub currency_code: Option<enums::Currency>, pub country_code: Option<String>, pub captured: Option<bool>, pub transaction_id: String, pub merchant_reference_id: Option<String>, pub paid: Option<bool>, pub failure_code: Option<String>, pub failure_message: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DisputeResponseData { pub id: String, pub amount: MinorUnit, pub currency: api_models::enums::Currency, pub token: String, pub dispute_reason_description: String, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub due_date: Option<PrimitiveDateTime>, pub status: RapydWebhookDisputeStatus, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub created_at: Option<PrimitiveDateTime>, #[serde(default, with = "common_utils::custom_serde::timestamp::option")] pub updated_at: Option<PrimitiveDateTime>, pub original_transaction_id: String, } #[derive(Default, Debug, Serialize)] pub struct RapydRefundRequest { pub payment: String, pub amount: Option<FloatMajorUnit>, pub currency: Option<enums::Currency>, } impl<F> TryFrom<&RapydRouterData<&types::RefundsRouterData<F>>> for RapydRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &RapydRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { payment: item .router_data .request .connector_transaction_id .to_string(), amount: Some(item.amount), currency: Some(item.router_data.request.currency), }) } } #[allow(dead_code)] #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] pub enum RefundStatus { Completed, Error, Rejected, #[default] Pending, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Completed => Self::Success, RefundStatus::Error | RefundStatus::Rejected => Self::Failure, RefundStatus::Pending => Self::Pending, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { pub status: Status, pub data: Option<RefundResponseData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct RefundResponseData { //Some field related to foreign exchange and split payment can be added as and when implemented pub id: String, pub payment: String, pub amount: i64, pub currency: enums::Currency, pub status: RefundStatus, pub created_at: Option<i64>, pub failure_reason: Option<String>, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for types::RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { let (connector_refund_id, refund_status) = match item.response.data { Some(data) => (data.id, enums::RefundStatus::from(data.status)), None => ( item.response.status.error_code, enums::RefundStatus::Failure, ), }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id, refund_status, }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for types::RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { let (connector_refund_id, refund_status) = match item.response.data { Some(data) => (data.id, enums::RefundStatus::from(data.status)), None => ( item.response.status.error_code, enums::RefundStatus::Failure, ), }; Ok(Self { response: Ok(RefundsResponseData { connector_refund_id, refund_status, }), ..item.data }) } } #[derive(Debug, Serialize, Clone)] pub struct CaptureRequest { amount: Option<FloatMajorUnit>, receipt_email: Option<Secret<String>>, statement_descriptor: Option<String>, } impl TryFrom<&RapydRouterData<&types::PaymentsCaptureRouterData>> for CaptureRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &RapydRouterData<&types::PaymentsCaptureRouterData>, ) -> Result<Self, Self::Error> { Ok(Self { amount: Some(item.amount), receipt_email: None, statement_descriptor: None, }) } } impl<F, T> TryFrom<ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, RapydPaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let (status, response) = match &item.response.data { Some(data) => { let attempt_status = get_status(data.status.to_owned(), data.next_action.to_owned()); match attempt_status { enums::AttemptStatus::Failure => ( enums::AttemptStatus::Failure, Err(ErrorResponse { code: data .failure_code .to_owned() .unwrap_or(item.response.status.error_code), status_code: item.http_code, message: item.response.status.status.unwrap_or_default(), reason: data.failure_message.to_owned(), attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ), _ => { let redirection_url = data .redirect_url .as_ref() .filter(|redirect_str| !redirect_str.is_empty()) .map(|url| { Url::parse(url).change_context( errors::ConnectorError::FailedToObtainIntegrationUrl, ) }) .transpose()?; let redirection_data = redirection_url.map(|url| RedirectForm::from((url, Method::Get))); ( attempt_status, Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(data.id.to_owned()), //transaction_id is also the field but this id is used to initiate a refund redirection_data: Box::new(redirection_data), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: data .merchant_reference_id .to_owned(), incremental_authorization_allowed: None, charges: None, }), ) } } } None => ( enums::AttemptStatus::Failure, Err(ErrorResponse { code: item.response.status.error_code, status_code: item.http_code, message: item.response.status.status.unwrap_or_default(), reason: item.response.status.message, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ), }; Ok(Self { status, response, ..item.data }) } } #[derive(Debug, Deserialize)] pub struct RapydIncomingWebhook { pub id: String, #[serde(rename = "type")] pub webhook_type: RapydWebhookObjectEventType, pub data: WebhookData, pub trigger_operation_id: Option<String>, pub status: String, pub created_at: i64, } #[derive(Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RapydWebhookObjectEventType { PaymentCompleted, PaymentCaptured, PaymentFailed, RefundCompleted, PaymentRefundRejected, PaymentRefundFailed, PaymentDisputeCreated, PaymentDisputeUpdated, #[serde(other)] Unknown, } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, strum::Display)] pub enum RapydWebhookDisputeStatus { #[serde(rename = "ACT")] Active, #[serde(rename = "RVW")] Review, #[serde(rename = "LOS")] Lose, #[serde(rename = "WIN")] Win, #[serde(other)] Unknown, } impl From<RapydWebhookDisputeStatus> for api_models::webhooks::IncomingWebhookEvent { fn from(value: RapydWebhookDisputeStatus) -> Self { match value { RapydWebhookDisputeStatus::Active => Self::DisputeOpened, RapydWebhookDisputeStatus::Review => Self::DisputeChallenged, RapydWebhookDisputeStatus::Lose => Self::DisputeLost, RapydWebhookDisputeStatus::Win => Self::DisputeWon, RapydWebhookDisputeStatus::Unknown => Self::EventNotSupported, } } } #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum WebhookData { Payment(ResponseData), Refund(RefundResponseData), Dispute(DisputeResponseData), } impl From<ResponseData> for RapydPaymentsResponse { fn from(value: ResponseData) -> Self { Self { status: Status { error_code: NO_ERROR_CODE.to_owned(), status: None, message: None, response_code: None, operation_id: None, }, data: Some(value), } } } impl From<RefundResponseData> for RefundResponse { fn from(value: RefundResponseData) -> Self { Self { status: Status { error_code: NO_ERROR_CODE.to_owned(), status: None, message: None, response_code: None, operation_id: None, }, data: Some(value), } } }
crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
hyperswitch_connectors
full_file
4,440
null
null
null
null
null
null
null
null
null
null
null
null
null
pub async fn parse_evidence_type( field: &mut Field, ) -> CustomResult<Option<disputes::EvidenceType>, errors::ApiErrorResponse> { let purpose = helpers::read_string(field).await; match purpose { Some(evidence_type) => Ok(Some( evidence_type .parse_enum("Evidence Type") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error parsing evidence type")?, )), _ => Ok(None), } }
crates/router/src/routes/disputes/utils.rs
router
function_signature
106
rust
null
null
null
null
parse_evidence_type
null
null
null
null
null
null
null
impl api::PaymentVoid for Trustpay {}
crates/hyperswitch_connectors/src/connectors/trustpay.rs
hyperswitch_connectors
impl_block
9
rust
null
Trustpay
api::PaymentVoid for
impl api::PaymentVoid for for Trustpay
null
null
null
null
null
null
null
null
pub struct DwollaPaymentsRequest { #[serde(rename = "_links")] links: DwollaPaymentLinks, amount: DwollaAmount, correlation_id: String, }
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
hyperswitch_connectors
struct_definition
37
rust
DwollaPaymentsRequest
null
null
null
null
null
null
null
null
null
null
null
pub struct CustomerMetaData { crm_id: Option<Secret<id_type::CustomerId>>, }
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
hyperswitch_connectors
struct_definition
20
rust
CustomerMetaData
null
null
null
null
null
null
null
null
null
null
null
impl IncomingWebhook for Adyenplatform { #[cfg(feature = "payouts")] fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> { Ok(Box::new(crypto::HmacSha256)) } #[cfg(feature = "payouts")] fn get_webhook_source_verification_signature( &self, request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { let base64_signature = request .headers .get(HeaderName::from_static("hmacsignature")) .ok_or(ConnectorError::WebhookSourceVerificationFailed)?; Ok(base64_signature.as_bytes().to_vec()) } #[cfg(feature = "payouts")] fn get_webhook_source_verification_message( &self, request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, ConnectorError> { Ok(request.body.to_vec()) } #[cfg(feature = "payouts")] async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_label: &str, ) -> CustomResult<bool, ConnectorError> { use common_utils::consts; let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_label, connector_webhook_details, ) .await .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context(ConnectorError::WebhookSourceVerificationFailed)?; let raw_key = hex::decode(connector_webhook_secrets.secret) .change_context(ConnectorError::WebhookVerificationSecretInvalid)?; let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key); let signed_messaged = hmac::sign(&signing_key, &message); let payload_sign = consts::BASE64_ENGINE.encode(signed_messaged.as_ref()); Ok(payload_sign.as_bytes().eq(&signature)) } fn get_webhook_object_reference_id( &self, #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(ConnectorError::WebhookSourceVerificationFailed)?; Ok(api_models::webhooks::ObjectReferenceId::PayoutId( api_models::webhooks::PayoutIdType::PayoutAttemptId(webhook_body.data.reference), )) } #[cfg(not(feature = "payouts"))] { Err(report!(ConnectorError::WebhooksNotImplemented)) } } fn get_webhook_api_response( &self, _request: &IncomingWebhookRequestDetails<'_>, error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, ConnectorError> { if error_kind.is_some() { Ok(ApplicationResponse::JsonWithHeaders(( serde_json::Value::Null, vec![( "x-http-code".to_string(), Maskable::Masked(Secret::new("404".to_string())), )], ))) } else { Ok(ApplicationResponse::StatusOk) } } fn get_webhook_event_type( &self, #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(ConnectorError::WebhookSourceVerificationFailed)?; Ok(get_adyen_webhook_event( webhook_body.webhook_type, webhook_body.data.status, webhook_body.data.tracking, webhook_body.data.category.as_ref(), )) } #[cfg(not(feature = "payouts"))] { Err(report!(ConnectorError::WebhooksNotImplemented)) } } fn get_webhook_resource_object( &self, #[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>, #[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> { #[cfg(feature = "payouts")] { let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request .body .parse_struct("AdyenplatformIncomingWebhook") .change_context(ConnectorError::WebhookSourceVerificationFailed)?; Ok(Box::new(webhook_body)) } #[cfg(not(feature = "payouts"))] { Err(report!(ConnectorError::WebhooksNotImplemented)) } } }
crates/hyperswitch_connectors/src/connectors/adyenplatform.rs
hyperswitch_connectors
impl_block
1,372
rust
null
Adyenplatform
IncomingWebhook for
impl IncomingWebhook for for Adyenplatform
null
null
null
null
null
null
null
null
impl ThreeDSDecision { /// Checks if the decision is to mandate a 3DS challenge pub fn should_force_3ds_challenge(self) -> bool { matches!(self, Self::ChallengeRequested) } }
crates/common_types/src/three_ds_decision_rule_engine.rs
common_types
impl_block
47
rust
null
ThreeDSDecision
null
impl ThreeDSDecision
null
null
null
null
null
null
null
null
File: crates/router/src/core/encryption.rs Public functions: 3 use api_models::admin::MerchantKeyTransferRequest; use base64::Engine; use common_utils::{ keymanager::transfer_key_to_key_manager, types::keymanager::{EncryptionTransferRequest, Identifier}, }; use error_stack::ResultExt; use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore; use masking::ExposeInterface; use crate::{consts::BASE64_ENGINE, errors, types::domain::UserKeyStore, SessionState}; pub async fn transfer_encryption_key( state: &SessionState, req: MerchantKeyTransferRequest, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let db = &*state.store; let key_stores = db .get_all_key_stores( &state.into(), &db.get_master_key().to_vec().into(), req.from, req.limit, ) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; send_request_to_key_service_for_merchant(state, key_stores).await } pub async fn send_request_to_key_service_for_merchant( state: &SessionState, keys: Vec<MerchantKeyStore>, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { let total = keys.len(); for key in keys { let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); let req = EncryptionTransferRequest { identifier: Identifier::Merchant(key.merchant_id.clone()), key: key_encoded, }; transfer_key_to_key_manager(&state.into(), req) .await .change_context(errors::ApiErrorResponse::InternalServerError)?; } Ok(total) } pub async fn send_request_to_key_service_for_user( state: &SessionState, keys: Vec<UserKeyStore>, ) -> errors::CustomResult<usize, errors::ApiErrorResponse> { futures::future::try_join_all(keys.into_iter().map(|key| async move { let key_encoded = BASE64_ENGINE.encode(key.key.clone().into_inner().expose()); let req = EncryptionTransferRequest { identifier: Identifier::User(key.user_id.clone()), key: key_encoded, }; transfer_key_to_key_manager(&state.into(), req).await })) .await .change_context(errors::ApiErrorResponse::InternalServerError) .map(|v| v.len()) }
crates/router/src/core/encryption.rs
router
full_file
517
null
null
null
null
null
null
null
null
null
null
null
null
null
impl api::ConnectorAccessToken for Aci {}
crates/hyperswitch_connectors/src/connectors/aci.rs
hyperswitch_connectors
impl_block
9
rust
null
Aci
api::ConnectorAccessToken for
impl api::ConnectorAccessToken for for Aci
null
null
null
null
null
null
null
null
pub fn rule<O: EuclidParsable>(input: &str) -> ParseResult<&str, ast::Rule<O>> { let rule_name = error::context( "rule_name", combinator::map( skip_ws(sequence::pair( complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'), complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'), )), |out: (&str, &str)| out.0.to_string() + out.1, ), ); let connector_selection = error::context( "parse_output", sequence::preceded(skip_ws(complete::tag(":")), output), ); error::context( "rule", combinator::map( sequence::tuple((rule_name, connector_selection, rule_conditions_array)), |tup: (String, O, Vec<ast::IfStatement>)| ast::Rule { name: tup.0, connector_selection: tup.1, statements: tup.2, }, ), )(input) }
crates/euclid/src/frontend/ast/parser.rs
euclid
function_signature
240
rust
null
null
null
null
rule
null
null
null
null
null
null
null