text
stringlengths 65
57.3k
| file_path
stringlengths 22
92
| module
stringclasses 38
values | type
stringclasses 7
values | struct_name
stringlengths 3
60
⌀ | impl_count
int64 0
60
⌀ | traits
listlengths 0
59
⌀ | tokens
int64 16
8.19k
| function_name
stringlengths 3
85
⌀ | type_name
stringlengths 1
67
⌀ | trait_name
stringclasses 573
values | method_count
int64 0
31
⌀ | public_method_count
int64 0
19
⌀ | submodule_count
int64 0
56
⌀ | export_count
int64 0
9
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Struct: CustomerBankAccountResponse
// File: crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CustomerBankAccountResponse
|
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CustomerBankAccountResponse
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/custombilling.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
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::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use transformers as custombilling;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Custombilling {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Custombilling {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Custombilling {}
impl api::PaymentSession for Custombilling {}
impl api::ConnectorAccessToken for Custombilling {}
impl api::MandateSetup for Custombilling {}
impl api::PaymentAuthorize for Custombilling {}
impl api::PaymentSync for Custombilling {}
impl api::PaymentCapture for Custombilling {}
impl api::PaymentVoid for Custombilling {}
impl api::Refund for Custombilling {}
impl api::RefundExecute for Custombilling {}
impl api::RefundSync for Custombilling {}
impl api::PaymentToken for Custombilling {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Custombilling
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Custombilling
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 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 Custombilling {
fn id(&self) -> &'static str {
"custombilling"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
// 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 {
""
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: custombilling::CustombillingErrorResponse = res
.response
.parse_struct("CustombillingErrorResponse")
.change_context(errors::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 Custombilling {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Custombilling {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Custombilling {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Custombilling
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Custombilling
{
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = custombilling::CustombillingRouterData::from((amount, req));
let connector_req =
custombilling::CustombillingPaymentsRequest::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: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("Custombilling PaymentsAuthorizeResponse")
.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)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Custombilling {
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("custombilling PaymentsSyncResponse")
.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)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Custombilling {
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
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: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("Custombilling PaymentsCaptureResponse")
.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)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Custombilling {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Custombilling {
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data =
custombilling::CustombillingRouterData::from((refund_amount, req));
let connector_req =
custombilling::CustombillingRefundRequest::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> {
let response: custombilling::RefundResponse = res
.response
.parse_struct("custombilling RefundResponse")
.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)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Custombilling {
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
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)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: custombilling::RefundResponse = res
.response
.parse_struct("custombilling RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Custombilling {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl ConnectorSpecifications for Custombilling {}
|
crates/hyperswitch_connectors/src/connectors/custombilling.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,258
| null | null | null | null | null | null | null |
// Struct: AffirmCancelRequest
// File: crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AffirmCancelRequest
|
crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AffirmCancelRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: payment_methods_session_delete_payment_method
// File: crates/router/src/core/payment_methods.rs
// Module: router
pub fn payment_methods_session_delete_payment_method(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
pm_id: id_type::GlobalPaymentMethodId,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
) -> RouterResponse<api::PaymentMethodDeleteResponse>
|
crates/router/src/core/payment_methods.rs
|
router
|
function_signature
| null | null | null | 96
|
payment_methods_session_delete_payment_method
| null | null | null | null | null | null |
// File: crates/router/src/core/payments/operations/payment_reject.rs
// Module: router
// Public structs: 1
use std::marker::PhantomData;
use api_models::{enums::FrmSuggestion, payments::PaymentsCancelRequest};
use async_trait::async_trait;
use error_stack::ResultExt;
use router_derive;
use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payments::{helpers, operations, PaymentAddress, PaymentData},
},
events::audit_events::{AuditEvent, AuditEventType},
routes::{app::ReqState, SessionState},
services,
types::{
api::{self, PaymentIdTypeExt},
domain,
storage::{self, enums},
},
utils::OptionExt,
};
#[derive(Debug, Clone, Copy, router_derive::PaymentOperation)]
#[operation(operations = "all", flow = "cancel")]
pub struct PaymentReject;
type PaymentRejectOperation<'b, F> = BoxedOperation<'b, F, PaymentsCancelRequest, PaymentData<F>>;
#[async_trait]
impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest>
for PaymentReject
{
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_id: &api::PaymentIdType,
_request: &PaymentsCancelRequest,
merchant_context: &domain::MerchantContext,
_auth_flow: services::AuthFlow,
_header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest, PaymentData<F>>>
{
let db = &*state.store;
let key_manager_state = &state.into();
let merchant_id = merchant_context.get_merchant_account().get_id();
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
key_manager_state,
&payment_id,
merchant_id,
merchant_context.get_merchant_key_store(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
helpers::validate_payment_status_against_not_allowed_statuses(
payment_intent.status,
&[
enums::IntentStatus::Cancelled,
enums::IntentStatus::Failed,
enums::IntentStatus::Succeeded,
enums::IntentStatus::Processing,
],
"reject",
)?;
let attempt_id = payment_intent.active_attempt.get_id().clone();
let payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
merchant_id,
attempt_id.clone().as_str(),
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let shipping_address = helpers::get_address_by_id(
state,
payment_intent.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let billing_address = helpers::get_address_by_id(
state,
payment_intent.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_method_billing = helpers::get_address_by_id(
state,
payment_attempt.payment_method_billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&payment_intent.payment_id,
merchant_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let currency = payment_attempt.currency.get_required_value("currency")?;
let amount = payment_attempt.get_total_amount().into();
let frm_response = if cfg!(feature = "frm") {
db.find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_context.get_merchant_account().get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {attempt_id}", merchant_context.get_merchant_account().get_id())
})
.ok()
} else {
None
};
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("'profile_id' not set in payment intent")?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let payment_data = PaymentData {
flow: PhantomData,
payment_intent,
payment_attempt,
currency,
amount,
email: None,
mandate_id: None,
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
address: PaymentAddress::new(
shipping_address.as_ref().map(From::from),
billing_address.as_ref().map(From::from),
payment_method_billing.as_ref().map(From::from),
business_profile.use_billing_as_payment_method_billing,
),
token_data: None,
confirm: None,
payment_method_data: None,
payment_method_token: None,
payment_method_info: None,
force_sync: None,
all_keys_required: None,
refunds: vec![],
disputes: vec![],
attempts: None,
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details: None,
frm_message: frm_response,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
recurring_details: None,
poll_config: None,
tax_data: None,
session_id: None,
service_details: None,
card_testing_guard_data: None,
vault_operation: None,
threeds_method_comp_ind: None,
whole_connector_response: None,
is_manual_retry_enabled: None,
};
let get_trackers_response = operations::GetTrackerResponse {
operation: Box::new(self),
customer_details: None,
payment_data,
business_profile,
mandate_type: None,
};
Ok(get_trackers_response)
}
}
#[async_trait]
impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, PaymentsCancelRequest> for PaymentReject {
#[instrument(skip_all)]
async fn update_trackers<'b>(
&'b self,
state: &'b SessionState,
req_state: ReqState,
mut payment_data: PaymentData<F>,
_customer: Option<domain::Customer>,
storage_scheme: enums::MerchantStorageScheme,
_updated_customer: Option<storage::CustomerUpdate>,
key_store: &domain::MerchantKeyStore,
_should_decline_transaction: Option<FrmSuggestion>,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<(PaymentRejectOperation<'b, F>, PaymentData<F>)>
where
F: 'b + Send,
{
let intent_status_update = storage::PaymentIntentUpdate::RejectUpdate {
status: enums::IntentStatus::Failed,
merchant_decision: Some(enums::MerchantDecision::Rejected.to_string()),
updated_by: storage_scheme.to_string(),
};
let (error_code, error_message) =
payment_data
.frm_message
.clone()
.map_or((None, None), |fraud_check| {
(
Some(Some(fraud_check.frm_status.to_string())),
Some(fraud_check.frm_reason.map(|reason| reason.to_string())),
)
});
let attempt_status_update = storage::PaymentAttemptUpdate::RejectUpdate {
status: enums::AttemptStatus::Failure,
error_code,
error_message,
updated_by: storage_scheme.to_string(),
};
payment_data.payment_intent = state
.store
.update_payment_intent(
&state.into(),
payment_data.payment_intent,
intent_status_update,
key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_attempt = state
.store
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt.clone(),
attempt_status_update,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let error_code = payment_data.payment_attempt.error_code.clone();
let error_message = payment_data.payment_attempt.error_message.clone();
req_state
.event_context
.event(AuditEvent::new(AuditEventType::PaymentReject {
error_code,
error_message,
}))
.with(payment_data.to_event())
.emit();
Ok((Box::new(self), payment_data))
}
}
impl<F: Send + Clone + Sync> ValidateRequest<F, PaymentsCancelRequest, PaymentData<F>>
for PaymentReject
{
#[instrument(skip_all)]
fn validate_request<'a, 'b>(
&'b self,
request: &PaymentsCancelRequest,
merchant_context: &'a domain::MerchantContext,
) -> RouterResult<(PaymentRejectOperation<'b, F>, operations::ValidateResult)> {
Ok((
Box::new(self),
operations::ValidateResult {
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_context.get_merchant_account().storage_scheme,
requeue: false,
},
))
}
}
|
crates/router/src/core/payments/operations/payment_reject.rs
|
router
|
full_file
| null | null | null | 2,250
| null | null | null | null | null | null | null |
// Struct: BitpayPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BitpayPaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BitpayPaymentsRequest
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/paystack.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use std::sync::LazyLock;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as paystack;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Paystack {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Paystack {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Paystack {}
impl api::PaymentSession for Paystack {}
impl api::ConnectorAccessToken for Paystack {}
impl api::MandateSetup for Paystack {}
impl api::PaymentAuthorize for Paystack {}
impl api::PaymentSync for Paystack {}
impl api::PaymentCapture for Paystack {}
impl api::PaymentVoid for Paystack {}
impl api::Refund for Paystack {}
impl api::RefundExecute for Paystack {}
impl api::RefundSync for Paystack {}
impl api::PaymentToken for Paystack {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Paystack
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paystack
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 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 Paystack {
fn id(&self) -> &'static str {
"paystack"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.paystack.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = paystack::PaystackAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.expose()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paystack::PaystackErrorResponse = res
.response
.parse_struct("PaystackErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_message = paystack::get_error_message(response.clone());
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: error_message,
reason: Some(response.message),
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 Paystack {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paystack {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paystack {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Paystack
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paystack {
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!("{}/charge", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = paystack::PaystackRouterData::from((amount, req));
let connector_req = paystack::PaystackPaymentsRequest::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: paystack::PaystackPaymentsResponse = res
.response
.parse_struct("Paystack PaymentsAuthorizeResponse")
.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)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Paystack {
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> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transaction/verify/",
connector_payment_id,
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: paystack::PaystackPSyncResponse = res
.response
.parse_struct("paystack PaymentsSyncResponse")
.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)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Paystack {
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> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
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: paystack::PaystackPaymentsResponse = res
.response
.parse_struct("Paystack PaymentsCaptureResponse")
.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)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paystack {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paystack {
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!("{}/refund", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = paystack::PaystackRouterData::from((refund_amount, req));
let connector_req = paystack::PaystackRefundRequest::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> {
let response: paystack::PaystackRefundsResponse = res
.response
.parse_struct("paystack RefundResponse")
.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)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paystack {
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 connector_refund_id = req
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/refund/",
connector_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)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: paystack::PaystackRefundsResponse = res
.response
.parse_struct("paystack RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Paystack {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha512))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = utils::get_header_key_value("x-paystack-signature", request.headers)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(signature)
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(message.to_string().into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body = request
.body
.parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match webhook_body.data {
paystack::PaystackWebhookEventData::Payment(data) => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(data.reference),
))
}
paystack::PaystackWebhookEventData::Refund(data) => {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(data.id),
))
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook_body = request
.body
.parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
webhook_body.data,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook_body = request
.body
.parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(match webhook_body.data {
paystack::PaystackWebhookEventData::Payment(payment_webhook_data) => {
Box::new(payment_webhook_data)
}
paystack::PaystackWebhookEventData::Refund(refund_webhook_data) => {
Box::new(refund_webhook_data)
}
})
}
}
static PAYSTACK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut paystack_supported_payment_methods = SupportedPaymentMethods::new();
paystack_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Eft,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
paystack_supported_payment_methods
});
static PAYSTACK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Paystack",
description: "Paystack is a Nigerian financial technology company that provides online and offline payment solutions to businesses across Africa.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static PAYSTACK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Paystack {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYSTACK_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYSTACK_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PAYSTACK_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/paystack.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 5,343
| null | null | null | null | null | null | null |
// File: crates/external_services/src/managers/secrets_management.rs
// Module: external_services
// Public functions: 2
//! Secrets management util module
use common_utils::errors::CustomResult;
#[cfg(feature = "hashicorp-vault")]
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::{
SecretManagementInterface, SecretsManagementError,
};
#[cfg(feature = "aws_kms")]
use crate::aws_kms;
#[cfg(feature = "hashicorp-vault")]
use crate::hashicorp_vault;
use crate::no_encryption::core::NoEncryption;
/// Enum representing configuration options for secrets management.
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(tag = "secrets_manager")]
#[serde(rename_all = "snake_case")]
pub enum SecretsManagementConfig {
/// AWS KMS configuration
#[cfg(feature = "aws_kms")]
AwsKms {
/// AWS KMS config
aws_kms: aws_kms::core::AwsKmsConfig,
},
/// HashiCorp-Vault configuration
#[cfg(feature = "hashicorp-vault")]
HashiCorpVault {
/// HC-Vault config
hc_vault: hashicorp_vault::core::HashiCorpVaultConfig,
},
/// Variant representing no encryption
#[default]
NoEncryption,
}
impl SecretsManagementConfig {
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => aws_kms.validate(),
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => hc_vault.validate(),
Self::NoEncryption => Ok(()),
}
}
/// Retrieves the appropriate secret management client based on the configuration.
pub async fn get_secret_management_client(
&self,
) -> CustomResult<Box<dyn SecretManagementInterface>, SecretsManagementError> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => {
Ok(Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await))
}
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => {
hashicorp_vault::core::HashiCorpVault::new(hc_vault)
.change_context(SecretsManagementError::ClientCreationFailed)
.map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) })
}
Self::NoEncryption => Ok(Box::new(NoEncryption)),
}
}
}
|
crates/external_services/src/managers/secrets_management.rs
|
external_services
|
full_file
| null | null | null | 593
| null | null | null | null | null | null | null |
// Struct: RefundBodyResponse
// File: crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundBodyResponse
|
crates/hyperswitch_connectors/src/connectors/bamboraapac/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundBodyResponse
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: KafkaFraudCheckEvent
// File: crates/router/src/services/kafka/fraud_check_event.rs
// Module: router
// Implementations: 2
// Traits: super::KafkaMessage
pub struct KafkaFraudCheckEvent<'a>
|
crates/router/src/services/kafka/fraud_check_event.rs
|
router
|
struct_definition
|
KafkaFraudCheckEvent
| 2
|
[
"super::KafkaMessage"
] | 55
| null | null | null | null | null | null | null |
// File: crates/router/src/types/api/mandates.rs
// Module: router
use ::payment_methods::controller::PaymentMethodsController;
use api_models::mandates;
pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse};
use common_utils::ext_traits::OptionExt;
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
payment_methods,
},
newtype,
routes::SessionState,
types::{
api, domain,
storage::{self, enums as storage_enums},
},
};
newtype!(
pub MandateCardDetails = mandates::MandateCardDetails,
derives = (Default, Debug, Deserialize, Serialize)
);
#[async_trait::async_trait]
pub(crate) trait MandateResponseExt: Sized {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self>;
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl MandateResponseExt for MandateResponse {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self> {
let db = &*state.store;
let payment_method = db
.find_payment_method(
&(state.into()),
&key_store,
&mandate.payment_method_id,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm = payment_method
.get_payment_method_type()
.get_required_value("payment_method")
.change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("payment_method not found")?;
let card = if pm == storage_enums::PaymentMethod::Card {
// if locker is disabled , decrypt the payment method data
let card_details = if state.conf.locker.locker_enabled {
let card = payment_methods::cards::get_card_from_locker(
state,
&payment_method.customer_id,
&payment_method.merchant_id,
payment_method
.locker_id
.as_ref()
.unwrap_or(payment_method.get_id()),
)
.await?;
payment_methods::transformers::get_card_detail(&payment_method, card)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while getting card details")?
} else {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account.clone(), key_store),
));
payment_methods::cards::PmCards {
state,
merchant_context: &merchant_context,
}
.get_card_details_without_locker_fallback(&payment_method)
.await?
};
Some(MandateCardDetails::from(card_details).into_inner())
} else {
None
};
let payment_method_type = payment_method
.get_payment_method_subtype()
.map(|pmt| pmt.to_string());
let user_agent = mandate.get_user_agent_extended().unwrap_or_default();
Ok(Self {
mandate_id: mandate.mandate_id,
customer_acceptance: Some(api::payments::CustomerAcceptance {
acceptance_type: if mandate.customer_ip_address.is_some() {
api::payments::AcceptanceType::Online
} else {
api::payments::AcceptanceType::Offline
},
accepted_at: mandate.customer_accepted_at,
online: Some(api::payments::OnlineMandate {
ip_address: mandate.customer_ip_address,
user_agent,
}),
}),
card,
status: mandate.mandate_status,
payment_method: pm.to_string(),
payment_method_type,
payment_method_id: mandate.payment_method_id,
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl MandateResponseExt for MandateResponse {
async fn from_db_mandate(
state: &SessionState,
key_store: domain::MerchantKeyStore,
mandate: storage::Mandate,
merchant_account: &domain::MerchantAccount,
) -> RouterResult<Self> {
todo!()
}
}
#[cfg(feature = "v1")]
impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self {
mandates::MandateCardDetails {
last4_digits: card_details_from_locker.last4_digits,
card_exp_month: card_details_from_locker.expiry_month.clone(),
card_exp_year: card_details_from_locker.expiry_year.clone(),
card_holder_name: card_details_from_locker.card_holder_name,
card_token: card_details_from_locker.card_token,
scheme: card_details_from_locker.scheme,
issuer_country: card_details_from_locker.issuer_country,
card_fingerprint: card_details_from_locker.card_fingerprint,
card_isin: card_details_from_locker.card_isin,
card_issuer: card_details_from_locker.card_issuer,
card_network: card_details_from_locker.card_network,
card_type: card_details_from_locker.card_type,
nick_name: card_details_from_locker.nick_name,
}
.into()
}
}
#[cfg(feature = "v2")]
impl From<api::payment_methods::CardDetailFromLocker> for MandateCardDetails {
fn from(card_details_from_locker: api::payment_methods::CardDetailFromLocker) -> Self {
mandates::MandateCardDetails {
last4_digits: card_details_from_locker.last4_digits,
card_exp_month: card_details_from_locker.expiry_month.clone(),
card_exp_year: card_details_from_locker.expiry_year.clone(),
card_holder_name: card_details_from_locker.card_holder_name,
card_token: None,
scheme: None,
issuer_country: card_details_from_locker
.issuer_country
.map(|country| country.to_string()),
card_fingerprint: card_details_from_locker.card_fingerprint,
card_isin: card_details_from_locker.card_isin,
card_issuer: card_details_from_locker.card_issuer,
card_network: card_details_from_locker.card_network,
card_type: card_details_from_locker
.card_type
.as_ref()
.map(|c| c.to_string()),
nick_name: card_details_from_locker.nick_name,
}
.into()
}
}
|
crates/router/src/types/api/mandates.rs
|
router
|
full_file
| null | null | null | 1,451
| null | null | null | null | null | null | null |
// Struct: ApplicationInformation
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ApplicationInformation
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ApplicationInformation
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Function: new_list
// File: crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
// Module: hyperswitch_connectors
pub fn new_list(value: Vec<T>) -> Self
|
crates/hyperswitch_connectors/src/connectors/netcetera/netcetera_types.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 49
|
new_list
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 26
use common_enums::{enums, CountryAlpha2, Currency};
use common_utils::{pii, request::Method, types::MinorUnit};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::{PayLaterData, PaymentMethodData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsCancelData, PaymentsCaptureData, ResponseId},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
pub struct AffirmRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for AffirmRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Serialize)]
pub struct AffirmPaymentsRequest {
pub merchant: Merchant,
pub items: Vec<Item>,
pub shipping: Option<Shipping>,
pub billing: Option<Billing>,
pub total: MinorUnit,
pub currency: Currency,
pub order_id: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct AffirmCompleteAuthorizeRequest {
pub order_id: Option<String>,
pub reference_id: Option<String>,
pub transaction_id: String,
}
impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for AffirmCompleteAuthorizeRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
let transaction_id = item.request.connector_transaction_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_transaction_id",
},
)?;
let reference_id = item.reference_id.clone();
let order_id = item.connector_request_reference_id.clone();
Ok(Self {
transaction_id,
order_id: Some(order_id),
reference_id,
})
}
}
#[derive(Debug, Serialize)]
pub struct Merchant {
pub public_api_key: Secret<String>,
pub user_confirmation_url: String,
pub user_cancel_url: String,
pub user_confirmation_url_action: Option<String>,
pub use_vcn: Option<String>,
pub name: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct Item {
pub display_name: String,
pub sku: String,
pub unit_price: MinorUnit,
pub qty: i64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Shipping {
pub name: Name,
pub address: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
}
#[derive(Debug, Serialize)]
pub struct Billing {
pub name: Name,
pub address: Address,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<pii::Email>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Name {
pub first: Option<Secret<String>>,
pub last: Option<Secret<String>>,
pub full: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Address {
pub line1: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub line2: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<Secret<String>>,
pub zipcode: Option<Secret<String>>,
pub country: Option<CountryAlpha2>,
}
#[derive(Debug, Serialize)]
pub struct Metadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub entity_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub platform_affirm: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub itinerary: Option<Vec<Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub checkout_channel_type: Option<String>,
#[serde(rename = "BOPIS", skip_serializing_if = "Option::is_none")]
pub bopis: Option<bool>,
}
#[derive(Debug, Serialize)]
pub struct Discount {
pub discount_amount: MinorUnit,
pub discount_display_name: String,
pub discount_code: Option<String>,
}
impl TryFrom<&AffirmRouterData<&PaymentsAuthorizeRouterData>> for AffirmPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AffirmRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let router_data = &item.router_data;
let request = &router_data.request;
let billing = Some(Billing {
name: Name {
first: item.router_data.get_optional_billing_first_name(),
last: item.router_data.get_optional_billing_last_name(),
full: item.router_data.get_optional_billing_full_name(),
},
address: Address {
line1: item.router_data.get_optional_billing_line1(),
line2: item.router_data.get_optional_billing_line2(),
city: item.router_data.get_optional_billing_city(),
state: item.router_data.get_optional_billing_state(),
zipcode: item.router_data.get_optional_billing_zip(),
country: item.router_data.get_optional_billing_country(),
},
phone_number: item.router_data.get_optional_billing_phone_number(),
email: item.router_data.get_optional_billing_email(),
});
let shipping = Some(Shipping {
name: Name {
first: item.router_data.get_optional_shipping_first_name(),
last: item.router_data.get_optional_shipping_last_name(),
full: item.router_data.get_optional_shipping_full_name(),
},
address: Address {
line1: item.router_data.get_optional_shipping_line1(),
line2: item.router_data.get_optional_shipping_line2(),
city: item.router_data.get_optional_shipping_city(),
state: item.router_data.get_optional_shipping_state(),
zipcode: item.router_data.get_optional_shipping_zip(),
country: item.router_data.get_optional_shipping_country(),
},
phone_number: item.router_data.get_optional_shipping_phone_number(),
email: item.router_data.get_optional_shipping_email(),
});
match request.payment_method_data.clone() {
PaymentMethodData::PayLater(PayLaterData::AffirmRedirect {}) => {
let items = match request.order_details.clone() {
Some(order_details) => order_details
.iter()
.map(|data| {
Ok(Item {
display_name: data.product_name.clone(),
sku: data.product_id.clone().unwrap_or_default(),
unit_price: data.amount,
qty: data.quantity.into(),
})
})
.collect::<Result<Vec<_>, _>>(),
None => Err(report!(errors::ConnectorError::MissingRequiredField {
field_name: "order_details",
})),
}?;
let auth_type = AffirmAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let public_api_key = auth_type.public_key;
let merchant = Merchant {
public_api_key,
user_confirmation_url: request.get_complete_authorize_url()?,
user_cancel_url: request.get_router_return_url()?,
user_confirmation_url_action: None,
use_vcn: None,
name: None,
};
Ok(Self {
merchant,
items,
shipping,
billing,
total: item.amount,
currency: request.currency,
order_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
}
pub struct AffirmAuthType {
pub public_key: Secret<String>,
pub private_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AffirmAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
public_key: api_key.to_owned(),
private_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl From<AffirmTransactionStatus> for common_enums::AttemptStatus {
fn from(item: AffirmTransactionStatus) -> Self {
match item {
AffirmTransactionStatus::Authorized => Self::Authorized,
AffirmTransactionStatus::AuthExpired => Self::Failure,
AffirmTransactionStatus::Canceled => Self::Voided,
AffirmTransactionStatus::Captured => Self::Charged,
AffirmTransactionStatus::ConfirmationExpired => Self::Failure,
AffirmTransactionStatus::Confirmed => Self::Authorized,
AffirmTransactionStatus::Created => Self::Pending,
AffirmTransactionStatus::Declined => Self::Failure,
AffirmTransactionStatus::Disputed => Self::Unresolved,
AffirmTransactionStatus::DisputeRefunded => Self::Unresolved,
AffirmTransactionStatus::ExpiredAuthorization => Self::Failure,
AffirmTransactionStatus::ExpiredConfirmation => Self::Failure,
AffirmTransactionStatus::PartiallyCaptured => Self::Charged,
AffirmTransactionStatus::Voided => Self::Voided,
AffirmTransactionStatus::PartiallyVoided => Self::Voided,
}
}
}
impl From<AffirmRefundStatus> for common_enums::RefundStatus {
fn from(item: AffirmRefundStatus) -> Self {
match item {
AffirmRefundStatus::PartiallyRefunded => Self::Success,
AffirmRefundStatus::Refunded => Self::Success,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AffirmPaymentsResponse {
checkout_id: String,
redirect_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCompleteAuthorizeResponse {
pub id: String,
pub status: AffirmTransactionStatus,
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: String,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
pub provider_id: Option<i64>,
pub remove_tax: Option<bool>,
pub checkout: Option<Value>,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<i64>,
pub loan_information: Option<LoanInformation>,
pub user_id: Option<String>,
pub platform: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TransactionEvent {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<i64>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LoanInformation {
pub fees: Option<LoanFees>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct LoanFees {
pub amount: Option<MinorUnit>,
pub description: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AffirmTransactionStatus {
Authorized,
AuthExpired,
Canceled,
Captured,
ConfirmationExpired,
Confirmed,
Created,
Declined,
Disputed,
DisputeRefunded,
ExpiredAuthorization,
ExpiredConfirmation,
PartiallyCaptured,
Voided,
PartiallyVoided,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AffirmRefundStatus {
PartiallyRefunded,
Refunded,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmPSyncResponse {
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: Option<String>,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub id: String,
pub order_id: String,
pub provider_id: Option<i64>,
pub remove_tax: Option<bool>,
pub status: AffirmTransactionStatus,
pub checkout: Option<Value>,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<MinorUnit>,
pub loan_information: Option<LoanInformation>,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub merchant_transaction_id: Option<String>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmRsyncResponse {
pub amount: MinorUnit,
pub amount_refunded: MinorUnit,
pub authorization_expiration: String,
pub checkout_id: String,
pub created: String,
pub currency: Currency,
pub events: Vec<TransactionEvent>,
pub id: String,
pub order_id: String,
pub status: AffirmRefundStatus,
pub refund_expires: Option<String>,
pub remaining_capturable_amount: Option<MinorUnit>,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub merchant_transaction_id: Option<String>,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AffirmResponseWrapper {
Authorize(AffirmPaymentsResponse),
Psync(Box<AffirmPSyncResponse>),
}
impl<F, T> TryFrom<ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmResponseWrapper, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match &item.response {
AffirmResponseWrapper::Authorize(resp) => {
let redirection_data = url::Url::parse(&resp.redirect_url)
.ok()
.map(|url| RedirectForm::from((url, Method::Get)));
Ok(Self {
status: enums::AttemptStatus::AuthenticationPending,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.checkout_id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
charges: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
AffirmResponseWrapper::Psync(resp) => {
let status = enums::AttemptStatus::from(resp.status);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(resp.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
charges: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmCompleteAuthorizeResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: common_enums::AttemptStatus::from(item.response.status),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct AffirmRefundRequest {
pub amount: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
pub reference_id: Option<String>,
}
impl<F> TryFrom<&AffirmRouterData<&RefundsRouterData<F>>> for AffirmRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AffirmRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let reference_id = item.router_data.request.connector_transaction_id.clone();
Ok(Self {
amount: item.amount.to_owned(),
reference_id: Some(reference_id),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmRefundResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
impl From<AffirmEventType> for enums::RefundStatus {
fn from(event_type: AffirmEventType) -> Self {
match event_type {
AffirmEventType::Refund => Self::Success,
_ => Self::Pending,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, AffirmRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, AffirmRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.event_type),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, AffirmRsyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, AffirmRsyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct AffirmErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Debug, Serialize)]
pub struct AffirmCaptureRequest {
pub order_id: Option<String>,
pub reference_id: Option<String>,
pub amount: MinorUnit,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
}
impl TryFrom<&AffirmRouterData<&PaymentsCaptureRouterData>> for AffirmCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AffirmRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let reference_id = match item.router_data.connector_request_reference_id.clone() {
ref_id if ref_id.is_empty() => None,
ref_id => Some(ref_id),
};
let amount = item.amount;
Ok(Self {
reference_id,
amount,
order_id: None,
shipping_carrier: None,
shipping_confirmation: None,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCaptureResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AffirmEventType {
Auth,
AuthExpired,
Capture,
ChargeOff,
Confirm,
ConfirmationExpired,
ExpireAuthorization,
ExpireConfirmation,
Refund,
SplitCapture,
Update,
Void,
PartialVoid,
RefundVoided,
}
impl From<AffirmEventType> for enums::AttemptStatus {
fn from(event_type: AffirmEventType) -> Self {
match event_type {
AffirmEventType::Auth => Self::Authorized,
AffirmEventType::Capture | AffirmEventType::SplitCapture | AffirmEventType::Confirm => {
Self::Charged
}
AffirmEventType::AuthExpired
| AffirmEventType::ChargeOff
| AffirmEventType::ConfirmationExpired
| AffirmEventType::ExpireAuthorization
| AffirmEventType::ExpireConfirmation => Self::Failure,
AffirmEventType::Refund | AffirmEventType::RefundVoided => Self::AutoRefunded,
AffirmEventType::Update => Self::Pending,
AffirmEventType::Void | AffirmEventType::PartialVoid => Self::Voided,
}
}
}
impl<F>
TryFrom<ResponseRouterData<F, AffirmCaptureResponse, PaymentsCaptureData, PaymentsResponseData>>
for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
AffirmCaptureResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.event_type.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for AffirmCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let request = &item.request;
let reference_id = request.connector_transaction_id.clone();
let amount = item
.request
.amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
Ok(Self {
reference_id: Some(reference_id),
amount,
merchant_transaction_id: None,
})
}
}
#[derive(Debug, Serialize)]
pub struct AffirmCancelRequest {
pub reference_id: Option<String>,
pub amount: i64,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AffirmCancelResponse {
pub id: String,
pub amount: MinorUnit,
pub created: String,
pub currency: Currency,
pub fee: Option<MinorUnit>,
pub fee_refunded: Option<MinorUnit>,
pub reference_id: Option<String>,
#[serde(rename = "type")]
pub event_type: AffirmEventType,
pub settlement_transaction_id: Option<String>,
pub transaction_id: String,
pub order_id: String,
pub shipping_carrier: Option<String>,
pub shipping_confirmation: Option<String>,
pub shipping: Option<Shipping>,
pub agent_alias: Option<String>,
pub merchant_transaction_id: Option<String>,
}
impl<F>
TryFrom<ResponseRouterData<F, AffirmCancelResponse, PaymentsCancelData, PaymentsResponseData>>
for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AffirmCancelResponse, PaymentsCancelData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.event_type.clone()),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
|
crates/hyperswitch_connectors/src/connectors/affirm/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 6,110
| null | null | null | null | null | null | null |
// Struct: ClientAuthCheckInfoResponse
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ClientAuthCheckInfoResponse
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ClientAuthCheckInfoResponse
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Struct: RoutingDictionaryRecord
// File: crates/api_models/src/routing.rs
// Module: api_models
// Implementations: 0
pub struct RoutingDictionaryRecord
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
|
RoutingDictionaryRecord
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Struct: HipayMaintenanceRequest
// File: crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct HipayMaintenanceRequest
|
crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
HipayMaintenanceRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: GlobalpayCaptureRequest
// File: crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GlobalpayCaptureRequest
|
crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
|
GlobalpayCaptureRequest
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Implementation: impl MandateSetup for for Threedsecureio
// File: crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl MandateSetup for for Threedsecureio
|
crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Threedsecureio
|
MandateSetup for
| 0
| 0
| null | null |
// Function: get_card_details_from_locker
// File: crates/router/src/core/payment_methods/cards.rs
// Module: router
pub fn get_card_details_from_locker(
state: &routes::SessionState,
pm: &domain::PaymentMethod,
) -> errors::RouterResult<api::CardDetailFromLocker>
|
crates/router/src/core/payment_methods/cards.rs
|
router
|
function_signature
| null | null | null | 68
|
get_card_details_from_locker
| null | null | null | null | null | null |
// Function: retrieve_file_and_provider_file_id_from_file_id
// File: crates/router/src/core/files/helpers.rs
// Module: router
pub fn retrieve_file_and_provider_file_id_from_file_id(
state: &SessionState,
file_id: Option<String>,
dispute_id: Option<String>,
merchant_context: &domain::MerchantContext,
is_connector_file_data_required: api::FileDataRequired,
) -> CustomResult<FileInfo, errors::ApiErrorResponse>
|
crates/router/src/core/files/helpers.rs
|
router
|
function_signature
| null | null | null | 97
|
retrieve_file_and_provider_file_id_from_file_id
| null | null | null | null | null | null |
// Function: set_debit_routing_savings
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Module: hyperswitch_domain_models
pub fn set_debit_routing_savings(&mut self, debit_routing_savings: Option<&MinorUnit>)
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 57
|
set_debit_routing_savings
| null | null | null | null | null | null |
// Struct: NmiValidateRequest
// File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NmiValidateRequest
|
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NmiValidateRequest
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Struct: SignedKey
// File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SignedKey
|
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SignedKey
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Struct: ResponseIndicators
// File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ResponseIndicators
|
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ResponseIndicators
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Paypal
// File: crates/hyperswitch_connectors/src/connectors/paypal.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Paypal
|
crates/hyperswitch_connectors/src/connectors/paypal.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Paypal
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Function: get_default_global_tenant_id
// File: crates/common_utils/src/id_type/tenant.rs
// Module: common_utils
// Documentation: Get the default global tenant ID
pub fn get_default_global_tenant_id() -> Self
|
crates/common_utils/src/id_type/tenant.rs
|
common_utils
|
function_signature
| null | null | null | 50
|
get_default_global_tenant_id
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 33
use std::str::FromStr;
use common_enums::enums;
use common_utils::{id_type, pii::Email, request::Method, types::StringMajorUnit};
use error_stack::report;
use hyperswitch_domain_models::{
network_tokenization::NetworkTokenNumber,
payment_method_data::{
BankRedirectData, Card, NetworkTokenData, PayLaterData, PaymentMethodData, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::SetupMandate,
router_request_types::{
PaymentsAuthorizeData, PaymentsCancelData, PaymentsSyncData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use super::aci_result_codes::{FAILURE_CODES, PENDING_CODES, SUCCESSFUL_CODES};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, CardData, NetworkTokenData as NetworkTokenDataTrait, PaymentsAuthorizeRequestData,
PhoneDetailsData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
trait GetCaptureMethod {
fn get_capture_method(&self) -> Option<enums::CaptureMethod>;
}
impl GetCaptureMethod for PaymentsAuthorizeData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
}
impl GetCaptureMethod for PaymentsSyncData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
self.capture_method
}
}
impl GetCaptureMethod for PaymentsCancelData {
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
None
}
}
#[derive(Debug, Serialize)]
pub struct AciRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> From<(StringMajorUnit, T)> for AciRouterData<T> {
fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
pub struct AciAuthType {
pub api_key: Secret<String>,
pub entity_id: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for AciAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = item {
Ok(Self {
api_key: api_key.to_owned(),
entity_id: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AciRecurringType {
Initial,
Repeated,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsRequest {
#[serde(flatten)]
pub txn_details: TransactionDetails,
#[serde(flatten)]
pub payment_method: PaymentDetails,
#[serde(flatten)]
pub instruction: Option<Instruction>,
pub shopper_result_url: Option<String>,
#[serde(rename = "customParameters[3DS2_enrolled]")]
pub three_ds_two_enrolled: Option<bool>,
pub recurring_type: Option<AciRecurringType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
pub entity_id: Secret<String>,
pub amount: StringMajorUnit,
pub currency: String,
pub payment_type: AciPaymentType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciCancelRequest {
pub entity_id: Secret<String>,
pub payment_type: AciPaymentType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciMandateRequest {
pub entity_id: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_brand: Option<PaymentBrand>,
#[serde(flatten)]
pub payment_details: PaymentDetails,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciMandateResponse {
pub id: String,
pub result: ResultCode,
pub build_number: String,
pub timestamp: String,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum PaymentDetails {
#[serde(rename = "card")]
AciCard(Box<CardDetails>),
BankRedirect(Box<BankRedirectionPMData>),
Wallet(Box<WalletPMData>),
Klarna,
Mandate,
AciNetworkToken(Box<AciNetworkTokenData>),
}
impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for PaymentDetails {
type Error = Error;
fn try_from(value: (&WalletData, &PaymentsAuthorizeRouterData)) -> Result<Self, Self::Error> {
let (wallet_data, item) = value;
let payment_data = match wallet_data {
WalletData::MbWayRedirect(_) => {
let phone_details = item.get_billing_phone()?;
Self::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::Mbway,
account_id: Some(phone_details.get_number_with_hash_country_code()?),
}))
}
WalletData::AliPayRedirect { .. } => Self::Wallet(Box::new(WalletPMData {
payment_brand: PaymentBrand::AliPay,
account_id: None,
})),
WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect { .. }
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect { .. }
| WalletData::VippsRedirect { .. }
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::AliPayQr(_)
| WalletData::ApplePayRedirect(_)
| WalletData::GooglePayRedirect(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
"Payment method".to_string(),
))?,
};
Ok(payment_data)
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let payment_data = match bank_redirect_data {
BankRedirectData::Eps { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eps,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Eft { .. } => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Eft,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
..
} => Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Giropay,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: bank_account_bic.clone(),
bank_account_iban: bank_account_iban.clone(),
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
})),
BankRedirectData::Ideal { bank_name, .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Ideal,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: Some(bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "ideal.bank_name",
},
)?),
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
}))
}
BankRedirectData::Sofort { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Sofortueberweisung,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: None,
}))
}
BankRedirectData::Przelewy24 { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Przelewy,
bank_account_country: None,
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: Some(item.router_data.get_billing_email()?),
}))
}
BankRedirectData::Interac { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::InteracOnline,
bank_account_country: Some(item.router_data.get_billing_country()?),
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: None,
merchant_customer_id: None,
merchant_transaction_id: None,
customer_email: Some(item.router_data.get_billing_email()?),
}))
}
BankRedirectData::Trustly { .. } => {
Self::BankRedirect(Box::new(BankRedirectionPMData {
payment_brand: PaymentBrand::Trustly,
bank_account_country: None,
bank_account_bank_name: None,
bank_account_bic: None,
bank_account_iban: None,
billing_country: Some(item.router_data.get_billing_country()?),
merchant_customer_id: Some(Secret::new(item.router_data.get_customer_id()?)),
merchant_transaction_id: Some(Secret::new(
item.router_data.connector_request_reference_id.clone(),
)),
customer_email: None,
}))
}
BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::BancontactCard { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {}
| BankRedirectData::OpenBankingUk { .. } => Err(
errors::ConnectorError::NotImplemented("Payment method".to_string()),
)?,
};
Ok(payment_data)
}
}
fn get_aci_payment_brand(
card_network: Option<common_enums::CardNetwork>,
is_network_token_flow: bool,
) -> Result<PaymentBrand, Error> {
match card_network {
Some(common_enums::CardNetwork::Visa) => Ok(PaymentBrand::Visa),
Some(common_enums::CardNetwork::Mastercard) => Ok(PaymentBrand::Mastercard),
Some(common_enums::CardNetwork::AmericanExpress) => Ok(PaymentBrand::AmericanExpress),
Some(common_enums::CardNetwork::JCB) => Ok(PaymentBrand::Jcb),
Some(common_enums::CardNetwork::DinersClub) => Ok(PaymentBrand::DinersClub),
Some(common_enums::CardNetwork::Discover) => Ok(PaymentBrand::Discover),
Some(common_enums::CardNetwork::UnionPay) => Ok(PaymentBrand::UnionPay),
Some(common_enums::CardNetwork::Maestro) => Ok(PaymentBrand::Maestro),
Some(unsupported_network) => Err(errors::ConnectorError::NotSupported {
message: format!("Card network {unsupported_network} is not supported by ACI"),
connector: "ACI",
})?,
None => {
if is_network_token_flow {
Ok(PaymentBrand::Visa)
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "card.card_network",
}
.into())
}
}
}
}
impl TryFrom<(Card, Option<Secret<String>>)> for PaymentDetails {
type Error = Error;
fn try_from(
(card_data, card_holder_name): (Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let card_expiry_year = card_data.get_expiry_year_4_digit();
let payment_brand = get_aci_payment_brand(card_data.card_network, false).ok();
Ok(Self::AciCard(Box::new(CardDetails {
card_number: card_data.card_number,
card_holder: card_holder_name.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
})?,
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year,
card_cvv: card_data.card_cvc,
payment_brand,
})))
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
)> for PaymentDetails
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (_item, network_token_data) = value;
let token_number = network_token_data.get_network_token();
let payment_brand = get_aci_payment_brand(network_token_data.card_network.clone(), true)?;
let aci_network_token_data = AciNetworkTokenData {
token_type: AciTokenAccountType::Network,
token_number,
token_expiry_month: network_token_data.get_network_token_expiry_month(),
token_expiry_year: network_token_data.get_expiry_year_4_digit(),
token_cryptogram: Some(
network_token_data
.get_cryptogram()
.clone()
.unwrap_or_default(),
),
payment_brand,
};
Ok(Self::AciNetworkToken(Box::new(aci_network_token_data)))
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AciTokenAccountType {
Network,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciNetworkTokenData {
#[serde(rename = "tokenAccount.type")]
pub token_type: AciTokenAccountType,
#[serde(rename = "tokenAccount.number")]
pub token_number: NetworkTokenNumber,
#[serde(rename = "tokenAccount.expiryMonth")]
pub token_expiry_month: Secret<String>,
#[serde(rename = "tokenAccount.expiryYear")]
pub token_expiry_year: Secret<String>,
#[serde(rename = "tokenAccount.cryptogram")]
pub token_cryptogram: Option<Secret<String>>,
#[serde(rename = "paymentBrand")]
pub payment_brand: PaymentBrand,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankRedirectionPMData {
payment_brand: PaymentBrand,
#[serde(rename = "bankAccount.country")]
bank_account_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "bankAccount.bankName")]
bank_account_bank_name: Option<common_enums::BankNames>,
#[serde(rename = "bankAccount.bic")]
bank_account_bic: Option<Secret<String>>,
#[serde(rename = "bankAccount.iban")]
bank_account_iban: Option<Secret<String>>,
#[serde(rename = "billing.country")]
billing_country: Option<api_models::enums::CountryAlpha2>,
#[serde(rename = "customer.email")]
customer_email: Option<Email>,
#[serde(rename = "customer.merchantCustomerId")]
merchant_customer_id: Option<Secret<id_type::CustomerId>>,
merchant_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletPMData {
payment_brand: PaymentBrand,
#[serde(rename = "virtualAccount.accountId")]
account_id: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PaymentBrand {
Eps,
Eft,
Ideal,
Giropay,
Sofortueberweisung,
InteracOnline,
Przelewy,
Trustly,
Mbway,
#[serde(rename = "ALIPAY")]
AliPay,
// Card network brands
#[serde(rename = "VISA")]
Visa,
#[serde(rename = "MASTER")]
Mastercard,
#[serde(rename = "AMEX")]
AmericanExpress,
#[serde(rename = "JCB")]
Jcb,
#[serde(rename = "DINERS")]
DinersClub,
#[serde(rename = "DISCOVER")]
Discover,
#[serde(rename = "UNIONPAY")]
UnionPay,
#[serde(rename = "MAESTRO")]
Maestro,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct CardDetails {
#[serde(rename = "card.number")]
pub card_number: cards::CardNumber,
#[serde(rename = "card.holder")]
pub card_holder: Secret<String>,
#[serde(rename = "card.expiryMonth")]
pub card_expiry_month: Secret<String>,
#[serde(rename = "card.expiryYear")]
pub card_expiry_year: Secret<String>,
#[serde(rename = "card.cvv")]
pub card_cvv: Secret<String>,
#[serde(rename = "paymentBrand")]
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_brand: Option<PaymentBrand>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum InstructionMode {
Initial,
Repeated,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum InstructionType {
Unscheduled,
}
#[derive(Debug, Clone, Serialize)]
pub enum InstructionSource {
#[serde(rename = "CIT")]
CardholderInitiatedTransaction,
#[serde(rename = "MIT")]
MerchantInitiatedTransaction,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
#[serde(rename = "standingInstruction.mode")]
mode: InstructionMode,
#[serde(rename = "standingInstruction.type")]
transaction_type: InstructionType,
#[serde(rename = "standingInstruction.source")]
source: InstructionSource,
create_registration: Option<bool>,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
pub struct BankDetails {
#[serde(rename = "bankAccount.holder")]
pub account_holder: Secret<String>,
}
#[allow(dead_code)]
#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum AciPaymentType {
#[serde(rename = "PA")]
Preauthorization,
#[default]
#[serde(rename = "DB")]
Debit,
#[serde(rename = "CD")]
Credit,
#[serde(rename = "CP")]
Capture,
#[serde(rename = "RV")]
Reversal,
#[serde(rename = "RF")]
Refund,
}
impl TryFrom<&AciRouterData<&PaymentsAuthorizeRouterData>> for AciPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &AciRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(ref card_data) => Self::try_from((item, card_data)),
PaymentMethodData::NetworkToken(ref network_token_data) => {
Self::try_from((item, network_token_data))
}
PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::PayLater(ref pay_later_data) => {
Self::try_from((item, pay_later_data))
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => {
Self::try_from((item, bank_redirect_data))
}
PaymentMethodData::MandatePayment => {
let mandate_id = item.router_data.request.mandate_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "mandate_id",
},
)?;
Self::try_from((item, mandate_id))
}
PaymentMethodData::Crypto(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Aci"),
))?
}
}
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &WalletData),
) -> Result<Self, Self::Error> {
let (item, wallet_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((wallet_data, item.router_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&BankRedirectData,
),
) -> Result<Self, Self::Error> {
let (item, bank_redirect_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, bank_redirect_data))?;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &PayLaterData),
) -> Result<Self, Self::Error> {
let (item, _pay_later_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::Klarna;
Ok(Self {
txn_details,
payment_method,
instruction: None,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl TryFrom<(&AciRouterData<&PaymentsAuthorizeRouterData>, &Card)> for AciPaymentsRequest {
type Error = Error;
fn try_from(
value: (&AciRouterData<&PaymentsAuthorizeRouterData>, &Card),
) -> Result<Self, Self::Error> {
let (item, card_data) = value;
let card_holder_name = item.router_data.get_optional_billing_full_name();
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((card_data.clone(), card_holder_name))?;
let instruction = get_instruction_details(item);
let recurring_type = get_recurring_type(item);
let three_ds_two_enrolled = item
.router_data
.is_three_ds()
.then_some(item.router_data.request.enrolled_for_3ds);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled,
recurring_type,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
&NetworkTokenData,
),
) -> Result<Self, Self::Error> {
let (item, network_token_data) = value;
let txn_details = get_transaction_details(item)?;
let payment_method = PaymentDetails::try_from((item, network_token_data))?;
let instruction = get_instruction_details(item);
Ok(Self {
txn_details,
payment_method,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type: None,
})
}
}
impl
TryFrom<(
&AciRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::MandateIds,
)> for AciPaymentsRequest
{
type Error = Error;
fn try_from(
value: (
&AciRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::MandateIds,
),
) -> Result<Self, Self::Error> {
let (item, _mandate_data) = value;
let instruction = get_instruction_details(item);
let txn_details = get_transaction_details(item)?;
let recurring_type = get_recurring_type(item);
Ok(Self {
txn_details,
payment_method: PaymentDetails::Mandate,
instruction,
shopper_result_url: item.router_data.request.router_return_url.clone(),
three_ds_two_enrolled: None,
recurring_type,
})
}
}
fn get_transaction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<TransactionDetails, error_stack::Report<errors::ConnectorError>> {
let auth = AciAuthType::try_from(&item.router_data.connector_auth_type)?;
let payment_type = if item.router_data.request.is_auto_capture()? {
AciPaymentType::Debit
} else {
AciPaymentType::Preauthorization
};
Ok(TransactionDetails {
entity_id: auth.entity_id,
amount: item.amount.to_owned(),
currency: item.router_data.request.currency.to_string(),
payment_type,
})
}
fn get_instruction_details(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<Instruction> {
if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession)
{
return Some(Instruction {
mode: InstructionMode::Initial,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::CardholderInitiatedTransaction,
create_registration: Some(true),
});
} else if item.router_data.request.mandate_id.is_some() {
return Some(Instruction {
mode: InstructionMode::Repeated,
transaction_type: InstructionType::Unscheduled,
source: InstructionSource::MerchantInitiatedTransaction,
create_registration: None,
});
}
None
}
fn get_recurring_type(
item: &AciRouterData<&PaymentsAuthorizeRouterData>,
) -> Option<AciRecurringType> {
if item.router_data.request.mandate_id.is_some() {
Some(AciRecurringType::Repeated)
} else if item.router_data.request.customer_acceptance.is_some()
&& item.router_data.request.setup_future_usage == Some(enums::FutureUsage::OffSession)
{
Some(AciRecurringType::Initial)
} else {
None
}
}
impl TryFrom<&PaymentsCancelRouterData> for AciCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.connector_auth_type)?;
let aci_payment_request = Self {
entity_id: auth.entity_id,
payment_type: AciPaymentType::Reversal,
};
Ok(aci_payment_request)
}
}
impl TryFrom<&RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>>
for AciMandateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let auth = AciAuthType::try_from(&item.connector_auth_type)?;
let (payment_brand, payment_details) = match &item.request.payment_method_data {
PaymentMethodData::Card(card_data) => {
let brand = get_aci_payment_brand(card_data.card_network.clone(), false).ok();
match brand.as_ref() {
Some(PaymentBrand::Visa)
| Some(PaymentBrand::Mastercard)
| Some(PaymentBrand::AmericanExpress) => (),
Some(_) => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
None => (),
};
let details = PaymentDetails::AciCard(Box::new(CardDetails {
card_number: card_data.card_number.clone(),
card_expiry_month: card_data.card_exp_month.clone(),
card_expiry_year: card_data.get_expiry_year_4_digit(),
card_cvv: card_data.card_cvc.clone(),
card_holder: card_data.card_holder_name.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
},
)?,
payment_brand: brand.clone(),
}));
(brand, details)
}
_ => {
return Err(errors::ConnectorError::NotSupported {
message: "Payment method not supported for mandate setup".to_string(),
connector: "ACI",
}
.into());
}
};
Ok(Self {
entity_id: auth.entity_id,
payment_brand,
payment_details,
})
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AciPaymentStatus {
Succeeded,
Failed,
#[default]
Pending,
RedirectShopper,
}
fn map_aci_attempt_status(item: AciPaymentStatus, auto_capture: bool) -> enums::AttemptStatus {
match item {
AciPaymentStatus::Succeeded => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
AciPaymentStatus::Failed => enums::AttemptStatus::Failure,
AciPaymentStatus::Pending => enums::AttemptStatus::Authorizing,
AciPaymentStatus::RedirectShopper => enums::AttemptStatus::AuthenticationPending,
}
}
impl FromStr for AciPaymentStatus {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if FAILURE_CODES.contains(&s) {
Ok(Self::Failed)
} else if PENDING_CODES.contains(&s) {
Ok(Self::Pending)
} else if SUCCESSFUL_CODES.contains(&s) {
Ok(Self::Succeeded)
} else {
Err(report!(errors::ConnectorError::UnexpectedResponseError(
bytes::Bytes::from(s.to_owned())
)))
}
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciPaymentsResponse {
id: String,
registration_id: Option<Secret<String>>,
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
pub(super) redirect: Option<AciRedirectionData>,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciErrorResponse {
ndc: String,
timestamp: String,
build_number: String,
pub(super) result: ResultCode,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AciRedirectionData {
pub method: Option<Method>,
pub parameters: Vec<Parameters>,
pub url: Url,
pub preconditions: Option<Vec<PreconditionData>>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PreconditionData {
pub method: Option<Method>,
pub parameters: Vec<Parameters>,
pub url: Url,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
pub struct Parameters {
pub name: String,
pub value: String,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResultCode {
pub(super) code: String,
pub(super) description: String,
pub(super) parameter_errors: Option<Vec<ErrorParameters>>,
}
#[derive(Default, Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
pub struct ErrorParameters {
pub(super) name: String,
pub(super) value: Option<String>,
pub(super) message: String,
}
impl<F, Req> TryFrom<ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>>
for RouterData<F, Req, PaymentsResponseData>
where
Req: GetCaptureMethod,
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AciPaymentsResponse, Req, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let redirection_data = item.response.redirect.map(|data| {
let mut form_fields = std::collections::HashMap::<_, _>::from_iter(
data.parameters
.iter()
.map(|parameter| (parameter.name.clone(), parameter.value.clone())),
);
if let Some(preconditions) = data.preconditions {
if let Some(first_precondition) = preconditions.first() {
for param in &first_precondition.parameters {
form_fields.insert(param.name.clone(), param.value.clone());
}
}
}
// If method is Get, parameters are appended to URL
// If method is post, we http Post the method to URL
RedirectForm::Form {
endpoint: data.url.to_string(),
// Handles method for Bank redirects currently.
|
crates/hyperswitch_connectors/src/connectors/aci/transformers.rs#chunk0
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,191
| null | null | null | null | null | null | null |
// Struct: QrCodeData
// File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct QrCodeData
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
QrCodeData
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Struct: SdkEventsRequest
// File: crates/api_models/src/analytics/sdk_events.rs
// Module: api_models
// Implementations: 0
pub struct SdkEventsRequest
|
crates/api_models/src/analytics/sdk_events.rs
|
api_models
|
struct_definition
|
SdkEventsRequest
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Implementation: impl Memoization
// File: crates/hyperswitch_constraint_graph/src/types.rs
// Module: hyperswitch_constraint_graph
// Methods: 1 total (1 public)
impl Memoization
|
crates/hyperswitch_constraint_graph/src/types.rs
|
hyperswitch_constraint_graph
|
impl_block
| null | null | null | 42
| null |
Memoization
| null | 1
| 1
| null | null |
// Struct: InjectorResponse
// File: crates/injector/src/types.rs
// Module: injector
// Implementations: 0
pub struct InjectorResponse
|
crates/injector/src/types.rs
|
injector
|
struct_definition
|
InjectorResponse
| 0
|
[] | 33
| null | null | null | null | null | null | null |
// Struct: Fiservemea
// File: crates/hyperswitch_connectors/src/connectors/fiservemea.rs
// Module: hyperswitch_connectors
// Implementations: 17
// Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications
pub struct Fiservemea
|
crates/hyperswitch_connectors/src/connectors/fiservemea.rs
|
hyperswitch_connectors
|
struct_definition
|
Fiservemea
| 17
|
[
"api::Payment",
"api::PaymentSession",
"api::ConnectorAccessToken",
"api::MandateSetup",
"api::PaymentAuthorize",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentVoid",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"api::PaymentToken",
"ConnectorCommon",
"ConnectorValidation",
"webhooks::IncomingWebhook",
"ConnectorSpecifications"
] | 134
| null | null | null | null | null | null | null |
// Implementation: impl WiseHttpStatus
// File: crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl WiseHttpStatus
|
crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 48
| null |
WiseHttpStatus
| null | 1
| 1
| null | null |
// Struct: PaymentLinkStatusData
// File: crates/hyperswitch_domain_models/src/api.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct PaymentLinkStatusData
|
crates/hyperswitch_domain_models/src/api.rs
|
hyperswitch_domain_models
|
struct_definition
|
PaymentLinkStatusData
| 0
|
[] | 43
| null | null | null | null | null | null | null |
// Implementation: impl DrainerSettings
// File: crates/scheduler/src/settings.rs
// Module: scheduler
// Methods: 1 total (1 public)
impl DrainerSettings
|
crates/scheduler/src/settings.rs
|
scheduler
|
impl_block
| null | null | null | 37
| null |
DrainerSettings
| null | 1
| 1
| null | null |
// Struct: PowertranzAuthType
// File: crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PowertranzAuthType
|
crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PowertranzAuthType
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentCapture for for Tokenio
// File: crates/hyperswitch_connectors/src/connectors/tokenio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentCapture for for Tokenio
|
crates/hyperswitch_connectors/src/connectors/tokenio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Tokenio
|
api::PaymentCapture for
| 0
| 0
| null | null |
// File: crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 17
use common_enums::enums;
use common_utils::pii::Email;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankDebitData, PaymentMethodData},
router_data::{ConnectorAuthType, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
ConnectorCustomerResponseData, PaymentsResponseData, RefundsResponseData,
},
types,
};
use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
self, missing_field_err, CardData as CardDataUtil, PaymentsAuthorizeRequestData,
RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct StaxRouterData<T> {
pub amount: f64,
pub router_data: T,
}
impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for StaxRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(currency_unit, currency, amount, item): (&api::CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
let amount = utils::get_amount_as_f64(currency_unit, amount, currency)?;
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
pub struct StaxPaymentsRequestMetaData {
tax: i64,
}
#[derive(Debug, Serialize)]
pub struct StaxPaymentsRequest {
payment_method_id: Secret<String>,
total: f64,
is_refundable: bool,
pre_auth: bool,
meta: StaxPaymentsRequestMetaData,
idempotency_id: Option<String>,
}
impl TryFrom<&StaxRouterData<&types::PaymentsAuthorizeRouterData>> for StaxPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &StaxRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
if item.router_data.request.currency != enums::Currency::USD {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Stax"),
))?
}
let total = item.amount;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(_) => {
let pm_token = item.router_data.get_payment_method_token()?;
let pre_auth = !item.router_data.request.is_auto_capture()?;
Ok(Self {
meta: StaxPaymentsRequestMetaData { tax: 0 },
total,
is_refundable: true,
pre_auth,
payment_method_id: match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Stax"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Stax"))?
}
},
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { .. }) => {
let pm_token = item.router_data.get_payment_method_token()?;
let pre_auth = !item.router_data.request.is_auto_capture()?;
Ok(Self {
meta: StaxPaymentsRequestMetaData { tax: 0 },
total,
is_refundable: true,
pre_auth,
payment_method_id: match pm_token {
PaymentMethodToken::Token(token) => token,
PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Stax"),
)?,
PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Stax"))?
}
PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Stax"))?
}
},
idempotency_id: Some(item.router_data.connector_request_reference_id.clone()),
})
}
PaymentMethodData::BankDebit(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Stax"),
))?
}
}
}
}
// Auth Struct
pub struct StaxAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for StaxAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Serialize)]
pub struct StaxCustomerRequest {
#[serde(skip_serializing_if = "Option::is_none")]
email: Option<Email>,
#[serde(skip_serializing_if = "Option::is_none")]
firstname: Option<Secret<String>>,
}
impl TryFrom<&types::ConnectorCustomerRouterData> for StaxCustomerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ConnectorCustomerRouterData) -> Result<Self, Self::Error> {
if item.request.email.is_none() && item.request.name.is_none() {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "email or name",
}
.into())
} else {
Ok(Self {
email: item.request.email.to_owned(),
firstname: item.request.name.to_owned(),
})
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StaxCustomerResponse {
id: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, StaxCustomerResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, StaxCustomerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(item.response.id.expose()),
)),
..item.data
})
}
}
#[derive(Debug, Serialize)]
pub struct StaxTokenizeData {
person_name: Secret<String>,
card_number: cards::CardNumber,
card_exp: Secret<String>,
card_cvv: Secret<String>,
customer_id: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct StaxBankTokenizeData {
person_name: Secret<String>,
bank_account: Secret<String>,
bank_routing: Secret<String>,
bank_name: common_enums::BankNames,
bank_type: common_enums::BankType,
bank_holder_type: common_enums::BankHolderType,
customer_id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(tag = "method")]
#[serde(rename_all = "lowercase")]
pub enum StaxTokenRequest {
Card(StaxTokenizeData),
Bank(StaxBankTokenizeData),
}
impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
let customer_id = item.get_connector_customer_id()?;
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card_data) => {
let stax_card_data = StaxTokenizeData {
card_exp: card_data
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string())?,
person_name: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
card_number: card_data.card_number,
card_cvv: card_data.card_cvc,
customer_id: Secret::new(customer_id),
};
Ok(Self::Card(stax_card_data))
}
PaymentMethodData::BankDebit(BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_name,
bank_type,
bank_holder_type,
..
}) => {
let stax_bank_data = StaxBankTokenizeData {
person_name: item.get_billing_full_name()?,
bank_account: account_number,
bank_routing: routing_number,
bank_name: bank_name.ok_or_else(missing_field_err("bank_name"))?,
bank_type: bank_type.ok_or_else(missing_field_err("bank_type"))?,
bank_holder_type: bank_holder_type
.ok_or_else(missing_field_err("bank_holder_type"))?,
customer_id: Secret::new(customer_id),
};
Ok(Self::Bank(stax_bank_data))
}
PaymentMethodData::BankDebit(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Stax"),
))?
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StaxTokenResponse {
id: Secret<String>,
}
impl<F, T> TryFrom<ResponseRouterData<F, StaxTokenResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, StaxTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.id.expose(),
}),
..item.data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StaxPaymentResponseTypes {
Charge,
PreAuth,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StaxChildCapture {
id: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StaxPaymentsResponse {
success: bool,
id: String,
is_captured: i8,
is_voided: bool,
child_captures: Vec<StaxChildCapture>,
#[serde(rename = "type")]
payment_response_type: StaxPaymentResponseTypes,
idempotency_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct StaxMetaData {
pub capture_id: String,
}
impl<F, T> TryFrom<ResponseRouterData<F, StaxPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, StaxPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let mut connector_metadata = None;
let mut status = match item.response.success {
true => match item.response.payment_response_type {
StaxPaymentResponseTypes::Charge => enums::AttemptStatus::Charged,
StaxPaymentResponseTypes::PreAuth => match item.response.is_captured {
0 => enums::AttemptStatus::Authorized,
_ => {
connector_metadata =
item.response.child_captures.first().map(|child_captures| {
serde_json::json!(StaxMetaData {
capture_id: child_captures.id.clone()
})
});
enums::AttemptStatus::Charged
}
},
},
false => enums::AttemptStatus::Failure,
};
if item.response.is_voided {
status = enums::AttemptStatus::Voided;
}
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(
item.response.idempotency_id.unwrap_or(item.response.id),
),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StaxCaptureRequest {
total: Option<f64>,
}
impl TryFrom<&StaxRouterData<&types::PaymentsCaptureRouterData>> for StaxCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &StaxRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let total = item.amount;
Ok(Self { total: Some(total) })
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
pub struct StaxRefundRequest {
pub total: f64,
}
impl<F> TryFrom<&StaxRouterData<&types::RefundsRouterData<F>>> for StaxRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &StaxRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self { total: item.amount })
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ChildTransactionsInResponse {
id: String,
success: bool,
created_at: String,
total: f64,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
success: bool,
child_transactions: Vec<ChildTransactionsInResponse>,
}
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 refund_amount = utils::to_currency_base_unit_asf64(
item.data.request.refund_amount,
item.data.request.currency,
)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let filtered_txn: Vec<&ChildTransactionsInResponse> = item
.response
.child_transactions
.iter()
.filter(|txn| txn.total == refund_amount)
.collect();
let mut refund_txn = filtered_txn
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
for child in filtered_txn.iter() {
if child.created_at > refund_txn.created_at {
refund_txn = child;
}
}
let refund_status = match refund_txn.success {
true => enums::RefundStatus::Success,
false => enums::RefundStatus::Failure,
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: refund_txn.id.clone(),
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 refund_status = match item.response.success {
true => enums::RefundStatus::Success,
false => enums::RefundStatus::Failure,
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StaxWebhookEventType {
PreAuth,
Capture,
Charge,
Void,
Refund,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct StaxWebhookBody {
#[serde(rename = "type")]
pub transaction_type: StaxWebhookEventType,
pub id: String,
pub auth_id: Option<String>,
pub success: bool,
}
|
crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 3,976
| null | null | null | null | null | null | null |
// Implementation: impl IntermediateString
// File: crates/external_services/src/email.rs
// Module: external_services
// Methods: 2 total (2 public)
impl IntermediateString
|
crates/external_services/src/email.rs
|
external_services
|
impl_block
| null | null | null | 37
| null |
IntermediateString
| null | 2
| 2
| null | null |
// Struct: BankOfAmericaRsyncResponse
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BankOfAmericaRsyncResponse
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BankOfAmericaRsyncResponse
| 0
|
[] | 56
| null | null | null | null | null | null | null |
// Function: new
// File: crates/diesel_models/src/subscription.rs
// Module: diesel_models
pub fn new(
id: common_utils::id_type::SubscriptionId,
status: String,
billing_processor: Option<String>,
payment_method_id: Option<String>,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
client_secret: Option<String>,
connector_subscription_id: Option<String>,
merchant_id: common_utils::id_type::MerchantId,
customer_id: common_utils::id_type::CustomerId,
metadata: Option<SecretSerdeValue>,
profile_id: common_utils::id_type::ProfileId,
merchant_reference_id: Option<String>,
) -> Self
|
crates/diesel_models/src/subscription.rs
|
diesel_models
|
function_signature
| null | null | null | 151
|
new
| null | null | null | null | null | null |
// Struct: TokenizedCard
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct TokenizedCard
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
TokenizedCard
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: to_field_value_pairs
// File: crates/diesel_models/src/kv.rs
// Module: diesel_models
pub fn to_field_value_pairs(
&self,
request_id: String,
global_id: String,
) -> crate::StorageResult<Vec<(&str, String)>>
|
crates/diesel_models/src/kv.rs
|
diesel_models
|
function_signature
| null | null | null | 63
|
to_field_value_pairs
| null | null | null | null | null | null |
// Implementation: impl api::MandateSetup for for Tesouro
// File: crates/hyperswitch_connectors/src/connectors/tesouro.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::MandateSetup for for Tesouro
|
crates/hyperswitch_connectors/src/connectors/tesouro.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Tesouro
|
api::MandateSetup for
| 0
| 0
| null | null |
// Struct: Routing
// File: crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Routing
|
crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Routing
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Struct: PaymentAccountCardInformation
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentAccountCardInformation
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentAccountCardInformation
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: ExternalVaultTokenData
// File: crates/api_models/src/payment_methods.rs
// Module: api_models
// Implementations: 0
pub struct ExternalVaultTokenData
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
|
ExternalVaultTokenData
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Paybox
// File: crates/hyperswitch_connectors/src/connectors/paybox.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Paybox
|
crates/hyperswitch_connectors/src/connectors/paybox.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Paybox
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Function: create_address
// File: crates/diesel_models/src/address.rs
// Module: diesel_models
pub fn create_address(self, source: Address) -> Address
|
crates/diesel_models/src/address.rs
|
diesel_models
|
function_signature
| null | null | null | 35
|
create_address
| null | null | null | null | null | null |
// Implementation: impl GlobalCustomerId
// File: crates/common_utils/src/id_type/global_id/customer.rs
// Module: common_utils
// Methods: 2 total (2 public)
impl GlobalCustomerId
|
crates/common_utils/src/id_type/global_id/customer.rs
|
common_utils
|
impl_block
| null | null | null | 40
| null |
GlobalCustomerId
| null | 2
| 2
| null | null |
// Function: new_password_without_validation
// File: crates/router/src/types/domain/user.rs
// Module: router
pub fn new_password_without_validation(password: Secret<String>) -> UserResult<Self>
|
crates/router/src/types/domain/user.rs
|
router
|
function_signature
| null | null | null | 40
|
new_password_without_validation
| null | null | null | null | null | null |
// Struct: AcceptDisputeRequestData
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct AcceptDisputeRequestData
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
AcceptDisputeRequestData
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Struct: TokenioAuthType
// File: crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct TokenioAuthType
|
crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
TokenioAuthType
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Implementation: impl BlackList for for AuthToken
// File: crates/router/src/services/authentication/blacklist.rs
// Module: router
// Methods: 1 total (0 public)
impl BlackList for for AuthToken
|
crates/router/src/services/authentication/blacklist.rs
|
router
|
impl_block
| null | null | null | 45
| null |
AuthToken
|
BlackList for
| 1
| 0
| null | null |
// Struct: ApiErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ApiErrorResponse
|
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ApiErrorResponse
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Struct: BlikBankRedirectAdditionalData
// File: crates/api_models/src/payments/additional_info.rs
// Module: api_models
// Implementations: 0
pub struct BlikBankRedirectAdditionalData
|
crates/api_models/src/payments/additional_info.rs
|
api_models
|
struct_definition
|
BlikBankRedirectAdditionalData
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Implementation: impl super::payments::metrics::PaymentMetricAnalytics for for SqlxClient
// File: crates/analytics/src/sqlx.rs
// Module: analytics
// Methods: 0 total (0 public)
impl super::payments::metrics::PaymentMetricAnalytics for for SqlxClient
|
crates/analytics/src/sqlx.rs
|
analytics
|
impl_block
| null | null | null | 60
| null |
SqlxClient
|
super::payments::metrics::PaymentMetricAnalytics for
| 0
| 0
| null | null |
// Struct: GetParentGroupsInfoQueryParams
// File: crates/api_models/src/user_role/role.rs
// Module: api_models
// Implementations: 0
pub struct GetParentGroupsInfoQueryParams
|
crates/api_models/src/user_role/role.rs
|
api_models
|
struct_definition
|
GetParentGroupsInfoQueryParams
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 12
use common_enums::enums::{self, AuthenticationType};
use common_utils::pii::IpAddress;
use hyperswitch_domain_models::{
payment_method_data::{Card, PaymentMethodData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::Execute,
router_request_types::{
BrowserInformation, PaymentsCancelData, PaymentsCaptureData, ResponseId,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{self, CardData, PaymentsAuthorizeRequestData, RouterData as _},
};
const ISO_SUCCESS_CODES: [&str; 7] = ["00", "3D0", "3D1", "HP0", "TK0", "SP4", "FC0"];
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzPaymentsRequest {
transaction_identifier: String,
total_amount: f64,
currency_code: String,
three_d_secure: bool,
source: Source,
order_identifier: String,
// billing and shipping are optional fields and requires state in iso codes, hence commenting it
// can be added later if we have iso code for state
// billing_address: Option<PowertranzAddressDetails>,
// shipping_address: Option<PowertranzAddressDetails>,
extended_data: Option<ExtendedData>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ExtendedData {
three_d_secure: ThreeDSecure,
merchant_response_url: String,
browser_info: BrowserInfo,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct BrowserInfo {
java_enabled: Option<bool>,
javascript_enabled: Option<bool>,
accept_header: Option<String>,
language: Option<String>,
screen_height: Option<String>,
screen_width: Option<String>,
time_zone: Option<String>,
user_agent: Option<String>,
i_p: Option<Secret<String, IpAddress>>,
color_depth: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ThreeDSecure {
challenge_window_size: u8,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum Source {
Card(PowertranzCard),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzCard {
cardholder_name: Secret<String>,
card_pan: cards::CardNumber,
card_expiration: Secret<String>,
card_cvv: Secret<String>,
}
// #[derive(Debug, Serialize)]
// #[serde(rename_all = "PascalCase")]
// pub struct PowertranzAddressDetails {
// first_name: Option<Secret<String>>,
// last_name: Option<Secret<String>>,
// line1: Option<Secret<String>>,
// line2: Option<Secret<String>>,
// city: Option<String>,
// country: Option<enums::CountryAlpha2>,
// state: Option<Secret<String>>,
// postal_code: Option<Secret<String>>,
// email_address: Option<Email>,
// phone_number: Option<Secret<String>>,
// }
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RedirectResponsePayload {
pub spi_token: Secret<String>,
}
impl TryFrom<&PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let source = match item.request.payment_method_data.clone() {
PaymentMethodData::Card(card) => {
let card_holder_name = item.get_optional_billing_full_name();
Source::try_from((&card, card_holder_name))
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotSupported {
message: utils::SELECTED_PAYMENT_METHOD.to_string(),
connector: "powertranz",
}
.into())
}
}?;
// let billing_address = get_address_details(&item.address.billing, &item.request.email);
// let shipping_address = get_address_details(&item.address.shipping, &item.request.email);
let (three_d_secure, extended_data) = match item.auth_type {
AuthenticationType::ThreeDs => (true, Some(ExtendedData::try_from(item)?)),
AuthenticationType::NoThreeDs => (false, None),
};
Ok(Self {
transaction_identifier: Uuid::new_v4().to_string(),
total_amount: utils::to_currency_base_unit_asf64(
item.request.amount,
item.request.currency,
)?,
currency_code: item.request.currency.iso_4217().to_string(),
three_d_secure,
source,
order_identifier: item.connector_request_reference_id.clone(),
// billing_address,
// shipping_address,
extended_data,
})
}
}
impl TryFrom<&PaymentsAuthorizeRouterData> for ExtendedData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
Ok(Self {
three_d_secure: ThreeDSecure {
// Merchants preferred sized of challenge window presented to cardholder.
// 5 maps to 100% of challenge window size
challenge_window_size: 5,
},
merchant_response_url: item.request.get_complete_authorize_url()?,
browser_info: BrowserInfo::try_from(&item.request.get_browser_info()?)?,
})
}
}
impl TryFrom<&BrowserInformation> for BrowserInfo {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &BrowserInformation) -> Result<Self, Self::Error> {
Ok(Self {
java_enabled: item.java_enabled,
javascript_enabled: item.java_script_enabled,
accept_header: item.accept_header.clone(),
language: item.language.clone(),
screen_height: item.screen_height.map(|height| height.to_string()),
screen_width: item.screen_width.map(|width| width.to_string()),
time_zone: item.time_zone.map(|zone| zone.to_string()),
user_agent: item.user_agent.clone(),
i_p: item
.ip_address
.map(|ip_address| Secret::new(ip_address.to_string())),
color_depth: item.color_depth.map(|depth| depth.to_string()),
})
}
}
/*fn get_address_details(
address: &Option<Address>,
email: &Option<Email>,
) -> Option<PowertranzAddressDetails> {
let phone_number = address
.as_ref()
.and_then(|address| address.phone.as_ref())
.and_then(|phone| {
phone.number.as_ref().and_then(|number| {
phone.country_code.as_ref().map(|country_code| {
Secret::new(format!("{}{}", country_code, number.clone().expose()))
})
})
});
address
.as_ref()
.and_then(|address| address.address.as_ref())
.map(|address_details| PowertranzAddressDetails {
first_name: address_details.first_name.clone(),
last_name: address_details.last_name.clone(),
line1: address_details.line1.clone(),
line2: address_details.line2.clone(),
city: address_details.city.clone(),
country: address_details.country,
state: address_details.state.clone(),
postal_code: address_details.zip.clone(),
email_address: email.clone(),
phone_number,
})
}*/
impl TryFrom<(&Card, Option<Secret<String>>)> for Source {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card, card_holder_name): (&Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let card = PowertranzCard {
cardholder_name: card_holder_name.unwrap_or(Secret::new("".to_string())),
card_pan: card.card_number.clone(),
card_expiration: card.get_expiry_date_as_yymm()?,
card_cvv: card.card_cvc.clone(),
};
Ok(Self::Card(card))
}
}
// Auth Struct
pub struct PowertranzAuthType {
pub(super) power_tranz_id: Secret<String>,
pub(super) power_tranz_password: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PowertranzAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
power_tranz_id: key1.to_owned(),
power_tranz_password: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
// Common struct used in Payment, Capture, Void, Refund
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzBaseResponse {
transaction_type: u8,
approved: bool,
transaction_identifier: String,
original_trxn_identifier: Option<String>,
errors: Option<Vec<Error>>,
iso_response_code: String,
redirect_data: Option<Secret<String>>,
response_message: String,
order_identifier: String,
}
fn get_status((transaction_type, approved, is_3ds): (u8, bool, bool)) -> enums::AttemptStatus {
match transaction_type {
// Auth
1 => match approved {
true => enums::AttemptStatus::Authorized,
false => match is_3ds {
true => enums::AttemptStatus::AuthenticationPending,
false => enums::AttemptStatus::Failure,
},
},
// Sale
2 => match approved {
true => enums::AttemptStatus::Charged,
false => match is_3ds {
true => enums::AttemptStatus::AuthenticationPending,
false => enums::AttemptStatus::Failure,
},
},
// Capture
3 => match approved {
true => enums::AttemptStatus::Charged,
false => enums::AttemptStatus::Failure,
},
// Void
4 => match approved {
true => enums::AttemptStatus::Voided,
false => enums::AttemptStatus::VoidFailed,
},
// Refund
5 => match approved {
true => enums::AttemptStatus::AutoRefunded,
false => enums::AttemptStatus::Failure,
},
// Risk Management
_ => match approved {
true => enums::AttemptStatus::Pending,
false => enums::AttemptStatus::Failure,
},
}
}
impl<F, T> TryFrom<ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, PowertranzBaseResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let error_response = build_error_response(&item.response, item.http_code);
// original_trxn_identifier will be present only in capture and void
let connector_transaction_id = item
.response
.original_trxn_identifier
.unwrap_or(item.response.transaction_identifier.clone());
let redirection_data = item.response.redirect_data.map(|redirect_data| {
hyperswitch_domain_models::router_response_types::RedirectForm::Html {
html_data: redirect_data.expose(),
}
});
let response = error_response.map_or(
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(connector_transaction_id),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_identifier),
incremental_authorization_allowed: None,
charges: None,
}),
Err,
);
Ok(Self {
status: get_status((
item.response.transaction_type,
item.response.approved,
is_3ds_payment(item.response.iso_response_code),
)),
response,
..item.data
})
}
}
fn is_3ds_payment(response_code: String) -> bool {
matches!(response_code.as_str(), "SP4")
}
// Type definition for Capture, Void, Refund Request
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzBaseRequest {
transaction_identifier: String,
total_amount: Option<f64>,
refund: Option<bool>,
}
impl TryFrom<&PaymentsCancelData> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelData) -> Result<Self, Self::Error> {
Ok(Self {
transaction_identifier: item.connector_transaction_id.clone(),
total_amount: None,
refund: None,
})
}
}
impl TryFrom<&PaymentsCaptureData> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCaptureData) -> Result<Self, Self::Error> {
let total_amount = Some(utils::to_currency_base_unit_asf64(
item.amount_to_capture,
item.currency,
)?);
Ok(Self {
transaction_identifier: item.connector_transaction_id.clone(),
total_amount,
refund: None,
})
}
}
impl<F> TryFrom<&RefundsRouterData<F>> for PowertranzBaseRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &RefundsRouterData<F>) -> Result<Self, Self::Error> {
let total_amount = Some(utils::to_currency_base_unit_asf64(
item.request.refund_amount,
item.request.currency,
)?);
Ok(Self {
transaction_identifier: item.request.connector_transaction_id.clone(),
total_amount,
refund: Some(true),
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, PowertranzBaseResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, PowertranzBaseResponse>,
) -> Result<Self, Self::Error> {
let error_response = build_error_response(&item.response, item.http_code);
let response = error_response.map_or(
Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_identifier.to_string(),
refund_status: match item.response.approved {
true => enums::RefundStatus::Success,
false => enums::RefundStatus::Failure,
},
}),
Err,
);
Ok(Self {
response,
..item.data
})
}
}
fn build_error_response(item: &PowertranzBaseResponse, status_code: u16) -> Option<ErrorResponse> {
// errors object has highest precedence to get error message and code
let error_response = if item.errors.is_some() {
item.errors.as_ref().map(|errors| {
let first_error = errors.first();
let code = first_error.map(|error| error.code.clone());
let message = first_error.map(|error| error.message.clone());
ErrorResponse {
status_code,
code: code.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: message.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
reason: Some(
errors
.iter()
.map(|error| format!("{} : {}", error.code, error.message))
.collect::<Vec<_>>()
.join(", "),
),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
})
} else if !ISO_SUCCESS_CODES.contains(&item.iso_response_code.as_str()) {
// Incase error object is not present the error message and code should be propagated based on iso_response_code
Some(ErrorResponse {
status_code,
code: item.iso_response_code.clone(),
message: item.response_message.clone(),
reason: Some(item.response_message.clone()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
error_response
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct PowertranzErrorResponse {
pub errors: Vec<Error>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct Error {
pub code: String,
pub message: String,
}
|
crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 3,886
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentToken for for Tokenio
// File: crates/hyperswitch_connectors/src/connectors/tokenio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Tokenio
|
crates/hyperswitch_connectors/src/connectors/tokenio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Tokenio
|
api::PaymentToken for
| 0
| 0
| null | null |
// Implementation: impl Capturable for for PaymentsCancelData
// File: crates/router/src/types.rs
// Module: router
// Methods: 2 total (0 public)
impl Capturable for for PaymentsCancelData
|
crates/router/src/types.rs
|
router
|
impl_block
| null | null | null | 44
| null |
PaymentsCancelData
|
Capturable for
| 2
| 0
| null | null |
// Function: construct_router_data_to_update_calculated_tax
// File: crates/router/src/core/payments/transformers.rs
// Module: router
pub fn construct_router_data_to_update_calculated_tax<'a, F, T>(
state: &'a SessionState,
payment_data: PaymentData<F>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
types::RouterData<F, T, types::PaymentsResponseData>: Feature<F, T>,
F: Clone,
error_stack::Report<errors::ApiErrorResponse>:
From<<T as TryFrom<PaymentAdditionalData<'a, F>>>::Error>,
|
crates/router/src/core/payments/transformers.rs
|
router
|
function_signature
| null | null | null | 196
|
construct_router_data_to_update_calculated_tax
| null | null | null | null | null | null |
// Function: convert_forex
// File: crates/router/src/core/currency.rs
// Module: router
pub fn convert_forex(
state: SessionState,
amount: i64,
to_currency: String,
from_currency: String,
) -> CustomResult<
ApplicationResponse<api_models::currency::CurrencyConversionResponse>,
ApiErrorResponse,
>
|
crates/router/src/core/currency.rs
|
router
|
function_signature
| null | null | null | 77
|
convert_forex
| null | null | null | null | null | null |
// Function: get_acs_reference_number
// File: crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
// Module: hyperswitch_domain_models
pub fn get_acs_reference_number(&self) -> Option<String>
|
crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 48
|
get_acs_reference_number
| null | null | null | null | null | null |
// File: crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
// Module: hyperswitch_domain_models
// Public structs: 10
use api_models;
use common_enums;
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
pii::Email,
};
use diesel_models::types::OrderDetailsWithAmount;
use masking::Secret;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::router_request_types;
#[derive(Debug, Clone)]
pub struct FraudCheckSaleData {
pub amount: i64,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub currency: Option<common_enums::Currency>,
pub email: Option<Email>,
}
#[derive(Debug, Clone)]
pub struct FraudCheckCheckoutData {
pub amount: i64,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub currency: Option<common_enums::Currency>,
pub browser_info: Option<router_request_types::BrowserInformation>,
pub payment_method_data: Option<api_models::payments::AdditionalPaymentData>,
pub email: Option<Email>,
pub gateway: Option<String>,
}
#[derive(Debug, Clone)]
pub struct FraudCheckTransactionData {
pub amount: i64,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub currency: Option<common_enums::Currency>,
pub payment_method: Option<common_enums::PaymentMethod>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub connector_transaction_id: Option<String>,
//The name of the payment gateway or financial institution that processed the transaction.
pub connector: Option<String>,
}
#[derive(Debug, Clone)]
pub struct FraudCheckRecordReturnData {
pub amount: i64,
pub currency: Option<common_enums::Currency>,
pub refund_method: RefundMethod,
pub refund_transaction_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundMethod {
StoreCredit,
OriginalPaymentInstrument,
NewPaymentInstrument,
}
#[derive(Debug, Clone)]
pub struct FraudCheckFulfillmentData {
pub amount: i64,
pub order_details: Option<Vec<Secret<serde_json::Value>>>,
pub fulfillment_req: FrmFulfillmentRequest,
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct FrmFulfillmentRequest {
///unique payment_id for the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub payment_id: common_utils::id_type::PaymentId,
///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>,
//name of the tracking Company
#[schema(max_length = 255, example = "fedex")]
pub tracking_company: Option<String>,
//tracking ID of the product
#[schema(example = r#"["track_8327446667", "track_8327446668"]"#)]
pub tracking_numbers: Option<Vec<String>>,
//tracking_url for tracking the product
pub tracking_urls: Option<Vec<String>>,
// The name of the Shipper.
pub carrier: Option<String>,
// Fulfillment method for the shipment.
pub fulfillment_method: Option<String>,
// Statuses to indicate shipment state.
pub shipment_status: Option<String>,
// The date and time items are ready to be shipped.
pub shipped_at: Option<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct Fulfillments {
///shipment_id of the shipped items
#[schema(max_length = 255, example = "ship_101")]
pub shipment_id: String,
///products sent in the shipment
#[schema(value_type = Option<Vec<Product>>)]
pub products: Option<Vec<Product>>,
///destination address of the shipment
#[schema(value_type = Destination)]
pub destination: Destination,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(untagged)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub enum FulfillmentStatus {
PARTIAL,
COMPLETE,
REPLACEMENT,
CANCELED,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct Product {
pub item_name: String,
pub item_quantity: i64,
pub item_id: String,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct Destination {
pub full_name: Secret<String>,
pub organization: Option<String>,
pub email: Option<Email>,
pub address: Address,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct Address {
pub street_address: Secret<String>,
pub unit: Option<Secret<String>>,
pub postal_code: Secret<String>,
pub city: String,
pub province_code: Secret<String>,
pub country_code: common_enums::CountryAlpha2,
}
impl ApiEventMetric for FrmFulfillmentRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::FraudCheck)
}
}
|
crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 1,389
| null | null | null | null | null | null | null |
// Implementation: impl UserInterface for for KafkaStore
// File: crates/router/src/db/kafka_store.rs
// Module: router
// Methods: 7 total (0 public)
impl UserInterface for for KafkaStore
|
crates/router/src/db/kafka_store.rs
|
router
|
impl_block
| null | null | null | 45
| null |
KafkaStore
|
UserInterface for
| 7
| 0
| null | null |
// Function: get_connector_transaction_id
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
pub fn get_connector_transaction_id(
&self,
) -> errors::CustomResult<String, errors::ValidationError>
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 56
|
get_connector_transaction_id
| null | null | null | null | null | null |
// Struct: UpdateUserRoleRequest
// File: crates/api_models/src/user_role.rs
// Module: api_models
// Implementations: 0
pub struct UpdateUserRoleRequest
|
crates/api_models/src/user_role.rs
|
api_models
|
struct_definition
|
UpdateUserRoleRequest
| 0
|
[] | 36
| null | null | null | null | null | null | null |
// Struct: BankAccountOptionalIDs
// File: crates/pm_auth/src/types.rs
// Module: pm_auth
// Implementations: 0
pub struct BankAccountOptionalIDs
|
crates/pm_auth/src/types.rs
|
pm_auth
|
struct_definition
|
BankAccountOptionalIDs
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Implementation: impl MandateSetup for for Payone
// File: crates/hyperswitch_connectors/src/connectors/payone.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl MandateSetup for for Payone
|
crates/hyperswitch_connectors/src/connectors/payone.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Payone
|
MandateSetup for
| 0
| 0
| null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/phonepe.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/phonepe.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 39
| null | null | null | null | null | 1
| 0
|
// Struct: CybersourceErrorInformationResponse
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CybersourceErrorInformationResponse
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CybersourceErrorInformationResponse
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Struct: RefundResponse
// File: crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundResponse
|
crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundResponse
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Implementation: impl Nuvei
// File: crates/hyperswitch_connectors/src/connectors/nuvei.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl Nuvei
|
crates/hyperswitch_connectors/src/connectors/nuvei.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 49
| null |
Nuvei
| null | 1
| 1
| null | null |
// Struct: JpmorganPaymentMethodTypeCancelResponse
// File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct JpmorganPaymentMethodTypeCancelResponse
|
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
JpmorganPaymentMethodTypeCancelResponse
| 0
|
[] | 58
| null | null | null | null | null | null | null |
// Struct: VaultRetrieve
// File: crates/router/src/types/payment_methods.rs
// Module: router
// Implementations: 1
// Traits: VaultingInterface
pub struct VaultRetrieve
|
crates/router/src/types/payment_methods.rs
|
router
|
struct_definition
|
VaultRetrieve
| 1
|
[
"VaultingInterface"
] | 40
| null | null | null | null | null | null | null |
// Struct: ReversalInformation
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ReversalInformation
|
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ReversalInformation
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Custombilling
// File: crates/hyperswitch_connectors/src/connectors/custombilling.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Custombilling
|
crates/hyperswitch_connectors/src/connectors/custombilling.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Custombilling
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Implementation: impl PartialEq for for ActivePaymentsMetricsBucketIdentifier
// File: crates/api_models/src/analytics/active_payments.rs
// Module: api_models
// Methods: 1 total (0 public)
impl PartialEq for for ActivePaymentsMetricsBucketIdentifier
|
crates/api_models/src/analytics/active_payments.rs
|
api_models
|
impl_block
| null | null | null | 52
| null |
ActivePaymentsMetricsBucketIdentifier
|
PartialEq for
| 1
| 0
| null | null |
// Struct: ArchipelPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ArchipelPaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ArchipelPaymentsResponse
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// File: crates/router_env/tests/test_module.rs
// Module: router_env
// Public functions: 2
use router_env as logger;
#[tracing::instrument(skip_all)]
pub async fn fn_with_colon(val: i32) {
let a = 13;
let b = 31;
logger::log!(
logger::Level::WARN,
?a,
?b,
tag = ?logger::Tag::ApiIncomingRequest,
category = ?logger::Category::Api,
flow = "some_flow",
session_id = "some_session",
answer = 13,
message2 = "yyy",
message = "Experiment",
val,
);
fn_without_colon(131).await;
}
#[tracing::instrument(fields(val3 = "abc"), skip_all)]
pub async fn fn_without_colon(val: i32) {
let a = 13;
let b = 31;
// trace_macros!(true);
logger::log!(
logger::Level::INFO,
?a,
?b,
tag = ?logger::Tag::ApiIncomingRequest,
category = ?logger::Category::Api,
flow = "some_flow",
session_id = "some_session",
answer = 13,
message2 = "yyy",
message = "Experiment",
val,
);
// trace_macros!(false);
}
|
crates/router_env/tests/test_module.rs
|
router_env
|
full_file
| null | null | null | 305
| null | null | null | null | null | null | null |
// Function: get_shipping_address
// File: crates/api_models/src/authentication.rs
// Module: api_models
pub fn get_shipping_address(&self) -> Option<Address>
|
crates/api_models/src/authentication.rs
|
api_models
|
function_signature
| null | null | null | 35
|
get_shipping_address
| null | null | null | null | null | null |
// File: crates/router/src/routes/verification.rs
// Module: router
// Public functions: 3
use actix_web::{web, HttpRequest, Responder};
use api_models::verifications;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
use crate::{
core::{api_locking, verification},
services::{api, authentication as auth, authorization::permissions::Permission},
};
#[cfg(all(feature = "olap", feature = "v1"))]
#[instrument(skip_all, fields(flow = ?Flow::Verification))]
pub async fn apple_pay_merchant_registration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>,
path: web::Path<common_utils::id_type::MerchantId>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
verification::verify_merchant_creds_for_applepay(
state.clone(),
body,
merchant_id.clone(),
auth.profile_id,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all, fields(flow = ?Flow::Verification))]
pub async fn apple_pay_merchant_registration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>,
path: web::Path<common_utils::id_type::MerchantId>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: auth::AuthenticationData, body, _| {
verification::verify_merchant_creds_for_applepay(
state.clone(),
body,
merchant_id.clone(),
Some(auth.profile.get_id().clone()),
)
},
auth::auth_type(
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
&auth::JWTAuth {
permission: Permission::ProfileAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::Verification))]
pub async fn retrieve_apple_pay_verified_domains(
state: web::Data<AppState>,
req: HttpRequest,
params: web::Query<verifications::ApplepayGetVerifiedDomainsParam>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = ¶ms.merchant_id;
let mca_id = ¶ms.merchant_connector_account_id;
Box::pin(api::server_wrap(
flow,
state,
&req,
merchant_id.clone(),
|state, _: auth::AuthenticationData, _, _| {
verification::get_verified_apple_domains_with_mid_mca_id(
state,
merchant_id.to_owned(),
mca_id.clone(),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantAccountRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/verification.rs
|
router
|
full_file
| null | null | null | 844
| null | null | null | null | null | null | null |
// Struct: ProfileAcquirer
// File: crates/router/src/routes/app.rs
// Module: router
// Implementations: 1
pub struct ProfileAcquirer
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
|
ProfileAcquirer
| 1
|
[] | 34
| null | null | null | null | null | null | null |
// Function: spawn
// File: crates/drainer/src/handler.rs
// Module: drainer
pub fn spawn(&self) -> errors::DrainerResult<()>
|
crates/drainer/src/handler.rs
|
drainer
|
function_signature
| null | null | null | 35
|
spawn
| null | null | null | null | null | null |
// Implementation: impl common_utils::events::ApiEventMetric for for RoutingEvaluateResponse
// File: crates/api_models/src/routing.rs
// Module: api_models
// Methods: 0 total (0 public)
impl common_utils::events::ApiEventMetric for for RoutingEvaluateResponse
|
crates/api_models/src/routing.rs
|
api_models
|
impl_block
| null | null | null | 59
| null |
RoutingEvaluateResponse
|
common_utils::events::ApiEventMetric for
| 0
| 0
| null | null |
// Function: signout
// File: crates/router/src/routes/user.rs
// Module: router
pub fn signout(state: web::Data<AppState>, http_req: HttpRequest) -> HttpResponse
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| null | null | null | 40
|
signout
| null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Loonio
// File: crates/hyperswitch_connectors/src/connectors/loonio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Loonio
|
crates/hyperswitch_connectors/src/connectors/loonio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Loonio
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Struct: BamboraAuthType
// File: crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BamboraAuthType
|
crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BamboraAuthType
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: SubscriptionUpdate
// File: crates/diesel_models/src/subscription.rs
// Module: diesel_models
// Implementations: 1
pub struct SubscriptionUpdate
|
crates/diesel_models/src/subscription.rs
|
diesel_models
|
struct_definition
|
SubscriptionUpdate
| 1
|
[] | 35
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Helcim
// File: crates/hyperswitch_connectors/src/connectors/helcim.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Helcim
|
crates/hyperswitch_connectors/src/connectors/helcim.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 63
| null |
Helcim
|
api::RefundExecute for
| 0
| 0
| null | null |
.is_customer_initiated_mandate_payment()
{
item.router_data.customer_id.as_ref().and_then(|customer| {
let customer_id = customer.get_string_repr();
(customer_id.len() <= MAX_ID_LENGTH).then_some(CustomerDetails {
id: customer_id.to_string(),
email: item.router_data.request.get_optional_email(),
})
})
} else {
None
};
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: Some(ccard.card_cvc.clone()),
})),
profile,
order: Order {
invoice_number: match &item.router_data.request.merchant_order_reference_id {
Some(merchant_order_reference_id) => {
if merchant_order_reference_id.len() <= MAX_ID_LENGTH {
merchant_order_reference_id.to_string()
} else {
get_random_string()
}
}
None => get_random_string(),
},
description: item.router_data.connector_request_reference_id.clone(),
},
customer,
bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: address.line1.clone(),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
}),
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: None,
subsequent_auth_information: None,
authorization_indicator_type: match item.router_data.request.capture_method {
Some(capture_method) => Some(AuthorizationIndicator {
authorization_indicator: capture_method.try_into()?,
}),
None => None,
},
})
}
}
impl
TryFrom<(
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&WalletData,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, wallet_data): (
&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
&WalletData,
),
) -> Result<Self, Self::Error> {
let profile = if item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
let connector_customer_id =
Secret::new(item.router_data.connector_customer.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "connector_customer_id".to_string(),
},
)?);
Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
create_profile: true,
customer_profile_id: Some(connector_customer_id),
}))
} else {
None
};
let customer = if !item
.router_data
.request
.is_customer_initiated_mandate_payment()
{
item.router_data.customer_id.as_ref().and_then(|customer| {
let customer_id = customer.get_string_repr();
(customer_id.len() <= MAX_ID_LENGTH).then_some(CustomerDetails {
id: customer_id.to_string(),
email: item.router_data.request.get_optional_email(),
})
})
} else {
None
};
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(get_wallet_data(
wallet_data,
&item.router_data.request.complete_authorize_url,
)?),
profile,
order: Order {
invoice_number: match &item.router_data.request.merchant_order_reference_id {
Some(merchant_order_reference_id) => {
if merchant_order_reference_id.len() <= MAX_ID_LENGTH {
merchant_order_reference_id.to_string()
} else {
get_random_string()
}
}
None => get_random_string(),
},
description: item.router_data.connector_request_reference_id.clone(),
},
customer,
bill_to: item
.router_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| BillTo {
first_name: address.first_name.clone(),
last_name: address.last_name.clone(),
address: address.line1.clone(),
city: address.city.clone(),
state: address.state.clone(),
zip: address.zip.clone(),
country: address.country,
}),
user_fields: match item.router_data.request.metadata.clone() {
Some(metadata) => Some(UserFields {
user_field: Vec::<UserField>::foreign_try_from(metadata)?,
}),
None => None,
},
processing_options: None,
subsequent_auth_information: None,
authorization_indicator_type: match item.router_data.request.capture_method {
Some(capture_method) => Some(AuthorizationIndicator {
authorization_indicator: capture_method.try_into()?,
}),
None => None,
},
})
}
}
impl TryFrom<&PaymentsCancelRouterData> for CancelOrCaptureTransactionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
amount: None, //amount is not required for void
transaction_type: TransactionType::Void,
ref_trans_id: item.request.connector_transaction_id.to_string(),
};
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication,
transaction_request,
},
})
}
}
impl TryFrom<&AuthorizedotnetRouterData<&PaymentsCaptureRouterData>>
for CancelOrCaptureTransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
amount: Some(item.amount),
transaction_type: TransactionType::Capture,
ref_trans_id: item
.router_data
.request
.connector_transaction_id
.to_string(),
};
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
create_transaction_request: AuthorizedotnetPaymentCancelOrCaptureRequest {
merchant_authentication,
transaction_request,
},
})
}
}
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub enum AuthorizedotnetPaymentStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
#[default]
HeldForReview,
#[serde(rename = "5")]
RequiresAction,
}
#[derive(Debug, Clone, serde::Deserialize, Serialize)]
pub enum AuthorizedotnetRefundStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
HeldForReview,
}
fn get_payment_status(
(item, auto_capture): (AuthorizedotnetPaymentStatus, bool),
) -> enums::AttemptStatus {
match item {
AuthorizedotnetPaymentStatus::Approved => {
if auto_capture {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => {
enums::AttemptStatus::Failure
}
AuthorizedotnetPaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending,
AuthorizedotnetPaymentStatus::HeldForReview => enums::AttemptStatus::Pending,
}
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
pub struct ResponseMessage {
code: String,
pub text: String,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize, strum::Display)]
enum ResultCode {
#[default]
Ok,
Error,
}
#[derive(Debug, Default, Clone, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResponseMessages {
result_code: ResultCode,
pub message: Vec<ResponseMessage>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorMessage {
pub error_code: String,
pub error_text: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TransactionResponse {
AuthorizedotnetTransactionResponse(Box<AuthorizedotnetTransactionResponse>),
AuthorizedotnetTransactionResponseError(Box<AuthorizedotnetTransactionResponseError>),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct AuthorizedotnetTransactionResponseError {
_supplemental_data_qualification_indicator: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetTransactionResponse {
response_code: AuthorizedotnetPaymentStatus,
#[serde(rename = "transId")]
transaction_id: String,
network_trans_id: Option<Secret<String>>,
pub(super) account_number: Option<Secret<String>>,
pub(super) errors: Option<Vec<ErrorMessage>>,
secure_acceptance: Option<SecureAcceptance>,
avs_result_code: Option<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
response_code: AuthorizedotnetRefundStatus,
#[serde(rename = "transId")]
transaction_id: String,
#[allow(dead_code)]
network_trans_id: Option<Secret<String>>,
pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct SecureAcceptance {
secure_acceptance_url: Option<url::Url>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsResponse {
pub transaction_response: Option<TransactionResponse>,
pub profile_response: Option<AuthorizedotnetNonZeroMandateResponse>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetNonZeroMandateResponse {
customer_profile_id: Option<String>,
customer_payment_profile_id_list: Option<Vec<String>>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetVoidResponse {
pub transaction_response: Option<VoidResponse>,
pub messages: ResponseMessages,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoidResponse {
response_code: AuthorizedotnetVoidStatus,
#[serde(rename = "transId")]
transaction_id: String,
network_trans_id: Option<Secret<String>>,
pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum AuthorizedotnetVoidStatus {
#[serde(rename = "1")]
Approved,
#[serde(rename = "2")]
Declined,
#[serde(rename = "3")]
Error,
#[serde(rename = "4")]
HeldForReview,
}
impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus {
fn from(item: AuthorizedotnetVoidStatus) -> Self {
match item {
AuthorizedotnetVoidStatus::Approved => Self::Voided,
AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => {
Self::VoidFailed
}
AuthorizedotnetVoidStatus::HeldForReview => Self::VoidInitiated,
}
}
}
fn get_avs_response_description(code: &str) -> Option<&'static str> {
match code {
"A" => Some("The street address matched, but the postal code did not."),
"B" => Some("No address information was provided."),
"E" => Some(
"AVS data provided is invalid or AVS is not allowed for the card type that was used.",
),
"G" => Some("The card was issued by a bank outside the U.S. and does not support AVS."),
"N" => Some("Neither the street address nor postal code matched."),
"P" => Some("AVS is not applicable for this transaction."),
"R" => Some("Retry — AVS was unavailable or timed out."),
"S" => Some("AVS is not supported by card issuer."),
"U" => Some("Address information is unavailable."),
"W" => Some("The US ZIP+4 code matches, but the street address does not."),
"X" => Some("Both the street address and the US ZIP+4 code matched."),
"Y" => Some("The street address and postal code matched."),
"Z" => Some("The postal code matched, but the street address did not."),
_ => None,
}
}
fn convert_to_additional_payment_method_connector_response(
transaction_response: &AuthorizedotnetTransactionResponse,
) -> Option<AdditionalPaymentMethodConnectorResponse> {
match transaction_response.avs_result_code.as_deref() {
Some("P") | None => None,
Some(code) => {
let description = get_avs_response_description(code);
let payment_checks = serde_json::json!({
"avs_result_code": code,
"description": description
});
Some(AdditionalPaymentMethodConnectorResponse::Card {
authentication_data: None,
payment_checks: Some(payment_checks),
card_network: None,
domestic_network: None,
})
}
}
}
impl<F, T>
ForeignTryFrom<(
ResponseRouterData<F, AuthorizedotnetPaymentsResponse, T, PaymentsResponseData>,
bool,
)> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, is_auto_capture): (
ResponseRouterData<F, AuthorizedotnetPaymentsResponse, T, PaymentsResponseData>,
bool,
),
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => {
let status = get_payment_status((
transaction_response.response_code.clone(),
is_auto_capture,
));
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
});
let metadata = transaction_response
.account_number
.as_ref()
.map(|acc_no| {
construct_refund_payment_details(PaymentDetailAccountNumber::Masked(
acc_no.clone().expose(),
))
.encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_metadata",
})?;
let connector_response_data =
convert_to_additional_payment_method_connector_response(transaction_response)
.map(ConnectorResponseData::with_additional_payment_method_data);
let url = transaction_response
.secure_acceptance
.as_ref()
.and_then(|x| x.secure_acceptance_url.to_owned());
let redirection_data = url.map(|url| RedirectForm::from((url, Method::Get)));
let mandate_reference = item.response.profile_response.map(|profile_response| {
let payment_profile_id = profile_response
.customer_payment_profile_id_list
.and_then(|customer_payment_profile_id_list| {
customer_payment_profile_id_list.first().cloned()
});
MandateReference {
connector_mandate_id: profile_response.customer_profile_id.and_then(
|customer_profile_id| {
payment_profile_id.map(|payment_profile_id| {
format!("{customer_profile_id}-{payment_profile_id}")
})
},
),
payment_method_id: None,
mandate_metadata: None,
connector_mandate_request_reference_id: None,
}
});
Ok(Self {
status,
response: match error {
Some(err) => Err(err),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
.clone()
.map(|network_trans_id| network_trans_id.expose()),
connector_response_reference_id: Some(
transaction_response.transaction_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
},
connector_response: connector_response_data,
..item.data
})
}
Some(TransactionResponse::AuthorizedotnetTransactionResponseError(_)) | None => {
Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
})
}
}
}
}
impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetVoidResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(transaction_response) => {
let status = enums::AttemptStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
});
let metadata = transaction_response
.account_number
.as_ref()
.map(|acc_no| {
construct_refund_payment_details(PaymentDetailAccountNumber::Masked(
acc_no.clone().expose(),
))
.encode_to_value()
})
.transpose()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_metadata",
})?;
Ok(Self {
status,
response: match error {
Some(err) => Err(err),
None => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: metadata,
network_txn_id: transaction_response
.network_trans_id
.clone()
.map(|network_trans_id| network_trans_id.expose()),
connector_response_reference_id: Some(
transaction_response.transaction_id.clone(),
),
incremental_authorization_allowed: None,
charges: None,
}),
},
..item.data
})
}
None => Ok(Self {
status: enums::AttemptStatus::Failure,
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct RefundTransactionRequest {
transaction_type: TransactionType,
amount: FloatMajorUnit,
currency_code: String,
payment: PaymentDetails,
#[serde(rename = "refTransId")]
reference_transaction_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetRefundRequest {
merchant_authentication: AuthorizedotnetAuthType,
transaction_request: RefundTransactionRequest,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
// The connector enforces field ordering, it expects fields to be in the same order as in their API documentation
pub struct CreateRefundRequest {
create_transaction_request: AuthorizedotnetRefundRequest,
}
impl<F> TryFrom<&AuthorizedotnetRouterData<&RefundsRouterData<F>>> for CreateRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let transaction_request = RefundTransactionRequest {
transaction_type: TransactionType::Refund,
amount: item.amount,
payment: get_refund_metadata(
&item.router_data.request.connector_metadata,
&item.router_data.request.additional_payment_method_data,
)?,
currency_code: item.router_data.request.currency.to_string(),
reference_transaction_id: item.router_data.request.connector_transaction_id.clone(),
};
Ok(Self {
create_transaction_request: AuthorizedotnetRefundRequest {
merchant_authentication,
transaction_request,
},
})
}
}
fn get_refund_metadata(
connector_metadata: &Option<Value>,
additional_payment_method: &Option<AdditionalPaymentData>,
) -> Result<PaymentDetails, error_stack::Report<errors::ConnectorError>> {
let payment_details_from_metadata = connector_metadata
.as_ref()
.get_required_value("connector_metadata")
.ok()
.and_then(|value| {
value
.clone()
.parse_value::<PaymentDetails>("PaymentDetails")
.ok()
});
let payment_details_from_additional_payment_method = match additional_payment_method {
Some(AdditionalPaymentData::Card(additional_card_info)) => {
additional_card_info.last4.clone().map(|last4| {
construct_refund_payment_details(PaymentDetailAccountNumber::UnMasked(
last4.to_string(),
))
})
}
_ => None,
};
match (
payment_details_from_metadata,
payment_details_from_additional_payment_method,
) {
(Some(payment_detail), _) => Ok(payment_detail),
(_, Some(payment_detail)) => Ok(payment_detail),
(None, None) => Err(errors::ConnectorError::MissingRequiredField {
field_name: "payment_details",
}
.into()),
}
}
impl From<AuthorizedotnetRefundStatus> for enums::RefundStatus {
fn from(item: AuthorizedotnetRefundStatus) -> Self {
match item {
AuthorizedotnetRefundStatus::Declined | AuthorizedotnetRefundStatus::Error => {
Self::Failure
}
AuthorizedotnetRefundStatus::Approved | AuthorizedotnetRefundStatus::HeldForReview => {
Self::Pending
}
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetRefundResponse {
pub transaction_response: RefundResponse,
pub messages: ResponseMessages,
}
impl<F> TryFrom<RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>>
for RefundsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>,
) -> Result<Self, Self::Error> {
let transaction_response = &item.response.transaction_response;
let refund_status = enums::RefundStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.clone().and_then(|errors| {
errors.first().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
status_code: item.http_code,
attempt_status: None,
connector_transaction_id: Some(transaction_response.transaction_id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
});
Ok(Self {
response: match error {
Some(err) => Err(err),
None => Ok(RefundsResponseData {
connector_refund_id: transaction_response.transaction_id.clone(),
refund_status,
}),
},
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionDetails {
merchant_authentication: AuthorizedotnetAuthType,
#[serde(rename = "transId")]
transaction_id: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetCreateSyncRequest {
get_transaction_details_request: TransactionDetails,
}
impl<F> TryFrom<&AuthorizedotnetRouterData<&RefundsRouterData<F>>>
for AuthorizedotnetCreateSyncRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &AuthorizedotnetRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let transaction_id = item.router_data.request.get_connector_refund_id()?;
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
let payload = Self {
get_transaction_details_request: TransactionDetails {
merchant_authentication,
transaction_id: Some(transaction_id),
},
};
Ok(payload)
}
}
impl TryFrom<&PaymentsSyncRouterData> for AuthorizedotnetCreateSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction_id = Some(
item.request
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
);
let merchant_authentication = AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let payload = Self {
get_transaction_details_request: TransactionDetails {
merchant_authentication,
transaction_id,
},
};
Ok(payload)
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum SyncStatus {
RefundSettledSuccessfully,
RefundPendingSettlement,
AuthorizedPendingCapture,
CapturedPendingSettlement,
SettledSuccessfully,
Declined,
Voided,
CouldNotVoid,
GeneralError,
#[serde(rename = "FDSPendingReview")]
FDSPendingReview,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum RSyncStatus {
RefundSettledSuccessfully,
RefundPendingSettlement,
Declined,
GeneralError,
Voided,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncTransactionResponse {
#[serde(rename = "transId")]
transaction_id: String,
transaction_status: SyncStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct AuthorizedotnetSyncResponse {
transaction: Option<SyncTransactionResponse>,
messages: ResponseMessages,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RSyncTransactionResponse {
#[serde(rename = "transId")]
transaction_id: String,
transaction_status: RSyncStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct AuthorizedotnetRSyncResponse {
transaction: Option<RSyncTransactionResponse>,
messages: ResponseMessages,
}
impl From<SyncStatus> for enums::AttemptStatus {
fn from(transaction_status: SyncStatus) -> Self {
match transaction_status {
SyncStatus::SettledSuccessfully | SyncStatus::CapturedPendingSettlement => {
Self::Charged
}
SyncStatus::AuthorizedPendingCapture => Self::Authorized,
SyncStatus::Declined => Self::AuthenticationFailed,
SyncStatus::Voided => Self::Voided,
SyncStatus::CouldNotVoid => Self::VoidFailed,
SyncStatus::GeneralError => Self::Failure,
SyncStatus::RefundSettledSuccessfully
| SyncStatus::RefundPendingSettlement
| SyncStatus::FDSPendingReview => Self::Pending,
}
}
}
impl From<RSyncStatus> for enums::RefundStatus {
fn from(transaction_status: RSyncStatus) -> Self {
match transaction_status {
RSyncStatus::RefundSettledSuccessfully => Self::Success,
RSyncStatus::RefundPendingSettlement => Self::Pending,
RSyncStatus::Declined | RSyncStatus::GeneralError | RSyncStatus::Voided => {
Self::Failure
}
}
}
}
impl TryFrom<RefundsResponseRouterData<RSync, AuthorizedotnetRSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, AuthorizedotnetRSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
let refund_status = enums::RefundStatus::from(transaction.transaction_status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: transaction.transaction_id,
refund_status,
}),
..item.data
})
}
None => Ok(Self {
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
}
}
}
impl<F, Req> TryFrom<ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, PaymentsResponseData>>
for RouterData<F, Req, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
let payment_status = enums::AttemptStatus::from(transaction.transaction_status);
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
transaction.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(transaction.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
status: payment_status,
..item.data
})
}
// E00053 indicates "server too busy"
// If the server is too busy, we return the already available data
None => match item
.response
.messages
.message
.iter()
.find(|msg| msg.code == "E00053")
{
Some(_) => Ok(item.data),
None => Ok(Self {
response: Err(get_err_response(item.http_code, item.response.messages)?),
..item.data
}),
},
}
}
}
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct ErrorDetails {
pub code: Option<String>,
#[serde(rename = "type")]
pub error_type: Option<String>,
pub message: Option<String>,
pub param: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct AuthorizedotnetErrorResponse {
pub error: ErrorDetails,
}
enum PaymentDetailAccountNumber {
Masked(String),
UnMasked(String),
}
fn construct_refund_payment_details(detail: PaymentDetailAccountNumber) -> PaymentDetails {
PaymentDetails::CreditCard(CreditCardDetails {
card_number: match detail {
PaymentDetailAccountNumber::Masked(masked) => masked.into(),
PaymentDetailAccountNumber::UnMasked(unmasked) => format!("XXXX{:}", unmasked).into(),
},
expiration_date: "XXXX".to_string().into(),
card_code: None,
})
}
impl TryFrom<Option<enums::CaptureMethod>> for TransactionType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(capture_method: Option<enums::CaptureMethod>) -> Result<Self, Self::Error> {
match capture_method {
Some(enums::CaptureMethod::Manual) => Ok(Self::Authorization),
Some(enums::CaptureMethod::SequentialAutomatic)
| Some(enums::CaptureMethod::Automatic)
| None => Ok(Self::Payment),
Some(enums::CaptureMethod::ManualMultiple) => {
Err(utils::construct_not_supported_error_report(
enums::CaptureMethod::ManualMultiple,
"authorizedotnet",
))?
}
Some(enums::CaptureMethod::Scheduled) => {
Err(utils::construct_not_supported_error_report(
enums::CaptureMethod::Scheduled,
"authorizedotnet",
))?
}
}
}
}
fn get_err_response(
status_code: u16,
message: ResponseMessages,
) -> Result<ErrorResponse, errors::ConnectorError> {
let response_message = message
.message
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(ErrorResponse {
code: response_message.code.clone(),
message: response_message.text.clone(),
reason: Some(response_message.text.clone()),
status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetWebhookObjectId {
pub webhook_id: String,
pub event_type: AuthorizedotnetWebhookEvent,
pub payload: AuthorizedotnetWebhookPayload,
}
#[derive(Debug, Deserialize)]
pub struct AuthorizedotnetWebhookPayload {
pub id: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetWebhookEventType {
pub event_type: AuthorizedotnetIncomingWebhookEventType,
}
#[derive(Debug, Deserialize)]
pub enum AuthorizedotnetWebhookEvent {
#[serde(rename = "net.authorize.payment.authorization.created")]
AuthorizationCreated,
#[serde(rename = "net.authorize.payment.priorAuthCapture.created")]
PriorAuthCapture,
#[serde(rename = "net.authorize.payment.authcapture.created")]
AuthCapCreated,
#[serde(rename = "net.authorize.payment.capture.created")]
CaptureCreated,
#[serde(rename = "net.authorize.payment.void.created")]
VoidCreated,
#[serde(rename = "net.authorize.payment.refund.created")]
RefundCreated,
}
///Including Unknown to map unknown webhook events
#[derive(Debug, Deserialize)]
pub enum AuthorizedotnetIncomingWebhookEventType {
#[serde(rename = "net.authorize.payment.authorization.created")]
AuthorizationCreated,
#[serde(rename = "net.authorize.payment.priorAuthCapture.created")]
PriorAuthCapture,
#[serde(rename = "net.authorize.payment.authcapture.created")]
AuthCapCreated,
#[serde(rename = "net.authorize.payment.capture.created")]
CaptureCreated,
#[serde(rename = "net.authorize.payment.void.created")]
VoidCreated,
#[serde(rename = "net.authorize.payment.refund.created")]
RefundCreated,
#[serde(other)]
Unknown,
}
impl From<AuthorizedotnetIncomingWebhookEventType> for IncomingWebhookEvent {
fn from(event_type: AuthorizedotnetIncomingWebhookEventType) -> Self {
match event_type {
AuthorizedotnetIncomingWebhookEventType::AuthorizationCreated
| AuthorizedotnetIncomingWebhookEventType::PriorAuthCapture
| AuthorizedotnetIncomingWebhookEventType::AuthCapCreated
| AuthorizedotnetIncomingWebhookEventType::CaptureCreated
| AuthorizedotnetIncomingWebhookEventType::VoidCreated => Self::PaymentIntentSuccess,
AuthorizedotnetIncomingWebhookEventType::RefundCreated => Self::RefundSuccess,
AuthorizedotnetIncomingWebhookEventType::Unknown => Self::EventNotSupported,
}
}
}
impl From<AuthorizedotnetWebhookEvent> for SyncStatus {
// status mapping reference https://developer.authorize.net/api/reference/features/webhooks.html#Event_Types_and_Payloads
fn from(event_type: AuthorizedotnetWebhookEvent) -> Self {
match event_type {
AuthorizedotnetWebhookEvent::AuthorizationCreated => Self::AuthorizedPendingCapture,
AuthorizedotnetWebhookEvent::CaptureCreated
| AuthorizedotnetWebhookEvent::AuthCapCreated => Self::CapturedPendingSettlement,
AuthorizedotnetWebhookEvent::PriorAuthCapture => Self::SettledSuccessfully,
AuthorizedotnetWebhookEvent::VoidCreated => Self::Voided,
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,176
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/stripe.rs
// Module: hyperswitch_connectors
// Public structs: 1
pub mod transformers;
use std::{collections::HashMap, sync::LazyLock};
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::{
CallConnectorAction, CaptureMethod, PaymentAction, PaymentChargeType, PaymentMethodType,
PaymentResourceUpdateStatus, StripeChargeType,
};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt as _, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, MinorUnit, MinorUnitForConnector, StringMinorUnit,
StringMinorUnitForConnector,
},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
AccessTokenAuth, Authorize, Capture, CreateConnectorCustomer, Evidence, Execute,
IncrementalAuthorization, PSync, PaymentMethodToken, RSync, Retrieve, Session,
SetupMandate, UpdateMetadata, Upload, Void,
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsSessionData, PaymentsSyncData,
PaymentsUpdateMetadataData, RefundsData, RetrieveFileRequestData, SetupMandateRequestData,
SplitRefundsRequest, SubmitEvidenceRequestData, UploadFileRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
RetrieveFileResponse, SubmitEvidenceResponse, SupportedPaymentMethods,
SupportedPaymentMethodsExt, UploadFileResponse,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsIncrementalAuthorizationRouterData,
PaymentsSyncRouterData, PaymentsUpdateMetadataRouterData, RefundsRouterData,
TokenizationRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::{PoCancel, PoCreate, PoFulfill, PoRecipient, PoRecipientAccount},
types::{PayoutsData, PayoutsResponseData, PayoutsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{
PayoutCancelType, PayoutCreateType, PayoutFulfillType, PayoutRecipientAccountType,
PayoutRecipientType,
};
use hyperswitch_interfaces::{
api::{
self,
disputes::SubmitEvidence,
files::{FilePurpose, FileUpload, RetrieveFile, UploadFile},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation, PaymentIncrementalAuthorization,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
disputes::DisputePayload,
errors::ConnectorError,
events::connector_api_logs::ConnectorEvent,
types::{
ConnectorCustomerType, IncrementalAuthorizationType, PaymentsAuthorizeType,
PaymentsCaptureType, PaymentsSyncType, PaymentsUpdateMetadataType, PaymentsVoidType,
RefundExecuteType, RefundSyncType, Response, RetrieveFileType, SubmitEvidenceType,
TokenizationType, UploadFileType,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask as _, Maskable, PeekInterface};
use router_env::{instrument, tracing};
use stripe::auth_headers;
use self::transformers as stripe;
#[cfg(feature = "payouts")]
use crate::utils::{PayoutsData as OtherPayoutsData, RouterData as OtherRouterData};
use crate::{
constants::headers::{AUTHORIZATION, CONTENT_TYPE, STRIPE_COMPATIBLE_CONNECT_ACCOUNT},
types::{
ResponseRouterData, RetrieveFileRouterData, SubmitEvidenceRouterData, UploadFileRouterData,
},
utils::{
self, get_authorise_integrity_object, get_capture_integrity_object,
get_refund_integrity_object, get_sync_integrity_object, PaymentMethodDataType,
RefundsRequestData as OtherRefundsRequestData,
},
};
#[derive(Clone)]
pub struct Stripe {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Stripe {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
amount_converter_webhooks: &StringMinorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Stripe
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![(
CONTENT_TYPE.to_string(),
Self::common_get_content_type(self).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 Stripe {
fn id(&self) -> &'static str {
"stripe"
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
// &self.base_url
connectors.stripe.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let auth = stripe::StripeAuthType::try_from(auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
Ok(vec![
(
AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.peek()).into_masked(),
),
(
auth_headers::STRIPE_API_VERSION.to_string(),
auth_headers::STRIPE_VERSION.to_string().into_masked(),
),
])
}
#[cfg(feature = "payouts")]
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
use hyperswitch_interfaces::consts::NO_ERROR_CODE;
let response: stripe::StripeConnectErrorResponse = res
.response
.parse_struct("StripeConnectErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.error.message,
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: response.error.network_advice_code,
network_decline_code: response.error.network_decline_code,
network_error_message: response.error.decline_code.or(response.error.advice_code),
connector_metadata: None,
})
}
}
impl ConnectorValidation for Stripe {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<CaptureMethod>,
_payment_method: common_enums::PaymentMethod,
_pmt: Option<PaymentMethodType>,
) -> CustomResult<(), ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
CaptureMethod::SequentialAutomatic
| CaptureMethod::Automatic
| CaptureMethod::Manual => Ok(()),
CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => Err(
utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
PaymentMethodDataType::AchBankDebit,
PaymentMethodDataType::BacsBankDebit,
PaymentMethodDataType::BecsBankDebit,
PaymentMethodDataType::SepaBankDebit,
PaymentMethodDataType::Sofort,
PaymentMethodDataType::Ideal,
PaymentMethodDataType::BancontactCard,
]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl api::Payment for Stripe {}
impl api::PaymentAuthorize for Stripe {}
impl api::PaymentUpdateMetadata for Stripe {}
impl api::PaymentSync for Stripe {}
impl api::PaymentVoid for Stripe {}
impl api::PaymentCapture for Stripe {}
impl api::PaymentSession for Stripe {}
impl api::ConnectorAccessToken for Stripe {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Stripe {
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Stripe {
// Not Implemented (R)
}
impl api::ConnectorCustomer for Stripe {}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Stripe
{
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut header = vec![(
CONTENT_TYPE.to_string(),
ConnectorCustomerType::get_content_type(self)
.to_string()
.into(),
)];
if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) = &req.request.split_payments
{
if stripe_split_payment.charge_type
== PaymentChargeType::Stripe(StripeChargeType::Direct)
{
let mut customer_account_header = vec![(
STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
stripe_split_payment
.transfer_account_id
.clone()
.into_masked(),
)];
header.append(&mut customer_account_header);
}
}
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "v1/customers"))
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let connector_req = stripe::CustomerRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&ConnectorCustomerType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(ConnectorCustomerType::get_headers(self, req, connectors)?)
.set_body(ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorCustomerRouterData, ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: stripe::StripeCustomerResponse = res
.response
.parse_struct("StripeCustomerResponse")
.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,
})
.change_context(ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.clone()
.map(|decline_code| {
format!("message - {message}, decline_code - {decline_code}")
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: response.error.network_advice_code,
network_decline_code: response.error.network_decline_code,
network_error_message: response.error.decline_code.or(response.error.advice_code),
connector_metadata: None,
})
}
}
impl api::PaymentToken for Stripe {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Stripe
{
fn get_headers(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut header = vec![(
CONTENT_TYPE.to_string(),
TokenizationType::get_content_type(self).to_string().into(),
)];
if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) = &req.request.split_payments
{
if stripe_split_payment.charge_type
== PaymentChargeType::Stripe(StripeChargeType::Direct)
{
let mut customer_account_header = vec![(
STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
stripe_split_payment
.transfer_account_id
.clone()
.into_masked(),
)];
header.append(&mut customer_account_header);
}
}
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
if matches!(
req.request.split_payments,
Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(_))
) {
return Ok(format!(
"{}{}",
self.base_url(connectors),
"v1/payment_methods"
));
}
Ok(format!("{}{}", self.base_url(connectors), "v1/tokens"))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let connector_req = stripe::TokenRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(TokenizationType::get_headers(self, req, connectors)?)
.set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: stripe::StripeTokenResponse = res
.response
.parse_struct("StripeTokenResponse")
.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,
})
.change_context(ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.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
.error
.code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.clone()
.map(|decline_code| {
format!("message - {message}, decline_code - {decline_code}")
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: response.error.network_advice_code,
network_decline_code: response.error.network_decline_code,
network_error_message: response.error.decline_code.or(response.error.advice_code),
connector_metadata: None,
})
}
}
impl api::MandateSetup for Stripe {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Stripe {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut header = vec![(
CONTENT_TYPE.to_string(),
Self::common_get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
let id = req.request.connector_transaction_id.as_str();
Ok(format!(
"{}{}/{}/capture",
self.base_url(connectors),
"v1/payment_intents",
id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_req = stripe::CaptureRequest::try_from(amount)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
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>
where
PaymentsCaptureData: Clone,
PaymentsResponseData: Clone,
{
let response: stripe::PaymentIntentResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = get_capture_integrity_object(
self.amount_converter,
response.amount_received,
response.currency.clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.clone()
.map(|decline_code| {
format!("message - {message}, decline_code - {decline_code}")
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: response.error.network_advice_code,
network_decline_code: response.error.network_decline_code,
network_error_message: response.error.decline_code.or(response.error.advice_code),
connector_metadata: None,
})
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Stripe {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut header = vec![(
CONTENT_TYPE.to_string(),
PaymentsSyncType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) = &req.request.split_payments
{
transformers::transform_headers_for_connect_platform(
stripe_split_payment.charge_type.clone(),
stripe_split_payment.transfer_account_id.clone(),
&mut header,
);
}
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
let id = req.request.connector_transaction_id.clone();
match id.get_connector_transaction_id() {
Ok(x) if x.starts_with("set") => Ok(format!(
"{}{}/{}?expand[0]=latest_attempt", // expand latest attempt to extract payment checks and three_d_secure data
self.base_url(connectors),
"v1/setup_intents",
x,
)),
Ok(x) => Ok(format!(
"{}{}/{}{}",
self.base_url(connectors),
"v1/payment_intents",
x,
"?expand[0]=latest_charge" //updated payment_id(if present) reside inside latest_charge field
)),
x => x.change_context(ConnectorError::MissingConnectorTransactionID),
}
}
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>
where
PaymentsResponseData: Clone,
{
let id = data.request.connector_transaction_id.clone();
match id.get_connector_transaction_id() {
Ok(x) if x.starts_with("set") => {
let response: stripe::SetupIntentResponse = res
.response
.parse_struct("SetupIntentSyncResponse")
.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,
})
}
Ok(_) => {
let response: stripe::PaymentIntentSyncResponse = res
.response
.parse_struct("PaymentIntentSyncResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = get_sync_integrity_object(
self.amount_converter,
response.amount,
response.currency.clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
});
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
Err(err) => Err(err).change_context(ConnectorError::MissingConnectorTransactionID),
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.clone()
.map(|decline_code| {
format!("message - {message}, decline_code - {decline_code}")
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: response.error.network_advice_code,
network_decline_code: response.error.network_decline_code,
network_error_message: response.error.decline_code.or(response.error.advice_code),
connector_metadata: None,
})
}
}
#[async_trait::async_trait]
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Stripe {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut header = vec![(
CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
let stripe_split_payment_metadata = stripe::StripeSplitPaymentRequest::try_from(req)?;
// if the request has split payment object, then append the transfer account id in headers in charge_type is Direct
if let Some(common_types::payments::SplitPaymentsRequest::StripeSplitPayment(
stripe_split_payment,
)) = &req.request.split_payments
{
if stripe_split_payment.charge_type
== PaymentChargeType::Stripe(StripeChargeType::Direct)
{
let mut customer_account_header = vec![(
STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
stripe_split_payment
.transfer_account_id
.clone()
.into_masked(),
)];
header.append(&mut customer_account_header);
}
}
// if request doesn't have transfer_account_id, but stripe_split_payment_metadata has it, append it
else if let Some(transfer_account_id) =
stripe_split_payment_metadata.transfer_account_id.clone()
{
let mut customer_account_header = vec![(
STRIPE_COMPATIBLE_CONNECT_ACCOUNT.to_string(),
transfer_account_id.into_masked(),
)];
header.append(&mut customer_account_header);
}
Ok(header)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v1/payment_intents"
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_req = stripe::PaymentIntentRequest::try_from((req, amount))?;
Ok(RequestContent::FormUrlEncoded(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: stripe::PaymentIntentResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = get_authorise_integrity_object(
self.amount_converter,
response.amount,
response.currency.clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: stripe::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response
.error
.code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: response
.error
.code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: response.error.message.map(|message| {
response
.error
.decline_code
.clone()
.map(|decline_code| {
format!("message - {message}, decline_code - {decline_code}")
})
.unwrap_or(message)
}),
attempt_status: None,
connector_transaction_id: response.error.payment_intent.map(|pi| pi.id),
network_advice_code: response.error.network_advice_code,
network_decline_code: response.error.network_decline_code,
network_error_message: response.error.decline_code.or(response.error.advice_code),
connector_metadata: None,
})
}
}
impl PaymentIncrementalAuthorization for Stripe {}
impl
ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
> for Stripe
{
fn get_headers(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Post
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}v1/payment_intents/{}/increment_authorization",
self.base_url(connectors),
req.request.connector_transaction_id,
))
}
fn get_request_body(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
MinorUnit::new(req.request.total_amount),
req.request.currency,
)?;
let connector_req = stripe::StripeIncrementalAuthRequest { amount }; // Incremental authorization can be done a maximum of 10 times in Stripe
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&IncrementalAuthorizationType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(IncrementalAuthorizationType::get_headers(
self, req, connectors,
)?)
.set_body(IncrementalAuthorizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsIncrementalAuthorizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>,
ConnectorError,
> {
let response: stripe::PaymentIntentResponse = res
|
crates/hyperswitch_connectors/src/connectors/stripe.rs#chunk0
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,189
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorRedirectResponse for for Breadpay
// File: crates/hyperswitch_connectors/src/connectors/breadpay.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl ConnectorRedirectResponse for for Breadpay
|
crates/hyperswitch_connectors/src/connectors/breadpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 56
| null |
Breadpay
|
ConnectorRedirectResponse for
| 1
| 0
| null | null |
// Struct: EphemeralKeyCreateRequest
// File: crates/api_models/src/ephemeral_key.rs
// Module: api_models
// Implementations: 1
// Traits: common_utils::events::ApiEventMetric
pub struct EphemeralKeyCreateRequest
|
crates/api_models/src/ephemeral_key.rs
|
api_models
|
struct_definition
|
EphemeralKeyCreateRequest
| 1
|
[
"common_utils::events::ApiEventMetric"
] | 57
| null | null | null | null | null | null | null |
// File: crates/router/src/core/verify_connector.rs
// Module: router
// Public functions: 1
use api_models::{enums::Connector, verify_connector::VerifyConnectorRequest};
use error_stack::ResultExt;
use crate::{
connector,
core::errors,
services,
types::{
api::{
self,
verify_connector::{self as types, VerifyConnector},
},
transformers::ForeignInto,
},
utils::verify_connector as utils,
SessionState,
};
pub async fn verify_connector_credentials(
state: SessionState,
req: VerifyConnectorRequest,
_profile_id: Option<common_utils::id_type::ProfileId>,
) -> errors::RouterResponse<()> {
let boxed_connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&req.connector_name.to_string(),
api::GetToken::Connector,
None,
)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)?;
let card_details = utils::get_test_card_details(req.connector_name)?.ok_or(
errors::ApiErrorResponse::FlowNotSupported {
flow: "Verify credentials".to_string(),
connector: req.connector_name.to_string(),
},
)?;
match req.connector_name {
Connector::Stripe => {
connector::Stripe::verify(
&state,
types::VerifyConnectorData {
connector: boxed_connector.connector,
connector_auth: req.connector_account_details.foreign_into(),
card_details,
},
)
.await
}
Connector::Paypal => connector::Paypal::get_access_token(
&state,
types::VerifyConnectorData {
connector: boxed_connector.connector,
connector_auth: req.connector_account_details.foreign_into(),
card_details,
},
)
.await
.map(|_| services::ApplicationResponse::StatusOk),
_ => Err(errors::ApiErrorResponse::FlowNotSupported {
flow: "Verify credentials".to_string(),
connector: req.connector_name.to_string(),
}
.into()),
}
}
|
crates/router/src/core/verify_connector.rs
|
router
|
full_file
| null | null | null | 430
| null | null | null | null | null | null | null |
// Struct: TrustpaymentsPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct TrustpaymentsPaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
TrustpaymentsPaymentsResponse
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: collect
// File: crates/analytics/src/frm/accumulator.rs
// Module: analytics
pub fn collect(self) -> FrmMetricsBucketValue
|
crates/analytics/src/frm/accumulator.rs
|
analytics
|
function_signature
| null | null | null | 33
|
collect
| null | null | null | null | null | null |
// Function: payments_reject
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn payments_reject(
state: web::Data<app::AppState>,
http_req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsRejectRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 86
|
payments_reject
| null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.