text string | file_path string | module string | type string | tokens int64 | language string | struct_name string | type_name string | trait_name string | impl_type string | function_name string | source string | section string | keys list | macro_type string | url string | title string | chunk_index int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pub async fn check_user_in_blacklist<A: SessionStateInfo>(
state: &A,
user_id: &str,
token_expiry: u64,
) -> RouterResult<bool> {
let token = format!("{USER_BLACKLIST_PREFIX}{user_id}");
let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
let redis_conn = get_redis_connection_for_global_tenant(state)?;
redis_conn
.get_key::<Option<i64>>(&token.as_str().into())
.await
.change_context(ApiErrorResponse::InternalServerError)
.map(|timestamp| timestamp > Some(token_issued_at))
} | crates/router/src/services/authentication/blacklist.rs | router | function_signature | 141 | rust | null | null | null | null | check_user_in_blacklist | null | null | null | null | null | null | null |
File: crates/pm_auth/src/connector/plaid.rs
Public structs: 1
pub mod transformers;
use std::fmt::Debug;
use common_utils::{
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use masking::{Mask, Maskable};
use transformers as plaid;
use crate::{
core::errors,
types::{
self as auth_types,
api::{
auth_service::{
self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate,
},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
},
},
};
#[derive(Debug, Clone)]
pub struct Plaid;
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
"Content-Type".to_string(),
self.get_content_type().to_string().into(),
)];
let mut auth = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut auth);
Ok(header)
}
}
impl ConnectorCommon for Plaid {
fn id(&self) -> &'static str {
"plaid"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str {
"https://sandbox.plaid.com"
}
fn get_auth_header(
&self,
auth_type: &auth_types::ConnectorAuthType,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = plaid::PlaidAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let client_id = auth.client_id.into_masked();
let secret = auth.secret.into_masked();
Ok(vec![
("PLAID-CLIENT-ID".to_string(), client_id),
("PLAID-SECRET".to_string(), secret),
])
}
fn build_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
let response: plaid::PlaidErrorResponse =
res.response
.parse_struct("PlaidErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(auth_types::ErrorResponse {
status_code: res.status_code,
code: crate::consts::NO_ERROR_CODE.to_string(),
message: response.error_message,
reason: response.display_message,
})
}
}
impl auth_service::AuthService for Plaid {}
impl auth_service::PaymentInitiationRecipientCreate for Plaid {}
impl auth_service::PaymentInitiation for Plaid {}
impl auth_service::AuthServiceLinkToken for Plaid {}
impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse>
for Plaid
{
fn get_headers(
&self,
req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, 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: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/link/token/create"
))
}
fn get_request_body(
&self,
req: &auth_types::LinkTokenRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthLinkTokenType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthLinkTokenType::get_headers(
self, req, connectors,
)?)
.set_body(auth_types::PaymentAuthLinkTokenType::get_request_body(
self, req,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::LinkTokenRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> {
let response: plaid::PlaidLinkTokenResponse = res
.response
.parse_struct("PlaidLinkTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl auth_service::AuthServiceExchangeToken for Plaid {}
impl
ConnectorIntegration<
ExchangeToken,
auth_types::ExchangeTokenRequest,
auth_types::ExchangeTokenResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, 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: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/item/public_token/exchange"
))
}
fn get_request_body(
&self,
req: &auth_types::ExchangeTokenRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthExchangeTokenType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthExchangeTokenType::get_headers(
self, req, connectors,
)?)
.set_body(auth_types::PaymentAuthExchangeTokenType::get_request_body(
self, req,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::ExchangeTokenRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> {
let response: plaid::PlaidExchangeTokenResponse = res
.response
.parse_struct("PlaidExchangeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl auth_service::AuthServiceBankAccountCredentials for Plaid {}
impl
ConnectorIntegration<
BankAccountCredentials,
auth_types::BankAccountCredentialsRequest,
auth_types::BankAccountCredentialsResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, 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: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/auth/get"))
}
fn get_request_body(
&self,
req: &auth_types::BankDetailsRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthBankAccountDetailsType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers(
self, req, connectors,
)?)
.set_body(
auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?,
)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::BankDetailsRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> {
let response: plaid::PlaidBankAccountCredentialsResponse = res
.response
.parse_struct("PlaidBankAccountCredentialsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl
ConnectorIntegration<
RecipientCreate,
auth_types::RecipientCreateRequest,
auth_types::RecipientCreateResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, 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: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/payment_initiation/recipient/create"
))
}
fn get_request_body(
&self,
req: &auth_types::RecipientCreateRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidRecipientCreateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentInitiationRecipientCreateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(
auth_types::PaymentInitiationRecipientCreateType::get_headers(
self, req, connectors,
)?,
)
.set_body(
auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?,
)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::RecipientCreateRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> {
let response: plaid::PlaidRecipientCreateResponse = res
.response
.parse_struct("PlaidRecipientCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(<auth_types::RecipientCreateRouterData>::from(
auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
))
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
| crates/pm_auth/src/connector/plaid.rs | pm_auth | full_file | 3,149 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn generic_find_by_id_optional<T, Pk, R>(
conn: &PgPooledConn,
id: Pk,
) -> StorageResult<Option<R>>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
<T as HasTable>::Table: FindDsl<Pk>,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
to_optional(generic_find_by_id_core::<T, _, _>(conn, id).await)
} | crates/diesel_models/src/query/generics.rs | diesel_models | function_signature | 171 | rust | null | null | null | null | generic_find_by_id_optional | null | null | null | null | null | null | null |
Documentation: api-reference/v1/payment-methods/list-payment-methods-for-a-merchant.mdx
# Type: Doc File
---
openapi: get /account/payment_methods
--- | api-reference/v1/payment-methods/list-payment-methods-for-a-merchant.mdx | null | doc_file | 37 | doc | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn generate_signature(
&self,
auth: wellsfargo::WellsfargoAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let wellsfargo::WellsfargoAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let is_patch_method = matches!(http_method, Method::Patch);
let is_delete_method = matches!(http_method, Method::Delete);
let digest_str = if is_post_method || is_patch_method {
"digest "
} else {
""
};
let headers = format!("host date (request-target) {digest_str}v-c-merchant-id");
let request_target = if is_post_method {
format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n")
} else if is_patch_method {
format!("(request-target): patch {resource}\ndigest: SHA-256={payload}\n")
} else if is_delete_method {
format!("(request-target): delete {resource}\n")
} else {
format!("(request-target): get {resource}\n")
};
let signature_string = format!(
"host: {host}\ndate: {date}\n{request_target}v-c-merchant-id: {}",
merchant_account.peek()
);
let key_value = consts::BASE64_ENGINE
.decode(api_secret.expose())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "connector_account_details.api_secret",
})?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let signature_value =
consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());
let signature_header = format!(
r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#,
api_key.peek()
);
Ok(signature_header)
} | crates/hyperswitch_connectors/src/connectors/wellsfargo.rs | hyperswitch_connectors | function_signature | 480 | rust | null | null | null | null | generate_signature | null | null | null | null | null | null | null |
impl api::ConnectorAccessToken for UnifiedAuthenticationService {} | crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs | hyperswitch_connectors | impl_block | 10 | rust | null | UnifiedAuthenticationService | api::ConnectorAccessToken for | impl api::ConnectorAccessToken for for UnifiedAuthenticationService | null | null | null | null | null | null | null | null |
pub struct Bitpay {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
} | crates/hyperswitch_connectors/src/connectors/bitpay.rs | hyperswitch_connectors | struct_definition | 27 | rust | Bitpay | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentToken for Gpayments {} | crates/hyperswitch_connectors/src/connectors/gpayments.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Gpayments | api::PaymentToken for | impl api::PaymentToken for for Gpayments | null | null | null | null | null | null | null | null |
impl api::ConnectorAccessToken for Gocardless {} | crates/hyperswitch_connectors/src/connectors/gocardless.rs | hyperswitch_connectors | impl_block | 10 | rust | null | Gocardless | api::ConnectorAccessToken for | impl api::ConnectorAccessToken for for Gocardless | null | null | null | null | null | null | null | null |
impl DynamicRoutingConfigParamsInterpolator {
pub fn new(
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
authentication_type: Option<common_enums::AuthenticationType>,
currency: Option<common_enums::Currency>,
country: Option<common_enums::CountryAlpha2>,
card_network: Option<String>,
card_bin: Option<String>,
) -> Self {
Self {
payment_method,
payment_method_type,
authentication_type,
currency,
country,
card_network,
card_bin,
}
}
pub fn get_string_val(
&self,
params: &Vec<routing_types::DynamicRoutingConfigParams>,
) -> String {
let mut parts: Vec<String> = Vec::new();
for param in params {
let val = match param {
routing_types::DynamicRoutingConfigParams::PaymentMethod => self
.payment_method
.as_ref()
.map_or(String::new(), |pm| pm.to_string()),
routing_types::DynamicRoutingConfigParams::PaymentMethodType => self
.payment_method_type
.as_ref()
.map_or(String::new(), |pmt| pmt.to_string()),
routing_types::DynamicRoutingConfigParams::AuthenticationType => self
.authentication_type
.as_ref()
.map_or(String::new(), |at| at.to_string()),
routing_types::DynamicRoutingConfigParams::Currency => self
.currency
.as_ref()
.map_or(String::new(), |cur| cur.to_string()),
routing_types::DynamicRoutingConfigParams::Country => self
.country
.as_ref()
.map_or(String::new(), |cn| cn.to_string()),
routing_types::DynamicRoutingConfigParams::CardNetwork => {
self.card_network.clone().unwrap_or_default()
}
routing_types::DynamicRoutingConfigParams::CardBin => {
self.card_bin.clone().unwrap_or_default()
}
};
if !val.is_empty() {
parts.push(val);
}
}
parts.join(":")
}
} | crates/router/src/core/routing/helpers.rs | router | impl_block | 458 | rust | null | DynamicRoutingConfigParamsInterpolator | null | impl DynamicRoutingConfigParamsInterpolator | null | null | null | null | null | null | null | null |
pub fn new() -> Self {
Self {
state: std::marker::PhantomData,
customer: None,
card: None,
card_cvc: None,
network_token: None,
stored_card: None,
stored_token: None,
payment_method_response: None,
card_tokenized: false,
error_code: None,
error_message: None,
}
} | crates/router/src/core/payment_methods/tokenize/payment_method_executor.rs | router | function_signature | 86 | rust | null | null | null | null | new | null | null | null | null | null | null | null |
pub struct RevenueRecoveryRecordBackResponse {
pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
} | crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs | hyperswitch_domain_models | struct_definition | 26 | rust | RevenueRecoveryRecordBackResponse | null | null | null | null | null | null | null | null | null | null | null |
pub fn generate_signature(
&self,
auth: &rapyd::RapydAuthType,
http_method: &str,
url_path: &str,
body: &str,
timestamp: i64,
salt: &str,
) -> CustomResult<String, errors::ConnectorError> {
let rapyd::RapydAuthType {
access_key,
secret_key,
} = auth;
let to_sign = format!(
"{http_method}{url_path}{salt}{timestamp}{}{}{body}",
access_key.peek(),
secret_key.peek()
);
let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.peek().as_bytes());
let tag = hmac::sign(&key, to_sign.as_bytes());
let hmac_sign = hex::encode(tag);
let signature_value = BASE64_ENGINE_URL_SAFE.encode(hmac_sign);
Ok(signature_value)
} | crates/hyperswitch_connectors/src/connectors/rapyd.rs | hyperswitch_connectors | function_signature | 202 | rust | null | null | null | null | generate_signature | null | null | null | null | null | null | null |
pub struct FiservCheckoutResponse {
pub gateway_response: GatewayResponse,
pub payment_receipt: PaymentReceipt,
pub interactions: FiservResponseInteractions,
pub order: Option<FiservResponseOrders>,
} | crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs | hyperswitch_connectors | struct_definition | 47 | rust | FiservCheckoutResponse | null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_profile_outgoing_webhook_events(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Query<
api_models::analytics::outgoing_webhook_event::OutgoingWebhookLogsRequest,
>,
) -> impl Responder {
let flow = AnalyticsFlow::GetOutgoingWebhookEvents;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
utils::check_if_profile_id_is_present_in_payment_intent(
req.payment_id.clone(),
&state,
&auth,
)
.await
.change_context(AnalyticsError::AccessForbiddenError)?;
outgoing_webhook_events_core(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/analytics.rs | router | function_signature | 236 | rust | null | null | null | null | get_profile_outgoing_webhook_events | null | null | null | null | null | null | null |
File: crates/router/src/types/api/fraud_check.rs
Public functions: 1
Public structs: 2
use std::str::FromStr;
use api_models::enums;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::fraud_check::{
Checkout, Fulfillment, RecordReturn, Sale, Transaction,
};
pub use hyperswitch_interfaces::api::fraud_check::{
FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn, FraudCheckSale,
FraudCheckTransaction,
};
pub use super::fraud_check_v2::{
FraudCheckCheckoutV2, FraudCheckFulfillmentV2, FraudCheckRecordReturnV2, FraudCheckSaleV2,
FraudCheckTransactionV2, FraudCheckV2,
};
use super::{ConnectorData, SessionConnectorDatas};
use crate::{connector, core::errors, services::connector_integration_interface::ConnectorEnum};
#[derive(Clone)]
pub struct FraudCheckConnectorData {
pub connector: ConnectorEnum,
pub connector_name: enums::FrmConnectors,
}
pub enum ConnectorCallType {
PreDetermined(ConnectorRoutingData),
Retryable(Vec<ConnectorRoutingData>),
SessionMultiple(SessionConnectorDatas),
}
#[derive(Clone)]
pub struct ConnectorRoutingData {
pub connector_data: ConnectorData,
pub network: Option<common_enums::CardNetwork>,
}
impl FraudCheckConnectorData {
pub fn get_connector_by_name(name: &str) -> CustomResult<Self, errors::ApiErrorResponse> {
let connector_name = enums::FrmConnectors::from_str(name)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| {
format!("unable to parse connector: {:?}", name.to_string())
})?;
let connector = Self::convert_connector(connector_name)?;
Ok(Self {
connector,
connector_name,
})
}
fn convert_connector(
connector_name: enums::FrmConnectors,
) -> CustomResult<ConnectorEnum, errors::ApiErrorResponse> {
match connector_name {
enums::FrmConnectors::Signifyd => {
Ok(ConnectorEnum::Old(Box::new(&connector::Signifyd)))
}
enums::FrmConnectors::Riskified => {
Ok(ConnectorEnum::Old(Box::new(connector::Riskified::new())))
}
}
}
}
| crates/router/src/types/api/fraud_check.rs | router | full_file | 512 | null | null | null | null | null | null | null | null | null | null | null | null | null |
- [jpmorgan] implement refund flow ([#8436](https://github.com/juspay/hyperswitch/pull/8436)) ([`cf92e1a`](https://github.com/juspay/hyperswitch/commit/cf92e1a5e10fe5e1a2f939038bf0a94bcaf01e92))
### Refactors
- **router:** Remove `refunds_v2` feature flag ([#8310](https://github.com/juspay/hyperswitch/pull/8310)) ([`c5c0e67`](https://github.com/juspay/hyperswitch/commit/c5c0e677f2a2d43170a66330c98e0ebc4d771717))
- Move CustomerAcceptance to common_types ([#8299](https://github.com/juspay/hyperswitch/pull/8299)) ([`44d93e5`](https://github.com/juspay/hyperswitch/commit/44d93e572f45c0ff46936c6f352c767f5cd7daf4))
### Miscellaneous Tasks
- **postman:** Update Postman collection files ([`6419ad8`](https://github.com/juspay/hyperswitch/commit/6419ad85fbc08246a207e2601a36e4661bf805ff))
**Full Changelog:** [`2025.06.25.0...2025.06.26.0`](https://github.com/juspay/hyperswitch/compare/2025.06.25.0...2025.06.26.0)
- - -
## 2025.06.25.0
### Features
- **authentication:** Initial commit to modular authentication create ([#8085](https://github.com/juspay/hyperswitch/pull/8085)) ([`2ea5d81`](https://github.com/juspay/hyperswitch/commit/2ea5d81d534840d8ff900b9d768c0c264c4ddf53))
- **connector:** [ARCHIPEL] fix Mastercard scheme string for Applepay payments ([#8450](https://github.com/juspay/hyperswitch/pull/8450)) ([`2a06f77`](https://github.com/juspay/hyperswitch/commit/2a06f776f69cb39e217056a1464bacfaac76d556))
- **router:** Add confirm flag in kafka payment intent events ([#8432](https://github.com/juspay/hyperswitch/pull/8432)) ([`bc767b9`](https://github.com/juspay/hyperswitch/commit/bc767b9131e2637ce90997da9018085d2dadb80b))
### Bug Fixes
- **connector:** Adyen connector creates connector's customer reference on the fly fixed ([#8447](https://github.com/juspay/hyperswitch/pull/8447)) ([`7ad2932`](https://github.com/juspay/hyperswitch/commit/7ad2932660607bf169853ebe45de98cef44ef91a))
- **routing:** Remove frm rule migration support as it is not supported in DE ([#8448](https://github.com/juspay/hyperswitch/pull/8448)) ([`fdacec4`](https://github.com/juspay/hyperswitch/commit/fdacec4b38ea1cbd427d5c15595db8e00ac80b22))
### Refactors
- Make billing details optional during data migration ([#8438](https://github.com/juspay/hyperswitch/pull/8438)) ([`dee5d0c`](https://github.com/juspay/hyperswitch/commit/dee5d0c552b382ba7c2db9cf672cc050c17ee3b9))
**Full Changelog:** [`2025.06.24.0...2025.06.25.0`](https://github.com/juspay/hyperswitch/compare/2025.06.24.0...2025.06.25.0)
- - -
## 2025.06.24.0
### Features
- **analytics:** Add RoutingApproach filter in payment analytics ([#8408](https://github.com/juspay/hyperswitch/pull/8408)) ([`a3cc44c`](https://github.com/juspay/hyperswitch/commit/a3cc44c6e15ce69f39104b2ce205bed632e3971e))
- **router:** Add `apply_three_ds_strategy` in payments confirm flow ([#8357](https://github.com/juspay/hyperswitch/pull/8357)) ([`786fe69`](https://github.com/juspay/hyperswitch/commit/786fe699c2abd1a3eb752121a1915acd2012d94a))
### Bug Fixes
- **connector:** [NEXIXPAY] Add Validation Checks for Request Fields ([#8345](https://github.com/juspay/hyperswitch/pull/8345)) ([`6fd7626`](https://github.com/juspay/hyperswitch/commit/6fd7626c99e006bb7dcac864c30299bb8ef1d742))
- Payments redirects for v2 ([#8405](https://github.com/juspay/hyperswitch/pull/8405)) ([`7338a8d`](https://github.com/juspay/hyperswitch/commit/7338a8db8562bae749e32437fa36d8f036655fcd))
**Full Changelog:** [`2025.06.23.0...2025.06.24.0`](https://github.com/juspay/hyperswitch/compare/2025.06.23.0...2025.06.24.0)
- - -
## 2025.06.23.0
### Features
- **connector:**
- [DUMMY_CONNECTOR] crate restructuring ([#8372](https://github.com/juspay/hyperswitch/pull/8372)) ([`293d93f`](https://github.com/juspay/hyperswitch/commit/293d93f68b16b14e2e6ceafebf7630d6ce6ff485))
- [SANTANDER] Add Template Code ([#8369](https://github.com/juspay/hyperswitch/pull/8369)) ([`c8b35da`](https://github.com/juspay/hyperswitch/commit/c8b35dacb85d6e2c38de476877f1b5ed34ab2edb))
- **routing:** Add profile config to switch between HS routing and DE routing result ([#8350](https://github.com/juspay/hyperswitch/pull/8350)) ([`a721d90`](https://github.com/juspay/hyperswitch/commit/a721d90c6b2655a79646ab3f8fa1b376486fcebc))
### Bug Fixes
- **openapi:**
- Correct schema references and semantics for v1 openApi spec ([#8127](https://github.com/juspay/hyperswitch/pull/8127)) ([`02dee9c`](https://github.com/juspay/hyperswitch/commit/02dee9c5811b83423a5cc7f90b203410b9e5c8a0))
- Fix broken mintlify pages (v2) ([#8382](https://github.com/juspay/hyperswitch/pull/8382)) ([`9319c7a`](https://github.com/juspay/hyperswitch/commit/9319c7a60cadac10fac8544f71b76dcc731620f1))
### Refactors
- **routing:** Add support to accept the `saving_percentage` in decision engine response ([#8388](https://github.com/juspay/hyperswitch/pull/8388)) ([`639b92c`](https://github.com/juspay/hyperswitch/commit/639b92c133209886593c0f93cc8a23488b2765ff))
### Documentation
- **connector:** [STRIPE] Added CIT & MIT Examples for API Reference in Stripe Split Payments ([#8311](https://github.com/juspay/hyperswitch/pull/8311)) ([`0851c6e`](https://github.com/juspay/hyperswitch/commit/0851c6ece574ce961830c14d91e6e2040cb3b286))
### Miscellaneous Tasks
- Resolve warnings in v2 ([#8373](https://github.com/juspay/hyperswitch/pull/8373)) ([`d2d4f3d`](https://github.com/juspay/hyperswitch/commit/d2d4f3d1d8e68b652e43532ddb16585ca7c8222b))
**Full Changelog:** [`2025.06.20.1...2025.06.23.0`](https://github.com/juspay/hyperswitch/compare/2025.06.20.1...2025.06.23.0)
- - -
## 2025.06.20.1
### Features
- **revenue_recovery:** Invoke attempt list instead of payment get in recovery webhooks flow ([#8393](https://github.com/juspay/hyperswitch/pull/8393)) ([`fc72c3e`](https://github.com/juspay/hyperswitch/commit/fc72c3eee826ca813010a09cb73178f5da88c71a))
- **router:** Add v2 endpoint to list payment attempts by intent_id ([#8368](https://github.com/juspay/hyperswitch/pull/8368)) ([`7943fb4`](https://github.com/juspay/hyperswitch/commit/7943fb4bfb156e22d5329d45a580f90e02283604))
**Full Changelog:** [`2025.06.20.0...2025.06.20.1`](https://github.com/juspay/hyperswitch/compare/2025.06.20.0...2025.06.20.1)
- - -
## 2025.06.20.0
### Features
- **kafka:** Add payment_intent payment_attempt and refund kafka events for v2 ([#8328](https://github.com/juspay/hyperswitch/pull/8328)) ([`305ca9b`](https://github.com/juspay/hyperswitch/commit/305ca9bda9d3c5bf3cc97458b7ed07b79e894154))
### Bug Fixes
- **connectors:** [worldpayvantiv] change endpoint, add billing address and fix 5xx incase of psync ([#8354](https://github.com/juspay/hyperswitch/pull/8354)) ([`5f7055f`](https://github.com/juspay/hyperswitch/commit/5f7055fc8c0d4b4c5e329fa6a527371338ef3b38))
**Full Changelog:** [`2025.06.19.0...2025.06.20.0`](https://github.com/juspay/hyperswitch/compare/2025.06.19.0...2025.06.20.0)
- - -
## 2025.06.19.0
### Bug Fixes
- **connector:** [STRIPE] Retrieving Connect Account Id from Mandate Metadata in MITs ([#8326](https://github.com/juspay/hyperswitch/pull/8326)) ([`17c30b6`](https://github.com/juspay/hyperswitch/commit/17c30b6105d9086585edac0c89432b1f4568c3de))
- **router:** Move Customer PML endpoint to OLAP (v2) ([#8303](https://github.com/juspay/hyperswitch/pull/8303)) ([`aee3f64`](https://github.com/juspay/hyperswitch/commit/aee3f6441f83d0641f0f38be79d4790303271d92))
**Full Changelog:** [`2025.06.18.0...2025.06.19.0`](https://github.com/juspay/hyperswitch/compare/2025.06.18.0...2025.06.19.0)
- - -
## 2025.06.18.0
### Features
- **core:** Accept merchant_connector_details in Payments and Psync flow ([#8199](https://github.com/juspay/hyperswitch/pull/8199)) ([`b8b1960`](https://github.com/juspay/hyperswitch/commit/b8b19605d83b94d248bb68a3fc7d83e22187a5b1))
- **payment_methods:** Populate connector_customer during customer creation step in payment methods migrate flow ([#8319](https://github.com/juspay/hyperswitch/pull/8319)) ([`3899ddd`](https://github.com/juspay/hyperswitch/commit/3899ddd52941aa6ba756f9a00b078245d7b47532))
### Bug Fixes
- **connector:** [ARCHIPEL] Make card_holder_name as none if cardholder field is none ([#8359](https://github.com/juspay/hyperswitch/pull/8359)) ([`7f6f4c4`](https://github.com/juspay/hyperswitch/commit/7f6f4c47fe0610196b19ce730a0cfd0da405d775))
### Refactors
- **routing:** Routing events core refactor ([#8323](https://github.com/juspay/hyperswitch/pull/8323)) ([`4d36be8`](https://github.com/juspay/hyperswitch/commit/4d36be87ec090ae57f8568d33c99cc1108ecc2b8))
**Full Changelog:** [`2025.06.17.0...2025.06.18.0`](https://github.com/juspay/hyperswitch/compare/2025.06.17.0...2025.06.18.0)
- - -
## 2025.06.17.0
### Features
- **core:**
- Fix Wasm changes for Tokenio Open Banking ([#8347](https://github.com/juspay/hyperswitch/pull/8347)) ([`800c5e6`](https://github.com/juspay/hyperswitch/commit/800c5e68dad47425c4d527f4362cef8557cb2953))
- Consume card details from billing connectors and first error codes and store them in payment intent table ([#8250](https://github.com/juspay/hyperswitch/pull/8250)) ([`abe9708`](https://github.com/juspay/hyperswitch/commit/abe9708d1c078b830de439ab54d17fa7340fbef5))
- **router:** Add retry support for debit routing ([#8220](https://github.com/juspay/hyperswitch/pull/8220)) ([`b5b7cfa`](https://github.com/juspay/hyperswitch/commit/b5b7cfafcf7602f7e9be46914514adf16a4ee83d))
- Add nix shell environments ([#8329](https://github.com/juspay/hyperswitch/pull/8329)) ([`e3233c6`](https://github.com/juspay/hyperswitch/commit/e3233c67fc0194f3e487be97f84a7be83408ac16))
### Bug Fixes
- **ci:** Update api-reference path in pr_labeler job ([#8344](https://github.com/juspay/hyperswitch/pull/8344)) ([`0eab55d`](https://github.com/juspay/hyperswitch/commit/0eab55d17aef3caa160878bc9b2be29deb37711d))
- Correct error for env not found ([#8320](https://github.com/juspay/hyperswitch/pull/8320)) ([`71bed12`](https://github.com/juspay/hyperswitch/commit/71bed12edce154b65f5cdd48270af8b4b1234ad9))
### Refactors
- Add compatibility for decision-engine rules ([#8346](https://github.com/juspay/hyperswitch/pull/8346)) ([`1ed2f21`](https://github.com/juspay/hyperswitch/commit/1ed2f210b2fec95696b98cfbe67c620c8fe716ff))
**Full Changelog:** [`2025.06.16.0...2025.06.17.0`](https://github.com/juspay/hyperswitch/compare/2025.06.16.0...2025.06.17.0)
- - -
## 2025.06.16.0
### Features
- **connector:** [trustpay] introduce instant bank_transfer, finland and poland ([#7925](https://github.com/juspay/hyperswitch/pull/7925)) ([`61c2e2c`](https://github.com/juspay/hyperswitch/commit/61c2e2c75fabdb03c5599df97240a030cb7b5b6a))
- Migration api for migrating routing rules to decision_engine ([#8233](https://github.com/juspay/hyperswitch/pull/8233)) ([`9045eb5`](https://github.com/juspay/hyperswitch/commit/9045eb5b65c21ee0c9746ee591b5f00bbce3b890))
### Bug Fixes
- **connector:** [ARCHIPEL] Change connector fields that are currently implemented as required in the code to optional ([#8342](https://github.com/juspay/hyperswitch/pull/8342)) ([`cfd0b07`](https://github.com/juspay/hyperswitch/commit/cfd0b0795e8d33f4d963861c22e1ba9ceba7c716))
- **postman:** Fix `stripe` test cases failures ([#8339](https://github.com/juspay/hyperswitch/pull/8339)) ([`535a927`](https://github.com/juspay/hyperswitch/commit/535a927e426f90bb6334e949d3f03fd1d190b714))
### Refactors
- **dynamic_routing:** Add support for shuffle on tie flag to success_based routing ([#8241](https://github.com/juspay/hyperswitch/pull/8241)) ([`c72d365`](https://github.com/juspay/hyperswitch/commit/c72d365fdeac13e3aa65b4c3d1f876b9c419168e))
### Documentation
- **openapi:** Show API version selection dropdown in Mintlify ([#8333](https://github.com/juspay/hyperswitch/pull/8333)) ([`ce85b83`](https://github.com/juspay/hyperswitch/commit/ce85b838f49d616335462e701e93ded2c6c58936))
### Miscellaneous Tasks
- **postman:** Update Postman collection files ([`94c32c8`](https://github.com/juspay/hyperswitch/commit/94c32c8e546134666eb98b3d5546152c1613ea5a))
**Full Changelog:** [`2025.06.13.0...2025.06.16.0`](https://github.com/juspay/hyperswitch/compare/2025.06.13.0...2025.06.16.0)
- - -
## 2025.06.13.0
### Features
- **authentication:** Create api for update profile acquirer ([#8307](https://github.com/juspay/hyperswitch/pull/8307)) ([`d33e344`](https://github.com/juspay/hyperswitch/commit/d33e344f82ca63e217c54893816218d60166a6cd))
- **dashboard:** Added wasm changes for threedsecure.io for collecting acquirer_bin, acquirer_merchant_id and acquirer_country_code in MCA ([#8330](https://github.com/juspay/hyperswitch/pull/8330)) ([`4318c93`](https://github.com/juspay/hyperswitch/commit/4318c934dd3d51e312e16fc524294982a33294d0))
- **router:** Add `merchant_category_code` in business profile ([#8296](https://github.com/juspay/hyperswitch/pull/8296)) ([`0f14279`](https://github.com/juspay/hyperswitch/commit/0f14279866350fff86deb6c9fd3d39765f4709e2))
### Refactors
- **debit_routing:** Filter debit networks based on merchant connector account configuration ([#8175](https://github.com/juspay/hyperswitch/pull/8175)) ([`5f97b7b`](https://github.com/juspay/hyperswitch/commit/5f97b7bce57766745cb64270921b0f38951df6ae))
- Add result type for Program ([#8179](https://github.com/juspay/hyperswitch/pull/8179)) ([`261818f`](https://github.com/juspay/hyperswitch/commit/261818f215787bb0247a8b67e02856f690d47c71))
**Full Changelog:** [`2025.06.12.0...2025.06.13.0`](https://github.com/juspay/hyperswitch/compare/2025.06.12.0...2025.06.13.0)
- - -
## 2025.06.12.0
### Features
- **authentication:** Added profile acquirer create module ([#8155](https://github.com/juspay/hyperswitch/pull/8155)) ([`f54d785`](https://github.com/juspay/hyperswitch/commit/f54d785ed49a0397fb62086284e39b590757ed83))
- **connector:** Implement Razorpay UPI Collect ([#8009](https://github.com/juspay/hyperswitch/pull/8009)) ([`ee7bce0`](https://github.com/juspay/hyperswitch/commit/ee7bce0ff6cbdb11d1d3018c1198131ba3bafad6))
### Bug Fixes
- **connector:** [trustpay] fix webhook deserialization error ([#8116](https://github.com/juspay/hyperswitch/pull/8116)) ([`0fb7eb0`](https://github.com/juspay/hyperswitch/commit/0fb7eb0b92017473b26028371a83c0d9ff46d0fd))
### Refactors
- **dynamic_routing:** Change the response type of update gateway score api in open router ([#8308](https://github.com/juspay/hyperswitch/pull/8308)) ([`ff5b2e8`](https://github.com/juspay/hyperswitch/commit/ff5b2e8e95fe82c201e4549e8308755dd945b6a4))
- **refunds_v2:** Change refunds v2 list request verb from GET to POST ([#8289](https://github.com/juspay/hyperswitch/pull/8289)) ([`6ea2e2a`](https://github.com/juspay/hyperswitch/commit/6ea2e2a6f4f7b6b6d3b2e99392e67a4c0e61c78a))
- **router:** Remove `payment_methods_v2` and `customer_v2` feature flag ([#8236](https://github.com/juspay/hyperswitch/pull/8236)) ([`000aa23`](https://github.com/juspay/hyperswitch/commit/000aa23c105804da4dbd5eb1bf168bd9ca5b501a))
### Documentation
- Improve readme ([#8251](https://github.com/juspay/hyperswitch/pull/8251)) ([`1e20b57`](https://github.com/juspay/hyperswitch/commit/1e20b57a0664ae94e948e4c47356d423b64cd494))
- Improving API Reference ([#8194](https://github.com/juspay/hyperswitch/pull/8194)) ([`5ce2ab2`](https://github.com/juspay/hyperswitch/commit/5ce2ab2d059d48a0f8305d65f45c7960c6939803))
**Full Changelog:** [`2025.06.11.0...2025.06.12.0`](https://github.com/juspay/hyperswitch/compare/2025.06.11.0...2025.06.12.0)
- - -
## 2025.06.11.0
### Features
- **connector:** [TRUSTPAY] Added Integrity Checks for PSync & RSync flows & Added New Variants in AttemptStatus & IntentStatus ([#8096](https://github.com/juspay/hyperswitch/pull/8096)) ([`a76a9c1`](https://github.com/juspay/hyperswitch/commit/a76a9c1514e503d5a73fc45ee99f530ff233ef68))
- **core:** Make installment_payment_enabled,recurring_enabled Optional ([#8201](https://github.com/juspay/hyperswitch/pull/8201)) ([`171ca3b`](https://github.com/juspay/hyperswitch/commit/171ca3b5645d8b0b7715939c46509cfa03af12ae))
### Bug Fixes
- **connector:**
- Removed forked josekit dependency from payout connector Nomupay ([#8183](https://github.com/juspay/hyperswitch/pull/8183)) ([`b1628f7`](https://github.com/juspay/hyperswitch/commit/b1628f798146e8222bc9bac72f7928a3d9285af3))
- [jpmorgan] 5xx during payment authorize and `cancellation_reason` ([#8282](https://github.com/juspay/hyperswitch/pull/8282)) ([`80206ee`](https://github.com/juspay/hyperswitch/commit/80206eed4234e851d1609e9cf6832b8fda68976e))
- [STRIPE] Throwing Missing Required Field Error if connector_customer is not present ([#8309](https://github.com/juspay/hyperswitch/pull/8309)) ([`c3a7f5c`](https://github.com/juspay/hyperswitch/commit/c3a7f5c43db48689092c1da5ff8ecbd32a862e84))
- Add RedirectInsidePopup response redirection URL ([#8257](https://github.com/juspay/hyperswitch/pull/8257)) ([`df34ff4`](https://github.com/juspay/hyperswitch/commit/df34ff43dcdb8facd4b9e670c81d0aa125639e4c))
- **cypress:** Fix itaubank, datatrans and facilitapay ([#8229](https://github.com/juspay/hyperswitch/pull/8229)) ([`e0ea1b4`](https://github.com/juspay/hyperswitch/commit/e0ea1b48321181457a12ed6172edd4bc46506792))
- Payment link styling for dynamic classes ([#8273](https://github.com/juspay/hyperswitch/pull/8273)) ([`be3fc6c`](https://github.com/juspay/hyperswitch/commit/be3fc6c742014f3304631b2efd6d8beb72b924f8))
### Refactors
- **connectors:** [worldpayvantiv] replace sandbox url with pre-live url and fix typo ([#8286](https://github.com/juspay/hyperswitch/pull/8286)) ([`67a42f0`](https://github.com/juspay/hyperswitch/commit/67a42f0c27157f876698982a6b5f0a1cd3e15ffb))
### Revert
- **connector:** [Worldpay] add root CA certificate ([#8224](https://github.com/juspay/hyperswitch/pull/8224)) ([`dab4058`](https://github.com/juspay/hyperswitch/commit/dab4058bfc94d9883a298930040324d22bb71a7c))
| CHANGELOG.md#chunk5 | null | doc_chunk | 8,150 | doc | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/paypal.rs
Public functions: 2
Public structs: 1
pub mod transformers;
use std::{fmt::Write, sync::LazyLock};
use base64::Engine;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
consts,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit,
StringMinorUnitForConnector,
},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData},
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, IncrementalAuthorization, PSync, PaymentMethodToken,
PostSessionTokens, PreProcessing, SdkSessionUpdate, Session, SetupMandate, Void,
},
refunds::{Execute, RSync},
CompleteAuthorize, VerifyWebhookSource,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsPostSessionTokensData,
PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData, ResponseId,
SdkPaymentsSessionUpdateData, SetupMandateRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt, VerifyWebhookSourceResponseData,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsIncrementalAuthorizationRouterData,
PaymentsPostSessionTokensRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
SdkSessionUpdateRouterData, SetupMandateRouterData, VerifyWebhookSourceRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::{PoCreate, PoFulfill, PoSync},
router_response_types::PayoutsResponseData,
types::{PayoutsData, PayoutsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{PayoutFulfillType, PayoutSyncType};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation, PaymentIncrementalAuthorization,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
disputes, errors,
events::connector_api_logs::ConnectorEvent,
types::{
IncrementalAuthorizationType, PaymentsAuthorizeType, PaymentsCaptureType,
PaymentsCompleteAuthorizeType, PaymentsPostSessionTokensType, PaymentsPreProcessingType,
PaymentsSyncType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType,
Response, SdkSessionUpdateType, SetupMandateType, VerifyWebhookSourceType,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret};
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
use transformers::{
self as paypal, auth_headers, PaypalAuthResponse, PaypalIncrementalAuthResponse, PaypalMeta,
PaypalWebhookEventType,
};
use crate::{
constants::{self, headers},
types::ResponseRouterData,
utils::{
self as connector_utils, to_connector_meta, ConnectorErrorType, ConnectorErrorTypeMapping,
ForeignTryFrom, PaymentMethodDataType, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, RefundsRequestData,
},
};
#[derive(Clone)]
pub struct Paypal {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Paypal {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
amount_converter_webhooks: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Paypal {}
impl api::PaymentSession for Paypal {}
impl api::PaymentToken for Paypal {}
impl api::ConnectorAccessToken for Paypal {}
impl api::MandateSetup for Paypal {}
impl api::PaymentAuthorize for Paypal {}
impl api::PaymentsCompleteAuthorize for Paypal {}
impl api::PaymentSync for Paypal {}
impl api::PaymentCapture for Paypal {}
impl api::PaymentVoid for Paypal {}
impl api::Refund for Paypal {}
impl api::RefundExecute for Paypal {}
impl api::RefundSync for Paypal {}
impl api::ConnectorVerifyWebhookSource for Paypal {}
impl api::PaymentPostSessionTokens for Paypal {}
impl api::PaymentSessionUpdate for Paypal {}
impl api::Payouts for Paypal {}
#[cfg(feature = "payouts")]
impl api::PayoutCreate for Paypal {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Paypal {}
#[cfg(feature = "payouts")]
impl api::PayoutSync for Paypal {}
impl Paypal {
pub fn get_order_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
//Handled error response separately for Orders as the end point is different for Orders - (Authorize) and Payments - (Capture, void, refund, rsync).
//Error response have different fields for Orders and Payments.
let response: paypal::PaypalOrderErrorResponse = res
.response
.parse_struct("Paypal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_reason = response.details.clone().map(|order_errors| {
order_errors
.iter()
.map(|error| {
let mut reason = format!("description - {}", error.description);
if let Some(value) = &error.value {
reason.push_str(&format!(", value - {value}"));
}
if let Some(field) = error
.field
.as_ref()
.and_then(|field| field.split('/').next_back())
{
reason.push_str(&format!(", field - {field}"));
}
reason.push(';');
reason
})
.collect::<String>()
});
let errors_list = response.details.unwrap_or_default();
let option_error_code_message =
connector_utils::get_error_code_error_message_based_on_priority(
self.clone(),
errors_list
.into_iter()
.map(|errors| errors.into())
.collect(),
);
Ok(ErrorResponse {
status_code: res.status_code,
code: option_error_code_message
.clone()
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(NO_ERROR_CODE.to_string()),
message: option_error_code_message
.map(|error_code_message| error_code_message.error_message)
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: error_reason.or(Some(response.message)),
attempt_status: None,
connector_transaction_id: response.debug_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paypal
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let key = &req.connector_request_reference_id;
let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into_masked(),
),
(
auth_headers::PREFER.to_string(),
"return=representation".to_string().into(),
),
(
auth_headers::PAYPAL_REQUEST_ID.to_string(),
key.to_string().into_masked(),
),
];
if let Ok(paypal::PaypalConnectorCredentials::PartnerIntegration(credentials)) =
auth.get_credentials()
{
let auth_assertion_header =
construct_auth_assertion_header(&credentials.payer_id, &credentials.client_id);
headers.extend(vec![
(
auth_headers::PAYPAL_AUTH_ASSERTION.to_string(),
auth_assertion_header.to_string().into_masked(),
),
(
auth_headers::PAYPAL_PARTNER_ATTRIBUTION_ID.to_string(),
"HyperSwitchPPCP_SP".to_string().into(),
),
])
} else {
headers.extend(vec![(
auth_headers::PAYPAL_PARTNER_ATTRIBUTION_ID.to_string(),
"HyperSwitchlegacy_Ecom".to_string().into(),
)])
}
Ok(headers)
}
}
fn construct_auth_assertion_header(
payer_id: &Secret<String>,
client_id: &Secret<String>,
) -> String {
let algorithm = consts::BASE64_ENGINE
.encode("{\"alg\":\"none\"}")
.to_string();
let merchant_credentials = format!(
"{{\"iss\":\"{}\",\"payer_id\":\"{}\"}}",
client_id.clone().expose(),
payer_id.clone().expose()
);
let encoded_credentials = consts::BASE64_ENGINE
.encode(merchant_credentials)
.to_string();
format!("{algorithm}.{encoded_credentials}.")
}
impl ConnectorCommon for Paypal {
fn id(&self) -> &'static str {
"paypal"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.paypal.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = paypal::PaypalAuthType::try_from(auth_type)?;
let credentials = auth.get_credentials()?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
credentials.get_client_secret().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paypal::PaypalPaymentErrorResponse = res
.response
.parse_struct("Paypal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_reason = response
.details
.clone()
.map(|error_details| {
error_details
.iter()
.try_fold(String::new(), |mut acc, error| {
if let Some(description) = &error.description {
write!(acc, "description - {description} ;")
.change_context(
errors::ConnectorError::ResponseDeserializationFailed,
)
.attach_printable("Failed to concatenate error details")
.map(|_| acc)
} else {
Ok(acc)
}
})
})
.transpose()?;
let reason = match error_reason {
Some(err_reason) => err_reason
.is_empty()
.then(|| response.message.to_owned())
.or(Some(err_reason)),
None => Some(response.message.to_owned()),
};
let errors_list = response.details.unwrap_or_default();
let option_error_code_message =
connector_utils::get_error_code_error_message_based_on_priority(
self.clone(),
errors_list
.into_iter()
.map(|errors| errors.into())
.collect(),
);
Ok(ErrorResponse {
status_code: res.status_code,
code: option_error_code_message
.clone()
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(NO_ERROR_CODE.to_string()),
message: option_error_code_message
.map(|error_code_message| error_code_message.error_message)
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason,
attempt_status: None,
connector_transaction_id: response.debug_id,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Paypal {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::PaypalRedirect,
PaymentMethodDataType::PaypalSdk,
]);
connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Paypal
{
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paypal {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paypal {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/oauth2/token", self.base_url(connectors)))
}
fn get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn get_headers(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?;
let credentials = auth.get_credentials()?;
let auth_val = credentials.generate_authorization_value();
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
),
(headers::AUTHORIZATION.to_string(), auth_val.into_masked()),
])
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = paypal::PaypalAuthUpdateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.headers(RefreshTokenType::get_headers(self, req, connectors)?)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: paypal::PaypalAuthUpdateResponse = res
.response
.parse_struct("Paypal PaypalAuthUpdateResponse")
.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> {
let response: paypal::PaypalAccessTokenErrorResponse = res
.response
.parse_struct("Paypal AccessTokenErrorResponse")
.change_context(errors::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.clone(),
message: response.error.clone(),
reason: Some(response.error_description),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Paypal {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/payments/payouts", self.base_url(connectors)))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data =
paypal::PaypalRouterData::try_from((amount, None, None, None, req))?;
let connector_req = paypal::PaypalFulfillRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: paypal::PaypalFulfillResponse = res
.response
.parse_struct("PaypalFulfillResponse")
.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)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for Paypal {
fn get_url(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let batch_id = req.request.connector_payout_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "connector_payout_id",
},
)?;
Ok(format!(
"{}v1/payments/payouts/{}",
self.base_url(connectors),
batch_id
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn build_request(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&PayoutSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutSyncType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoSync>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoSync>, errors::ConnectorError> {
let response: paypal::PaypalPayoutSyncResponse = res
.response
.parse_struct("PaypalPayoutSyncResponse")
.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]
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Paypal {
fn build_request(
&self,
_req: &PayoutsRouterData<PoCreate>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
// Eligibility check for wallet is not implemented
Err(
errors::ConnectorError::NotImplemented("Payout Eligibility for Paypal".to_string())
.into(),
)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paypal {
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, 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: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}v3/vault/payment-tokens/",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = paypal::PaypalZeroMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: paypal::PaypalSetupMandatesResponse = res
.response
.parse_struct("PaypalSetupMandatesResponse")
.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<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>
for Paypal
{
fn get_headers(
&self,
req: &PaymentsPostSessionTokensRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, 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: &PaymentsPostSessionTokensRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v2/checkout/orders", self.base_url(connectors)))
}
fn build_request(
&self,
req: &PaymentsPostSessionTokensRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsPostSessionTokensType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsPostSessionTokensType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsPostSessionTokensType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn get_request_body(
&self,
req: &PaymentsPostSessionTokensRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.amount,
req.request.currency,
)?;
let shipping_cost = connector_utils::convert_amount(
self.amount_converter,
req.request.shipping_cost.unwrap_or(MinorUnit::zero()),
req.request.currency,
)?;
let order_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.order_amount,
req.request.currency,
)?;
let connector_router_data = paypal::PaypalRouterData::try_from((
amount,
Some(shipping_cost),
None,
Some(order_amount),
req,
))?;
let connector_req = paypal::PaypalPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &PaymentsPostSessionTokensRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPostSessionTokensRouterData, errors::ConnectorError> {
let response: paypal::PaypalRedirectResponse = res
.response
.parse_struct("PaypalRedirectResponse")
.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.get_order_error_response(res, event_builder)
}
}
impl ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>
for Paypal
{
fn get_headers(
&self,
req: &SdkSessionUpdateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, 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: &SdkSessionUpdateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let session_id =
req.request
.session_id
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "session_id",
})?;
Ok(format!(
"{}v2/checkout/orders/{}",
self.base_url(connectors),
session_id
))
}
fn build_request(
&self,
req: &SdkSessionUpdateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Patch)
.url(&SdkSessionUpdateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SdkSessionUpdateType::get_headers(self, req, connectors)?)
.set_body(SdkSessionUpdateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn get_request_body(
&self,
req: &SdkSessionUpdateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let order_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.order_amount,
req.request.currency,
)?;
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.amount,
req.request.currency,
)?;
let order_tax_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.order_tax_amount,
req.request.currency,
)?;
let shipping_cost = connector_utils::convert_amount(
self.amount_converter,
req.request.shipping_cost.unwrap_or(MinorUnit::zero()),
req.request.currency,
)?;
let connector_router_data = paypal::PaypalRouterData::try_from((
amount,
Some(shipping_cost),
Some(order_tax_amount),
Some(order_amount),
req,
))?;
let connector_req = paypal::PaypalUpdateOrderRequest::try_from(&connector_router_data)?;
// encode only for for urlencoded things.
Ok(RequestContent::Json(Box::new(
connector_req.get_inner_value(),
)))
}
fn handle_response(
&self,
data: &SdkSessionUpdateRouterData,
_event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SdkSessionUpdateRouterData, errors::ConnectorError> {
router_env::logger::debug!("Expected zero bytes response, skipped parsing of the response");
// https://developer.paypal.com/docs/api/orders/v2/#orders_patch
// If 204 status code, then the session was updated successfully.
let status = if res.status_code == 204 {
enums::PaymentResourceUpdateStatus::Success
} else {
enums::PaymentResourceUpdateStatus::Failure
};
Ok(SdkSessionUpdateRouterData {
response: Ok(PaymentsResponseData::PaymentResourceUpdateResponse { status }),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paypal {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, 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> {
match &req.request.payment_method_data {
PaymentMethodData::Wallet(WalletData::PaypalSdk(paypal_wallet_data)) => {
let authorize_url = if req.request.is_auto_capture()? {
"capture".to_string()
} else {
"authorize".to_string()
};
Ok(format!(
"{}v2/checkout/orders/{}/{authorize_url}",
self.base_url(connectors),
paypal_wallet_data.token
))
}
_ => Ok(format!("{}v2/checkout/orders", self.base_url(connectors))),
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let shipping_cost = connector_utils::convert_amount(
self.amount_converter,
req.request.shipping_cost.unwrap_or(MinorUnit::zero()),
req.request.currency,
)?;
let connector_router_data =
paypal::PaypalRouterData::try_from((amount, Some(shipping_cost), None, None, req))?;
let connector_req = paypal::PaypalPaymentsRequest::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> {
let payment_method_data = req.request.payment_method_data.clone();
let req = match payment_method_data {
PaymentMethodData::Wallet(WalletData::PaypalSdk(_)) => RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.build(),
_ => 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(),
};
Ok(Some(req))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: PaypalAuthResponse =
res.response
.parse_struct("paypal PaypalAuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
match response {
PaypalAuthResponse::PaypalOrdersResponse(response) => {
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,
})
}
PaypalAuthResponse::PaypalRedirectResponse(response) => {
event_builder.map(|i| i.set_response_body(&response)); | crates/hyperswitch_connectors/src/connectors/paypal.rs#chunk0 | hyperswitch_connectors | chunk | 8,182 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct CeleroErrorResponse {
pub status: CeleroResponseStatus,
pub msg: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
} | crates/hyperswitch_connectors/src/connectors/celero/transformers.rs | hyperswitch_connectors | struct_definition | 46 | rust | CeleroErrorResponse | null | null | null | null | null | null | null | null | null | null | null |
pub struct ConnectorMandateDetails {
pub connector_mandate_id: masking::Secret<String>,
} | crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs | hyperswitch_domain_models | struct_definition | 22 | rust | ConnectorMandateDetails | null | null | null | null | null | null | null | null | null | null | null |
pub struct NuveiRedirectionResponse {
pub cres: Secret<String>,
} | crates/hyperswitch_connectors/src/connectors/nuvei/transformers.rs | hyperswitch_connectors | struct_definition | 17 | rust | NuveiRedirectionResponse | null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_role(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::GetRole;
let request_payload = user_role_api::role::GetRoleRequest {
role_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
request_payload,
|state, user, payload, _| async move {
role_core::get_role_with_groups(state, user, payload).await
},
&auth::JWTAuth {
permission: Permission::ProfileUserRead,
},
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/user_role.rs | router | function_signature | 157 | rust | null | null | null | null | get_role | null | null | null | null | null | null | null |
pub struct ThreedsecureioPostAuthenticationResponse {
pub authentication_value: Option<Secret<String>>,
pub trans_status: ThreedsecureioTransStatus,
pub eci: Option<String>,
} | crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs | hyperswitch_connectors | struct_definition | 41 | rust | ThreedsecureioPostAuthenticationResponse | null | null | null | null | null | null | null | null | null | null | null |
pub struct PayloadRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
} | crates/hyperswitch_connectors/src/connectors/payload/transformers.rs | hyperswitch_connectors | struct_definition | 24 | rust | PayloadRouterData | null | null | null | null | null | null | null | null | null | null | null |
pub async fn profile_create() {} | crates/openapi/src/routes/profile.rs | openapi | function_signature | 7 | rust | null | null | null | null | profile_create | null | null | null | null | null | null | null |
pub struct CybersourceAuthEnrollmentRequest {
payment_information: PaymentInformation,
client_reference_information: ClientReferenceInformation,
consumer_authentication_information: CybersourceConsumerAuthInformationRequest,
order_information: OrderInformationWithBill,
} | crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs | hyperswitch_connectors | struct_definition | 49 | rust | CybersourceAuthEnrollmentRequest | null | null | null | null | null | null | null | null | null | null | null |
pub fn new() -> Self {
// Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"`
// before running tests in shell
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.expect("connector authentication file path not set");
// Read the file contents to a JsonString
let contents =
&std::fs::read_to_string(path).expect("Failed to read connector authentication file");
// Deserialize the JsonString to a HashMap
let auth_config: HashMap<String, toml::Value> =
toml::from_str(contents).expect("Failed to deserialize TOML file");
// auth_config contains the data in below given format:
// {
// "connector_name": Table(
// {
// "api_key": String(
// "API_Key",
// ),
// "api_secret": String(
// "Secret key",
// ),
// "key1": String(
// "key1",
// ),
// "key2": String(
// "key2",
// ),
// },
// ),
// "connector_name": Table(
// ...
// }
// auth_map refines and extracts required information
let auth_map = auth_config
.into_iter()
.map(|(connector_name, config)| {
let auth_type = match config {
toml::Value::Table(mut table) => {
if let Some(auth_key_map_value) = table.remove("auth_key_map") {
// This is a CurrencyAuthKey
if let toml::Value::Table(auth_key_map_table) = auth_key_map_value {
let mut parsed_auth_map = HashMap::new();
for (currency, val) in auth_key_map_table {
if let Ok(currency_enum) =
currency.parse::<common_enums::Currency>()
{
parsed_auth_map
.insert(currency_enum, Secret::new(val.to_string()));
}
}
ConnectorAuthType::CurrencyAuthKey {
auth_key_map: parsed_auth_map,
}
} else {
ConnectorAuthType::NoKey
}
} else {
match (
table.get("api_key"),
table.get("key1"),
table.get("api_secret"),
table.get("key2"),
) {
(Some(api_key), None, None, None) => ConnectorAuthType::HeaderKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
},
(Some(api_key), Some(key1), None, None) => {
ConnectorAuthType::BodyKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), None) => {
ConnectorAuthType::SignatureKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), Some(key2)) => {
ConnectorAuthType::MultiAuthKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
key2: Secret::new(
key2.as_str().unwrap_or_default().to_string(),
),
}
}
_ => ConnectorAuthType::NoKey,
}
}
}
_ => ConnectorAuthType::NoKey,
};
(connector_name, auth_type)
})
.collect();
Self(auth_map)
} | crates/test_utils/src/connector_auth.rs | test_utils | function_signature | 904 | rust | null | null | null | null | new | null | null | null | null | null | null | null |
pub struct CardNetworkTokenizeRecord {
// Card details
pub raw_card_number: Option<CardNumber>,
pub card_expiry_month: Option<masking::Secret<String>>,
pub card_expiry_year: Option<masking::Secret<String>>,
pub card_cvc: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
pub nick_name: Option<masking::Secret<String>>,
pub card_issuing_country: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_issuer: Option<String>,
pub card_type: Option<payment_methods_api::CardType>,
// Payment method details
pub payment_method_id: Option<String>,
pub payment_method_type: Option<payment_methods_api::CardType>,
pub payment_method_issuer: Option<String>,
// Customer details
pub customer_id: id_type::CustomerId,
#[serde(rename = "name")]
pub customer_name: Option<masking::Secret<String>>,
#[serde(rename = "email")]
pub customer_email: Option<pii::Email>,
#[serde(rename = "phone")]
pub customer_phone: Option<masking::Secret<String>>,
#[serde(rename = "phone_country_code")]
pub customer_phone_country_code: Option<String>,
#[serde(rename = "tax_registration_id")]
pub customer_tax_registration_id: Option<masking::Secret<String>>,
// Billing details
pub billing_address_city: Option<String>,
pub billing_address_country: Option<enums::CountryAlpha2>,
pub billing_address_line1: Option<masking::Secret<String>>,
pub billing_address_line2: Option<masking::Secret<String>>,
pub billing_address_line3: Option<masking::Secret<String>>,
pub billing_address_zip: Option<masking::Secret<String>>,
pub billing_address_state: Option<masking::Secret<String>>,
pub billing_address_first_name: Option<masking::Secret<String>>,
pub billing_address_last_name: Option<masking::Secret<String>>,
pub billing_phone_number: Option<masking::Secret<String>>,
pub billing_phone_country_code: Option<String>,
pub billing_email: Option<pii::Email>,
// Other details
pub line_number: Option<u64>,
pub merchant_id: Option<id_type::MerchantId>,
} | crates/hyperswitch_domain_models/src/bulk_tokenization.rs | hyperswitch_domain_models | struct_definition | 497 | rust | CardNetworkTokenizeRecord | null | null | null | null | null | null | null | null | null | null | null |
pub async fn proxy_create_domain_model(
payment_intent: &super::PaymentIntent,
cell_id: id_type::CellId,
storage_scheme: storage_enums::MerchantStorageScheme,
request: &api_models::payments::ProxyPaymentsRequest,
encrypted_data: DecryptedPaymentAttempt,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let id = id_type::GlobalAttemptId::generate(&cell_id);
let intent_amount_details = payment_intent.amount_details.clone();
let attempt_amount_details =
intent_amount_details.proxy_create_attempt_amount_details(request);
let now = common_utils::date_time::now();
let payment_method_billing_address = encrypted_data
.payment_method_billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
let connector_token = Some(diesel_models::ConnectorTokenDetails {
connector_mandate_id: None,
connector_token_request_reference_id: Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)),
});
let payment_method_type_data = payment_intent.get_payment_method_type();
let payment_method_subtype_data = payment_intent.get_payment_method_sub_type();
let authentication_type = payment_intent.authentication_type.unwrap_or_default();
Ok(Self {
payment_id: payment_intent.id.clone(),
merchant_id: payment_intent.merchant_id.clone(),
amount_details: attempt_amount_details,
status: common_enums::AttemptStatus::Started,
connector: Some(request.connector.clone()),
authentication_type,
created_at: now,
modified_at: now,
last_synced: None,
cancellation_reason: None,
browser_info: request.browser_info.clone(),
payment_token: None,
connector_metadata: None,
payment_experience: None,
payment_method_data: None,
routing_result: None,
preprocessing_step_id: None,
multiple_capture_count: None,
connector_response_reference_id: None,
updated_by: storage_scheme.to_string(),
redirection_data: None,
encoded_data: None,
merchant_connector_id: Some(request.merchant_connector_id.clone()),
external_three_ds_authentication_attempted: None,
authentication_connector: None,
authentication_id: None,
fingerprint_id: None,
charges: None,
client_source: None,
client_version: None,
customer_acceptance: None,
profile_id: payment_intent.profile_id.clone(),
organization_id: payment_intent.organization_id.clone(),
payment_method_type: payment_method_type_data
.unwrap_or(common_enums::PaymentMethod::Card),
payment_method_id: None,
connector_payment_id: None,
payment_method_subtype: payment_method_subtype_data
.unwrap_or(common_enums::PaymentMethodType::Credit),
authentication_applied: None,
external_reference_id: None,
payment_method_billing_address,
error: None,
connector_token_details: connector_token,
feature_metadata: None,
id,
card_discovery: None,
processor_merchant_id: payment_intent.merchant_id.clone(),
created_by: None,
connector_request_reference_id: None,
network_transaction_id: None,
})
} | crates/hyperswitch_domain_models/src/payments/payment_attempt.rs | hyperswitch_domain_models | function_signature | 712 | rust | null | null | null | null | proxy_create_domain_model | null | null | null | null | null | null | null |
impl KafkaPaymentIntent<'_> {
#[cfg(feature = "v1")]
fn get_id(&self) -> &id_type::PaymentId {
self.payment_id
}
#[cfg(feature = "v2")]
fn get_id(&self) -> &id_type::GlobalPaymentId {
self.payment_id
}
} | crates/router/src/services/kafka/payment_intent.rs | router | impl_block | 71 | rust | null | KafkaPaymentIntent | null | impl KafkaPaymentIntent | null | null | null | null | null | null | null | null |
impl api::RefundSync for Juspaythreedsserver {} | crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs | hyperswitch_connectors | impl_block | 15 | rust | null | Juspaythreedsserver | api::RefundSync for | impl api::RefundSync for for Juspaythreedsserver | null | null | null | null | null | null | null | null |
pub fn make_dsl_input_for_surcharge(
_payment_attempt: &oss_storage::PaymentAttempt,
_payment_intent: &oss_storage::PaymentIntent,
_billing_address: Option<Address>,
) -> RoutingResult<dsl_inputs::BackendInput> {
todo!()
} | crates/router/src/core/payments/routing.rs | router | function_signature | 59 | rust | null | null | null | null | make_dsl_input_for_surcharge | null | null | null | null | null | null | null |
pub fn payment_method_session_create() {} | crates/openapi/src/routes/payment_method.rs | openapi | function_signature | 8 | rust | null | null | null | null | payment_method_session_create | null | null | null | null | null | null | null |
fn get_payment_attempt_connector(&self) -> Option<&str> {
todo!()
}
fn get_merchant_connector_id_in_attempt(&self) -> Option<id_type::MerchantConnectorAccountId> {
todo!()
}
fn get_connector_customer_id(&self) -> Option<String> {
todo!()
}
fn get_billing_address(&self) -> Option<hyperswitch_domain_models::address::Address> {
todo!()
}
fn get_payment_method_data(&self) -> Option<&domain::PaymentMethodData> {
todo!()
}
fn get_sessions_token(&self) -> Vec<api::SessionToken> {
todo!()
}
fn get_token_data(&self) -> Option<&storage::PaymentTokenData> {
todo!()
}
fn get_mandate_connector(&self) -> Option<&MandateConnectorDetails> {
todo!()
}
fn get_force_sync(&self) -> Option<bool> {
todo!()
}
fn get_capture_method(&self) -> Option<enums::CaptureMethod> {
todo!()
}
#[cfg(feature = "v2")]
fn get_optional_payment_attempt(&self) -> Option<&storage::PaymentAttempt> {
todo!()
}
fn get_pre_routing_result(
&self,
) -> Option<HashMap<enums::PaymentMethodType, domain::PreRoutingConnectorChoice>> {
None
}
fn get_merchant_connector_details(
&self,
) -> Option<common_types::domain::MerchantConnectorAuthDetails> {
todo!()
}
fn get_optional_external_vault_session_details(&self) -> Option<api::VaultSessionDetails> {
todo!()
}
}
| crates/router/src/core/payments.rs#chunk11 | router | chunk | 378 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub fn new() -> &'static Self {
&Self {
amount_convertor: &MinorUnitForConnector,
}
} | crates/hyperswitch_connectors/src/connectors/opennode.rs | hyperswitch_connectors | function_signature | 28 | rust | null | null | null | null | new | null | null | null | null | null | null | null |
pub struct PaymentsMetricsResponse<T> {
pub query_data: Vec<T>,
pub meta_data: [PaymentsAnalyticsMetadata; 1],
} | crates/api_models/src/analytics.rs | api_models | struct_definition | 30 | rust | PaymentsMetricsResponse | null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/tests/connectors/worldpayxml.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct WorldpayxmlTest;
impl ConnectorActions for WorldpayxmlTest {}
impl utils::Connector for WorldpayxmlTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Worldpayxml;
utils::construct_connector_data_old(
Box::new(Worldpayxml::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.worldpayxml
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"Worldpayxml".to_string()
}
}
static CONNECTOR: WorldpayxmlTest = WorldpayxmlTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| crates/router/tests/connectors/worldpayxml.rs | router | full_file | 2,934 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub(crate) fn diesel_error_to_data_error(
diesel_error: diesel_models::errors::DatabaseError,
) -> StorageError {
match diesel_error {
diesel_models::errors::DatabaseError::DatabaseConnectionError => {
StorageError::DatabaseConnectionError
}
diesel_models::errors::DatabaseError::NotFound => {
StorageError::ValueNotFound("Value not found".to_string())
}
diesel_models::errors::DatabaseError::UniqueViolation => StorageError::DuplicateValue {
entity: "entity ",
key: None,
},
_ => StorageError::DatabaseError(error_stack::report!(diesel_error)),
}
} | crates/storage_impl/src/lib.rs | storage_impl | function_signature | 135 | rust | null | null | null | null | diesel_error_to_data_error | null | null | null | null | null | null | null |
pub struct WellsfargopayoutErrorResponse {
pub status_code: u16,
pub code: String,
pub message: String,
pub reason: Option<String>,
} | crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs | hyperswitch_connectors | struct_definition | 38 | rust | WellsfargopayoutErrorResponse | null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorCommon for Paytm {
fn id(&self) -> &'static str {
"paytm"
}
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.paytm.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
// This method is not implemented for Paytm, as it will always call the UCS service which has the logic to create headers.
Err(errors::ConnectorError::NotImplemented("get_auth_header method".to_string()).into())
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paytm::PaytmErrorResponse =
res.response
.parse_struct("PaytmErrorResponse")
.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,
})
}
} | crates/hyperswitch_connectors/src/connectors/paytm.rs | hyperswitch_connectors | impl_block | 375 | rust | null | Paytm | ConnectorCommon for | impl ConnectorCommon for for Paytm | null | null | null | null | null | null | null | null |
pub struct ErrorResponseBankRedirect {
#[serde(rename = "ResultInfo")]
pub payment_result_info: ResultInfo,
} | crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs | hyperswitch_connectors | struct_definition | 25 | rust | ErrorResponseBankRedirect | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.PaymentsPostSessionTokensRequest
{
"type": "object",
"required": [
"client_secret",
"payment_method_type",
"payment_method"
],
"properties": {
"client_secret": {
"type": "string",
"description": "It's a token used for client side verification."
},
"payment_method_type": {
"$ref": "#/components/schemas/PaymentMethodType"
},
"payment_method": {
"$ref": "#/components/schemas/PaymentMethod"
}
}
} | ./hyperswitch/api-reference/v1/openapi_spec_v1.json | null | openapi_block | 128 | .json | null | null | null | null | null | openapi_spec | components | [
"schemas",
"PaymentsPostSessionTokensRequest"
] | null | null | null | null |
pub async fn retrieve_poll_status() {} | crates/openapi/src/routes/poll.rs | openapi | function_signature | 8 | rust | null | null | null | null | retrieve_poll_status | null | null | null | null | null | null | null |
pub fn valid_business_statuses() -> Vec<&'static str> {
vec![storage::business_status::PENDING]
} | crates/scheduler/src/consumer.rs | scheduler | function_signature | 26 | rust | null | null | null | null | valid_business_statuses | null | null | null | null | null | null | null |
pub fn convert_connector_service_status_code(
status_code: u32,
) -> Result<u16, error_stack::Report<UnifiedConnectorServiceError>> {
u16::try_from(status_code).map_err(|err| {
UnifiedConnectorServiceError::RequestEncodingFailedWithReason(format!(
"Failed to convert connector service status code to u16: {err}"
))
.into()
})
} | crates/router/src/core/unified_connector_service/transformers.rs | router | function_signature | 89 | rust | null | null | null | null | convert_connector_service_status_code | null | null | null | null | null | null | null |
pub fn mk_add_bank_response_hs(
bank: api::BankPayout,
bank_reference: String,
req: api::PaymentMethodCreate,
merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
customer_id: req.customer_id,
payment_method_id: bank_reference,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
bank_transfer: Some(bank),
card: None,
metadata: req.metadata,
created: Some(common_utils::date_time::now()),
recurring_enabled: Some(false), // [#256]
installment_payment_enabled: Some(false), // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
client_secret: None,
}
} | crates/router/src/core/payment_methods/transformers.rs | router | function_signature | 203 | rust | null | null | null | null | mk_add_bank_response_hs | null | null | null | null | null | null | null |
pub async fn find_authentication_by_merchant_id_connector_authentication_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_authentication_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_authentication_id.eq(connector_authentication_id.to_owned())),
)
.await
} | crates/diesel_models/src/query/authentication.rs | diesel_models | function_signature | 114 | rust | null | null | null | null | find_authentication_by_merchant_id_connector_authentication_id | null | null | null | null | null | null | null |
File: crates/euclid/src/frontend/dir/transformers.rs
use crate::{dirval, dssa::types::AnalysisErrorType, enums as global_enums, frontend::dir};
pub trait IntoDirValue {
fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType>;
}
impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMethod) {
fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType> {
match self.0 {
global_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
global_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
#[cfg(feature = "v2")]
global_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)),
global_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
global_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)),
global_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)),
global_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)),
global_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)),
global_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)),
global_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)),
global_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)),
global_enums::PaymentMethodType::AfterpayClearpay => {
Ok(dirval!(PayLaterType = AfterpayClearpay))
}
global_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
global_enums::PaymentMethodType::Skrill => Ok(dirval!(WalletType = Skrill)),
global_enums::PaymentMethodType::Paysera => Ok(dirval!(WalletType = Paysera)),
global_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
global_enums::PaymentMethodType::Bluecode => Ok(dirval!(WalletType = Bluecode)),
global_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
global_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
global_enums::PaymentMethodType::RevolutPay => Ok(dirval!(WalletType = RevolutPay)),
global_enums::PaymentMethodType::CryptoCurrency => {
Ok(dirval!(CryptoType = CryptoCurrency))
}
global_enums::PaymentMethodType::Ach => match self.1 {
global_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)),
global_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)),
global_enums::PaymentMethod::PayLater
| global_enums::PaymentMethod::Card
| global_enums::PaymentMethod::CardRedirect
| global_enums::PaymentMethod::Wallet
| global_enums::PaymentMethod::BankRedirect
| global_enums::PaymentMethod::Crypto
| global_enums::PaymentMethod::Reward
| global_enums::PaymentMethod::RealTimePayment
| global_enums::PaymentMethod::Upi
| global_enums::PaymentMethod::Voucher
| global_enums::PaymentMethod::OpenBanking
| global_enums::PaymentMethod::MobilePayment
| global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported),
},
global_enums::PaymentMethodType::Bacs => match self.1 {
global_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Bacs)),
global_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Bacs)),
global_enums::PaymentMethod::PayLater
| global_enums::PaymentMethod::Card
| global_enums::PaymentMethod::CardRedirect
| global_enums::PaymentMethod::Wallet
| global_enums::PaymentMethod::BankRedirect
| global_enums::PaymentMethod::Crypto
| global_enums::PaymentMethod::Reward
| global_enums::PaymentMethod::RealTimePayment
| global_enums::PaymentMethod::Upi
| global_enums::PaymentMethod::Voucher
| global_enums::PaymentMethod::OpenBanking
| global_enums::PaymentMethod::MobilePayment
| global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported),
},
global_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)),
global_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)),
global_enums::PaymentMethodType::SepaBankTransfer => {
Ok(dirval!(BankTransferType = SepaBankTransfer))
}
global_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)),
global_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)),
global_enums::PaymentMethodType::BancontactCard => {
Ok(dirval!(BankRedirectType = BancontactCard))
}
global_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)),
global_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)),
global_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)),
global_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)),
global_enums::PaymentMethodType::Multibanco => {
Ok(dirval!(BankTransferType = Multibanco))
}
global_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)),
global_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)),
global_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)),
global_enums::PaymentMethodType::OnlineBankingCzechRepublic => {
Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic))
}
global_enums::PaymentMethodType::OnlineBankingFinland => {
Ok(dirval!(BankRedirectType = OnlineBankingFinland))
}
global_enums::PaymentMethodType::OnlineBankingPoland => {
Ok(dirval!(BankRedirectType = OnlineBankingPoland))
}
global_enums::PaymentMethodType::OnlineBankingSlovakia => {
Ok(dirval!(BankRedirectType = OnlineBankingSlovakia))
}
global_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)),
global_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)),
global_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)),
global_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)),
global_enums::PaymentMethodType::Flexiti => Ok(dirval!(PayLaterType = Flexiti)),
global_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)),
global_enums::PaymentMethodType::Breadpay => Ok(dirval!(PayLaterType = Breadpay)),
global_enums::PaymentMethodType::Przelewy24 => {
Ok(dirval!(BankRedirectType = Przelewy24))
}
global_enums::PaymentMethodType::PromptPay => {
Ok(dirval!(RealTimePaymentType = PromptPay))
}
global_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)),
global_enums::PaymentMethodType::ClassicReward => {
Ok(dirval!(RewardType = ClassicReward))
}
global_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
global_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
global_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
global_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
global_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
global_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
global_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)),
global_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)),
global_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)),
global_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)),
global_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)),
global_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)),
global_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)),
global_enums::PaymentMethodType::OnlineBankingFpx => {
Ok(dirval!(BankRedirectType = OnlineBankingFpx))
}
global_enums::PaymentMethodType::LocalBankRedirect => {
Ok(dirval!(BankRedirectType = LocalBankRedirect))
}
global_enums::PaymentMethodType::OnlineBankingThailand => {
Ok(dirval!(BankRedirectType = OnlineBankingThailand))
}
global_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)),
global_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)),
global_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)),
global_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)),
global_enums::PaymentMethodType::PagoEfectivo => {
Ok(dirval!(VoucherType = PagoEfectivo))
}
global_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)),
global_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)),
global_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)),
global_enums::PaymentMethodType::BcaBankTransfer => {
Ok(dirval!(BankTransferType = BcaBankTransfer))
}
global_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)),
global_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)),
global_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)),
global_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)),
global_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)),
global_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)),
global_enums::PaymentMethodType::LocalBankTransfer => {
Ok(dirval!(BankTransferType = LocalBankTransfer))
}
global_enums::PaymentMethodType::InstantBankTransfer => {
Ok(dirval!(BankTransferType = InstantBankTransfer))
}
global_enums::PaymentMethodType::InstantBankTransferFinland => {
Ok(dirval!(BankTransferType = InstantBankTransferFinland))
}
global_enums::PaymentMethodType::InstantBankTransferPoland => {
Ok(dirval!(BankTransferType = InstantBankTransferPoland))
}
global_enums::PaymentMethodType::PermataBankTransfer => {
Ok(dirval!(BankTransferType = PermataBankTransfer))
}
global_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)),
global_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)),
global_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)),
global_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)),
global_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)),
global_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)),
global_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)),
global_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)),
global_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)),
global_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)),
global_enums::PaymentMethodType::OpenBankingUk => {
Ok(dirval!(BankRedirectType = OpenBankingUk))
}
global_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)),
global_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
global_enums::PaymentMethodType::CardRedirect => {
Ok(dirval!(CardRedirectType = CardRedirect))
}
global_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
global_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)),
global_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
global_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
global_enums::PaymentMethodType::DirectCarrierBilling => {
Ok(dirval!(MobilePaymentType = DirectCarrierBilling))
}
global_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)),
global_enums::PaymentMethodType::IndonesianBankTransfer => {
Ok(dirval!(BankTransferType = IndonesianBankTransfer))
}
global_enums::PaymentMethodType::BhnCardNetwork => {
Ok(dirval!(GiftCardType = BhnCardNetwork))
}
}
}
}
| crates/euclid/src/frontend/dir/transformers.rs | euclid | full_file | 3,320 | null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct Authorize; | crates/hyperswitch_domain_models/src/router_flow_types/payments.rs | hyperswitch_domain_models | struct_definition | 5 | rust | Authorize | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.MobilePayRedirection
{
"type": "object"
} | ./hyperswitch/api-reference/v1/openapi_spec_v1.json | null | openapi_block | 22 | .json | null | null | null | null | null | openapi_spec | components | [
"schemas",
"MobilePayRedirection"
] | null | null | null | null |
pub struct CaptureResponseTransactionBody {
id: String,
status: BraintreePaymentStatus,
} | crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs | hyperswitch_connectors | struct_definition | 21 | rust | CaptureResponseTransactionBody | null | null | null | null | null | null | null | null | null | null | null |
impl api::RefundExecute for Chargebee {} | crates/hyperswitch_connectors/src/connectors/chargebee.rs | hyperswitch_connectors | impl_block | 10 | rust | null | Chargebee | api::RefundExecute for | impl api::RefundExecute for for Chargebee | null | null | null | null | null | null | null | null |
pub struct DwollaRefundsRequest {
#[serde(rename = "_links")]
links: DwollaPaymentLinks,
amount: DwollaAmount,
correlation_id: String,
} | crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs | hyperswitch_connectors | struct_definition | 38 | rust | DwollaRefundsRequest | null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorValidation for CtpMastercard {} | crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs | hyperswitch_connectors | impl_block | 9 | rust | null | CtpMastercard | ConnectorValidation for | impl ConnectorValidation for for CtpMastercard | null | null | null | null | null | null | null | null |
impl api::RefundSync for Stripebilling {} | crates/hyperswitch_connectors/src/connectors/stripebilling.rs | hyperswitch_connectors | impl_block | 10 | rust | null | Stripebilling | api::RefundSync for | impl api::RefundSync for for Stripebilling | null | null | null | null | null | null | null | null |
pub fn generate_authorization_value(&self) -> String {
let auth_id = format!(
"{}:{}",
self.get_client_id().expose(),
self.get_client_secret().expose(),
);
format!("Basic {}", consts::BASE64_ENGINE.encode(auth_id))
} | crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs | hyperswitch_connectors | function_signature | 60 | rust | null | null | null | null | generate_authorization_value | null | null | null | null | null | null | null |
File: crates/router/tests/connectors/trustpayments.rs
use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
use masking::Secret;
use router::types::{self, api, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct TrustpaymentsTest;
impl ConnectorActions for TrustpaymentsTest {}
impl utils::Connector for TrustpaymentsTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Trustpayments;
utils::construct_connector_data_old(
Box::new(Trustpayments::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.trustpayments
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"trustpayments".to_string()
}
}
static CONNECTOR: TrustpaymentsTest = TrustpaymentsTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| crates/router/tests/connectors/trustpayments.rs | router | full_file | 2,926 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl<M> Metadata for M where M: erased_serde::Serialize + Any + Send + Sync + fmt::Debug {} | crates/hyperswitch_constraint_graph/src/types.rs | hyperswitch_constraint_graph | impl_block | 25 | rust | null | M | Metadata for | impl Metadata for for M | null | null | null | null | null | null | null | null |
pub struct InsertResourceParams<'a> {
pub insertable: kv::Insertable,
pub reverse_lookups: Vec<String>,
pub key: PartitionKey<'a>,
// secondary key
pub identifier: String,
// type of resource Eg: "payment_attempt"
pub resource_type: &'static str,
} | crates/storage_impl/src/kv_router_store.rs | storage_impl | struct_definition | 69 | rust | InsertResourceParams | null | null | null | null | null | null | null | null | null | null | null |
File: crates/drainer/build.rs
fn main() {
#[cfg(feature = "vergen")]
router_env::vergen::generate_cargo_instructions();
}
| crates/drainer/build.rs | drainer | full_file | 34 | null | null | null | null | null | null | null | null | null | null | null | null | null |
/// After we get the access token, check if there was an error and if the flow should proceed further
/// Returns bool
/// true - Everything is well, continue with the flow
/// false - There was an error, cannot proceed further
pub fn update_router_data_with_access_token_result<F, Req, Res>(
add_access_token_result: &types::AddAccessTokenResult,
router_data: &mut types::RouterData<F, Req, Res>,
call_connector_action: &payments::CallConnectorAction,
) -> bool {
// Update router data with access token or error only if it will be calling connector
let should_update_router_data = matches!(
(
add_access_token_result.connector_supports_access_token,
call_connector_action
),
(true, payments::CallConnectorAction::Trigger)
);
if should_update_router_data {
match add_access_token_result.access_token_result.as_ref() {
Ok(access_token) => {
router_data.access_token.clone_from(access_token);
true
}
Err(connector_error) => {
router_data.response = Err(connector_error.clone());
false
}
}
} else {
true
}
} | crates/router/src/core/payments/access_token.rs | router | function_signature | 249 | rust | null | null | null | null | update_router_data_with_access_token_result | null | null | null | null | null | null | null |
impl api::ConnectorAccessToken for Zen {} | crates/hyperswitch_connectors/src/connectors/zen.rs | hyperswitch_connectors | impl_block | 8 | rust | null | Zen | api::ConnectorAccessToken for | impl api::ConnectorAccessToken for for Zen | null | null | null | null | null | null | null | null |
pub struct SupportedMsgExt {
pub id: String,
pub version: String,
} | crates/hyperswitch_connectors/src/connectors/unified_authentication_service/transformers.rs | hyperswitch_connectors | struct_definition | 19 | rust | SupportedMsgExt | null | null | null | null | null | null | null | null | null | null | null |
pub struct NetworkField {
#[serde(rename = "@fieldNumber")]
pub field_number: String,
#[serde(rename = "@fieldName", skip_serializing_if = "Option::is_none")]
pub field_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub field_value: Option<String>,
#[serde(default)]
#[serde(rename = "networkSubField")]
pub network_sub_fields: Vec<NetworkSubField>,
} | crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs | hyperswitch_connectors | struct_definition | 98 | rust | NetworkField | null | null | null | null | null | null | null | null | null | null | null |
pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_accounts_replica_pool();
// If either one of these are true we need to get master pool.
// 1. Only OLTP is enabled.
// 2. Both OLAP and OLTP is enabled.
// 3. Both OLAP and OLTP is disabled.
#[cfg(any(
all(not(feature = "olap"), feature = "oltp"),
all(feature = "olap", feature = "oltp"),
all(not(feature = "olap"), not(feature = "oltp"))
))]
let pool = store.get_accounts_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
} | crates/router/src/connection.rs | router | function_signature | 240 | rust | null | null | null | null | pg_accounts_connection_read | null | null | null | null | null | null | null |
pub struct PartnerConfigOverride {
pub partner_logo_url: String,
pub return_url: String,
} | crates/router/src/types/api/connector_onboarding/paypal.rs | router | struct_definition | 22 | rust | PartnerConfigOverride | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.ToggleBlocklistResponse
{
"type": "object",
"required": [
"blocklist_guard_status"
],
"properties": {
"blocklist_guard_status": {
"type": "string"
}
}
} | ./hyperswitch/api-reference/v1/openapi_spec_v1.json | null | openapi_block | 60 | .json | null | null | null | null | null | openapi_spec | components | [
"schemas",
"ToggleBlocklistResponse"
] | null | null | null | null |
pub struct Recon; | crates/router/src/routes/app.rs | router | struct_definition | 4 | rust | Recon | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentToken for Wellsfargo {} | crates/hyperswitch_connectors/src/connectors/wellsfargo.rs | hyperswitch_connectors | impl_block | 10 | rust | null | Wellsfargo | api::PaymentToken for | impl api::PaymentToken for for Wellsfargo | null | null | null | null | null | null | null | null |
pub struct SmartRetriedAmount; | crates/api_models/src/analytics/payment_intents.rs | api_models | struct_definition | 7 | rust | SmartRetriedAmount | null | null | null | null | null | null | null | null | null | null | null |
impl IncomingWebhook for Threedsecureio {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
} | crates/hyperswitch_connectors/src/connectors/threedsecureio.rs | hyperswitch_connectors | impl_block | 175 | rust | null | Threedsecureio | IncomingWebhook for | impl IncomingWebhook for for Threedsecureio | null | null | null | null | null | null | null | null |
pub async fn get_or_create_custom_recovery_intent(
data: api_models::payments::RecoveryPaymentsCreate,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<revenue_recovery::RecoveryPaymentIntent, errors::RevenueRecoveryError> {
let recovery_intent = Self(revenue_recovery::RevenueRecoveryInvoiceData::foreign_from(
data,
));
recovery_intent
.get_payment_intent(state, req_state, merchant_context, profile)
.await
.transpose()
.async_unwrap_or_else(|| async {
recovery_intent
.create_payment_intent(state, req_state, merchant_context, profile)
.await
})
.await
} | crates/router/src/core/webhooks/recovery_incoming.rs | router | function_signature | 171 | rust | null | null | null | null | get_or_create_custom_recovery_intent | null | null | null | null | null | null | null |
impl PMAuthConfigValidation<'_> {
async fn validate_pm_auth(&self, val: &pii::SecretSerdeValue) -> RouterResponse<()> {
let config = serde_json::from_value::<api_models::pm_auth::PaymentMethodAuthConfig>(
val.clone().expose(),
)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "invalid data received for payment method auth config".to_string(),
})
.attach_printable("Failed to deserialize Payment Method Auth config")?;
let all_mcas = self
.db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
self.key_manager_state,
self.merchant_id,
true,
self.key_store,
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: self.merchant_id.get_string_repr().to_owned(),
})?;
for conn_choice in config.enabled_payment_methods {
let pm_auth_mca = all_mcas
.iter()
.find(|mca| mca.get_id() == conn_choice.mca_id)
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method auth connector account not found".to_string(),
})?;
if &pm_auth_mca.profile_id != self.profile_id {
return Err(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method auth profile_id differs from connector profile_id"
.to_string(),
}
.into());
}
}
Ok(services::ApplicationResponse::StatusOk)
}
async fn validate_pm_auth_config(&self) -> RouterResult<()> {
if self.connector_type != &api_enums::ConnectorType::PaymentMethodAuth {
if let Some(val) = self.pm_auth_config.clone() {
self.validate_pm_auth(&val).await?;
}
}
Ok(())
}
} | crates/router/src/core/admin.rs | router | impl_block | 402 | rust | null | PMAuthConfigValidation | null | impl PMAuthConfigValidation | null | null | null | null | null | null | null | null |
impl api::RefundExecute for Fiserv {} | crates/hyperswitch_connectors/src/connectors/fiserv.rs | hyperswitch_connectors | impl_block | 11 | rust | null | Fiserv | api::RefundExecute for | impl api::RefundExecute for for Fiserv | null | null | null | null | null | null | null | null |
impl super::auth_events::filters::AuthEventFilterAnalytics for ClickhouseClient {} | crates/analytics/src/clickhouse.rs | analytics | impl_block | 17 | rust | null | ClickhouseClient | super::auth_events::filters::AuthEventFilterAnalytics for | impl super::auth_events::filters::AuthEventFilterAnalytics for for ClickhouseClient | null | null | null | null | null | null | null | null |
pub fn is_all_none(&self) -> bool {
self.payment_method.is_none()
&& self.currency.is_none()
&& self.status.is_none()
&& self.customer_email.is_none()
&& self.search_tags.is_none()
&& self.connector.is_none()
&& self.payment_method_type.is_none()
&& self.card_network.is_none()
&& self.card_last_4.is_none()
&& self.payment_id.is_none()
&& self.amount.is_none()
&& self.customer_id.is_none()
} | crates/api_models/src/analytics/search.rs | api_models | function_signature | 107 | rust | null | null | null | null | is_all_none | null | null | null | null | null | null | null |
### Features
- **connector:**
- [Worldpay] Use connector_request_reference_id as reference to the connector ([#2553](https://github.com/juspay/hyperswitch/pull/2553)) ([`9ea5830`](https://github.com/juspay/hyperswitch/commit/9ea5830befe333270f8f424753e1b46a439e79bb))
- [ProphetPay] Template generation ([#2610](https://github.com/juspay/hyperswitch/pull/2610)) ([`7e6207e`](https://github.com/juspay/hyperswitch/commit/7e6207e6ca98fe2af9a61e272735e9d2292d6a92))
- [Bambora] Use connector_response_reference_id as reference to the connector ([#2635](https://github.com/juspay/hyperswitch/pull/2635)) ([`a9b5dc9`](https://github.com/juspay/hyperswitch/commit/a9b5dc9ab767eb54a95bcebc4fd5a7b00dbf65f6))
- [Klarna] Add order id as the reference id to merchant ([#2614](https://github.com/juspay/hyperswitch/pull/2614)) ([`b7d5573`](https://github.com/juspay/hyperswitch/commit/b7d557367a3a5aca478ffd2087af8077bc4e7e2b))
### Bug Fixes
- Payment_method_data and description null during payment confirm ([#2618](https://github.com/juspay/hyperswitch/pull/2618)) ([`6765a1c`](https://github.com/juspay/hyperswitch/commit/6765a1c695493499d1907c56d05bdcd80a2fea93))
### Refactors
- **connector:**
- [Dlocal] Currency Unit Conversion ([#2615](https://github.com/juspay/hyperswitch/pull/2615)) ([`1f2fe51`](https://github.com/juspay/hyperswitch/commit/1f2fe5170ae318a8b1613f6f02538a36f30f0b3d))
- [Iatapay] remove default case handling ([#2587](https://github.com/juspay/hyperswitch/pull/2587)) ([`6494e8a`](https://github.com/juspay/hyperswitch/commit/6494e8a6e4a195ecc9ca5b2f6ac0a636f06b03f7))
- [noon] remove cancellation_reason ([#2627](https://github.com/juspay/hyperswitch/pull/2627)) ([`41b7742`](https://github.com/juspay/hyperswitch/commit/41b7742b5498bfa9ef32b9408ab2d9a7a43b01dc))
- [Forte] Remove Default Case Handling ([#2625](https://github.com/juspay/hyperswitch/pull/2625)) ([`418715b`](https://github.com/juspay/hyperswitch/commit/418715b816337bcaeee1aceeb911e6d329add2ad))
- [Dlocal] remove default case handling ([#2624](https://github.com/juspay/hyperswitch/pull/2624)) ([`1584313`](https://github.com/juspay/hyperswitch/commit/158431391d560be4a79160ccea7bf5feaa4b52db))
- Remove code related to temp locker ([#2640](https://github.com/juspay/hyperswitch/pull/2640)) ([`cc0b422`](https://github.com/juspay/hyperswitch/commit/cc0b42263257b6cf6c7f94350442a74d3c02750b))
- Add surcharge_applicable to payment_intent and remove surcharge_metadata from payment_attempt ([#2642](https://github.com/juspay/hyperswitch/pull/2642)) ([`e5fbaae`](https://github.com/juspay/hyperswitch/commit/e5fbaae0d4278681e5f589aa46c867e7904c4646))
### Testing
- **postman:** Update postman collection files ([`2593dd1`](https://github.com/juspay/hyperswitch/commit/2593dd17c30d7f327b54f3c386a9fd42ae8146ca))
### Miscellaneous Tasks
- **deps:** Bump rustix from 0.37.24 to 0.37.25 ([#2637](https://github.com/juspay/hyperswitch/pull/2637)) ([`67d0062`](https://github.com/juspay/hyperswitch/commit/67d006272158372a4b9ec65cbbe7b2ae8f35eb69))
### Build System / Dependencies
- **deps:** Use `async-bb8-diesel` from `crates.io` instead of git repository ([#2619](https://github.com/juspay/hyperswitch/pull/2619)) ([`14c0821`](https://github.com/juspay/hyperswitch/commit/14c0821b8085279072db3484a3b1bcdde0f7893b))
**Full Changelog:** [`v1.61.0...v1.62.0`](https://github.com/juspay/hyperswitch/compare/v1.61.0...v1.62.0)
- - -
## 1.61.0 (2023-10-18)
### Features
- **Connector:** [Paypal] add support for dispute webhooks for paypal connector ([#2353](https://github.com/juspay/hyperswitch/pull/2353)) ([`6cf8f05`](https://github.com/juspay/hyperswitch/commit/6cf8f0582cfa4f6a58c67a868cb67846970b3835))
- **apple_pay:** Add support for decrypted apple pay token for checkout ([#2628](https://github.com/juspay/hyperswitch/pull/2628)) ([`794dbc6`](https://github.com/juspay/hyperswitch/commit/794dbc6a766d12ff3cdf0b782abb4c48b8fa77d0))
- **connector:**
- [Aci] Update connector_response_reference_id with merchant reference ([#2551](https://github.com/juspay/hyperswitch/pull/2551)) ([`9e450b8`](https://github.com/juspay/hyperswitch/commit/9e450b81ca8bc4b1ddbbe2c1d732dbc58c61934e))
- [Bambora] use connector_request_reference_id ([#2518](https://github.com/juspay/hyperswitch/pull/2518)) ([`73e9391`](https://github.com/juspay/hyperswitch/commit/73e93910cd3bd668d721b15edb86240adc18f46b))
- [Tsys] Use connector_request_reference_id as reference to the connector ([#2631](https://github.com/juspay/hyperswitch/pull/2631)) ([`b145463`](https://github.com/juspay/hyperswitch/commit/b1454634259144d896716e5cef37d9b8491f55b9))
- **core:** Replace temp locker with redis ([#2594](https://github.com/juspay/hyperswitch/pull/2594)) ([`2edbd61`](https://github.com/juspay/hyperswitch/commit/2edbd6123512a6f2f4d51d5c2d1ed8b6ee502813))
- **events:** Add events for incoming API requests ([#2621](https://github.com/juspay/hyperswitch/pull/2621)) ([`7a76d6c`](https://github.com/juspay/hyperswitch/commit/7a76d6c01a0c6087c6429e58cc9dd6b4ea7fc0aa))
- **merchant_account:** Add merchant account list endpoint ([#2560](https://github.com/juspay/hyperswitch/pull/2560)) ([`a1472c6`](https://github.com/juspay/hyperswitch/commit/a1472c6b78afa819cbe026a7db1e0c2b9016715e))
- Update surcharge_amount and tax_amount in update_trackers of payment_confirm ([#2603](https://github.com/juspay/hyperswitch/pull/2603)) ([`2f9a355`](https://github.com/juspay/hyperswitch/commit/2f9a3557f63150bcd27e27c6510a799669706718))
### Bug Fixes
- **connector:**
- [Authorizedotnet]fix error deserialization incase of authentication failure ([#2600](https://github.com/juspay/hyperswitch/pull/2600)) ([`4859b7d`](https://github.com/juspay/hyperswitch/commit/4859b7da73125c2da72f4754863ff4485bebce29))
- [Paypal]fix error deserelization for source verification call ([#2611](https://github.com/juspay/hyperswitch/pull/2611)) ([`da77d13`](https://github.com/juspay/hyperswitch/commit/da77d1393b8f6ab658dd7f3c202dd6c7d15c0ebd))
- **payments:** Fix payment update enum being inserted into kv ([#2612](https://github.com/juspay/hyperswitch/pull/2612)) ([`9aa1c75`](https://github.com/juspay/hyperswitch/commit/9aa1c75eca24caa14af5f4801173cd59f76d7e57))
### Refactors
- **events:** Allow box dyn for event handler ([#2629](https://github.com/juspay/hyperswitch/pull/2629)) ([`01410bb`](https://github.com/juspay/hyperswitch/commit/01410bb9f233637e98f27ebe509e859c7dad2cf4))
- **payment_connector:** Allow connector label to be updated ([#2622](https://github.com/juspay/hyperswitch/pull/2622)) ([`c86ac9b`](https://github.com/juspay/hyperswitch/commit/c86ac9b1fe5388666463aa16c899427a2bf442fb))
- **router:** Remove unnecessary function from Refunds Validate Flow ([#2609](https://github.com/juspay/hyperswitch/pull/2609)) ([`3399328`](https://github.com/juspay/hyperswitch/commit/3399328ae7f525fb72e0751182cf32d0b2470594))
- Refactor connector auth type failure to 4xx ([#2616](https://github.com/juspay/hyperswitch/pull/2616)) ([`1dad745`](https://github.com/juspay/hyperswitch/commit/1dad7455c4ae8d26d52c44d90f5b8d815d85d205))
### Testing
- **postman:** Update postman collection files ([`d899025`](https://github.com/juspay/hyperswitch/commit/d89902507486b8b97011fb63ed0343f727255ca2))
### Documentation
- **postman:** Rewrite postman documentation to help devs develop tests for their features ([#2613](https://github.com/juspay/hyperswitch/pull/2613)) ([`1548ee6`](https://github.com/juspay/hyperswitch/commit/1548ee62b661200fcb9d439d16c072a66dbfa718))
### Miscellaneous Tasks
- **scripts:** Add connector script changes ([#2620](https://github.com/juspay/hyperswitch/pull/2620)) ([`373a10b`](https://github.com/juspay/hyperswitch/commit/373a10beffc7cddef6ff76f5c8fff91ca3618581))
**Full Changelog:** [`v1.60.0...v1.61.0`](https://github.com/juspay/hyperswitch/compare/v1.60.0...v1.61.0)
- - -
## 1.60.0 (2023-10-17)
### Features
- **compatibility:** Added support to connector txn id ([#2606](https://github.com/juspay/hyperswitch/pull/2606)) ([`82980a8`](https://github.com/juspay/hyperswitch/commit/82980a86ad7966c6645d26a4abec85c8c7e3bdad))
- **router:** Better UI payment link and order details product image and merchant config support ([#2583](https://github.com/juspay/hyperswitch/pull/2583)) ([`fdd9580`](https://github.com/juspay/hyperswitch/commit/fdd95800127bb79fe2a9eeca1b7e0e158b6d2783))
- Add updated_by to tracker tables ([#2604](https://github.com/juspay/hyperswitch/pull/2604)) ([`6a74e8c`](https://github.com/juspay/hyperswitch/commit/6a74e8cba9078529fd9662d29ac7b941a191fbf4))
### Bug Fixes
- Make push to drainer generic and add application metrics for KV ([#2563](https://github.com/juspay/hyperswitch/pull/2563)) ([`274a783`](https://github.com/juspay/hyperswitch/commit/274a78343e5e3de614cfb1476570b5c449ee0c1e))
### Refactors
- **connector:** [Nuvei] remove default case handling ([#2584](https://github.com/juspay/hyperswitch/pull/2584)) ([`3807601`](https://github.com/juspay/hyperswitch/commit/3807601ee1c140310abf7a7e6ee4b83d44de9558))
- **router:** Throw bad request error on applepay verification failure ([#2607](https://github.com/juspay/hyperswitch/pull/2607)) ([`cecea87`](https://github.com/juspay/hyperswitch/commit/cecea8718a48b4e896b2bafce0f909ef8d9a6e8a))
**Full Changelog:** [`v1.59.0...v1.60.0`](https://github.com/juspay/hyperswitch/compare/v1.59.0...v1.60.0)
- - -
## 1.59.0 (2023-10-16)
### Features
- **connector:**
- Add support for surcharge in trustpay ([#2581](https://github.com/juspay/hyperswitch/pull/2581)) ([`2d5d3b8`](https://github.com/juspay/hyperswitch/commit/2d5d3b8efbf782bf03e5f5ef1aa557d3dd3f5860))
- Add surcharge support in paypal connector ([#2568](https://github.com/juspay/hyperswitch/pull/2568)) ([`92ee1db`](https://github.com/juspay/hyperswitch/commit/92ee1db107ac41326ecfb31b4565664a29a4b80a))
- **events:** Add basic event handler to collect application events ([#2602](https://github.com/juspay/hyperswitch/pull/2602)) ([`5d88dbc`](https://github.com/juspay/hyperswitch/commit/5d88dbc92ce470c951717debe246e182b3fe5656))
### Refactors
- **connector:** [multisafepay] Remove Default Case Handling ([#2586](https://github.com/juspay/hyperswitch/pull/2586)) ([`7adc6a0`](https://github.com/juspay/hyperswitch/commit/7adc6a05b60fa9143260b2a7f623907647557621))
**Full Changelog:** [`v1.58.0...v1.59.0`](https://github.com/juspay/hyperswitch/compare/v1.58.0...v1.59.0)
- - -
## 1.58.0 (2023-10-15)
### Features
- **connector:**
- [HELCIM] Implement Cards for Helcim ([#2210](https://github.com/juspay/hyperswitch/pull/2210)) ([`b5feab6`](https://github.com/juspay/hyperswitch/commit/b5feab61d950921c75267ad88e944e7e2c4af3ca))
- [Paypal] use connector request reference id as reference for paypal ([#2577](https://github.com/juspay/hyperswitch/pull/2577)) ([`500405d`](https://github.com/juspay/hyperswitch/commit/500405d78938772e0e9f8e3ce4f930d782c670fa))
- [Airwallex] Currency Unit Conversion ([#2571](https://github.com/juspay/hyperswitch/pull/2571)) ([`8971b17`](https://github.com/juspay/hyperswitch/commit/8971b17b073315f869e3c843b0aee7644dcf6479))
- [Klarna] Use connector_request_reference_id as reference to connector ([#2494](https://github.com/juspay/hyperswitch/pull/2494)) ([`2609ef6`](https://github.com/juspay/hyperswitch/commit/2609ef6aeb17e1e89d8f98ff84a2c33b9704e6b2))
- [Dlocal] Use connector_response_reference_id as reference to merchant ([#2446](https://github.com/juspay/hyperswitch/pull/2446)) ([`f6677b8`](https://github.com/juspay/hyperswitch/commit/f6677b8e9300a75810a39de5b60243e34cf1d76c))
- **nexinets:** Use connector_request_reference_id as reference to the connector - Work In Progress ([#2515](https://github.com/juspay/hyperswitch/pull/2515)) ([`088dce0`](https://github.com/juspay/hyperswitch/commit/088dce076d8d8ff86769717368150e09d7d92593))
- **router:** Add Cancel Event in Webhooks and Mapping it in Stripe ([#2573](https://github.com/juspay/hyperswitch/pull/2573)) ([`92f7918`](https://github.com/juspay/hyperswitch/commit/92f7918e6f98460fb739d50b908ae33fda2f80b8))
### Refactors
- **connector:**
- [Worldline] Currency Unit Conversion ([#2569](https://github.com/juspay/hyperswitch/pull/2569)) ([`9f03a41`](https://github.com/juspay/hyperswitch/commit/9f03a4118ccdd6036d27074c9126a79d6e9b0495))
- [Authorizedotnet] Enhance currency Mapping with ConnectorCurrencyCommon Trait ([#2570](https://github.com/juspay/hyperswitch/pull/2570)) ([`d401975`](https://github.com/juspay/hyperswitch/commit/d4019751ff4acbd26abb2c32a600e8e6c55893f6))
- [noon] enhance response status mapping ([#2575](https://github.com/juspay/hyperswitch/pull/2575)) ([`053c79d`](https://github.com/juspay/hyperswitch/commit/053c79d248df0ff6ec702c3c301acc5654a1735a))
- **storage:** Update paymentintent object to provide a relation with attempts ([#2502](https://github.com/juspay/hyperswitch/pull/2502)) ([`fbf3c03`](https://github.com/juspay/hyperswitch/commit/fbf3c03d418242b1f5f1a15c69029023d0b25b4e))
### Testing
- **postman:** Update postman collection files ([`08141ab`](https://github.com/juspay/hyperswitch/commit/08141abb3e87504bb4fe54fdfea92e6c889d729a))
**Full Changelog:** [`v1.57.1+hotfix.1...v1.58.0`](https://github.com/juspay/hyperswitch/compare/v1.57.1+hotfix.1...v1.58.0)
- - -
## 1.57.1 (2023-10-12)
### Bug Fixes
- **connector:** Trigger Psync after redirection url ([#2422](https://github.com/juspay/hyperswitch/pull/2422)) ([`8029a89`](https://github.com/juspay/hyperswitch/commit/8029a895b2c27a1ac14a19aea23bbc06cc364809))
**Full Changelog:** [`v1.57.0...v1.57.1`](https://github.com/juspay/hyperswitch/compare/v1.57.0...v1.57.1)
- - -
## 1.57.0 (2023-10-12)
### Features
- **connector:**
- [Tsys] Use `connector_response_reference_id` as reference to the connector ([#2546](https://github.com/juspay/hyperswitch/pull/2546)) ([`550377a`](https://github.com/juspay/hyperswitch/commit/550377a6c3943d9fec4ca6a8be5a5f3aafe109ab))
- [Cybersource] Use connector_request_reference_id as reference to the connector ([#2512](https://github.com/juspay/hyperswitch/pull/2512)) ([`81cb8da`](https://github.com/juspay/hyperswitch/commit/81cb8da4d47fe2a75330d39c665bb259faa35b00))
- [Iatapay] use connector_response_reference_id as reference to connector ([#2524](https://github.com/juspay/hyperswitch/pull/2524)) ([`ef647b7`](https://github.com/juspay/hyperswitch/commit/ef647b7ab942707a06971b6545c81168f28cb94c))
- [ACI] Use connector_request_reference_id as reference to the connector ([#2549](https://github.com/juspay/hyperswitch/pull/2549)) ([`c2ad200`](https://github.com/juspay/hyperswitch/commit/c2ad2002c0e6d673f62ec4c72c8fd98b07a05c0b))
- **customers:** Add customer list endpoint ([#2564](https://github.com/juspay/hyperswitch/pull/2564)) ([`c26620e`](https://github.com/juspay/hyperswitch/commit/c26620e041add914abc60c6149787be62ea5985d))
- **router:**
- Add kv implementation for update address in update payments flow ([#2542](https://github.com/juspay/hyperswitch/pull/2542)) ([`9f446bc`](https://github.com/juspay/hyperswitch/commit/9f446bc1742c06a7fab3d92128ba4e7d3be80ea6))
- Add payment link support ([#2105](https://github.com/juspay/hyperswitch/pull/2105)) ([`642085d`](https://github.com/juspay/hyperswitch/commit/642085dc745f87b4edd2f7a744c31b8979b23cfa))
### Bug Fixes
- **connector:**
- [noon] sync with reference_id ([#2544](https://github.com/juspay/hyperswitch/pull/2544)) ([`9ef60e4`](https://github.com/juspay/hyperswitch/commit/9ef60e425d0cbe764ce66c65c8c09b1992cbe99f))
- [braintree] add 3ds redirection error mapping and metadata validation ([#2552](https://github.com/juspay/hyperswitch/pull/2552)) ([`28d02f9`](https://github.com/juspay/hyperswitch/commit/28d02f94c6d52d05b6f520e4d48ba88adf7be619))
- **router:** Add customer_id validation for `payment method create` flow ([#2543](https://github.com/juspay/hyperswitch/pull/2543)) ([`53d7604`](https://github.com/juspay/hyperswitch/commit/53d760460305e16f03d86f699acb035151dfdfad))
- Percentage float inconsistency problem and api models changes to support surcharge feature ([#2550](https://github.com/juspay/hyperswitch/pull/2550)) ([`1ee1184`](https://github.com/juspay/hyperswitch/commit/1ee11849d4a60afbf3d05103cb491a11e905b811))
- Consume profile_id throughout payouts flow ([#2501](https://github.com/juspay/hyperswitch/pull/2501)) ([`7eabd24`](https://github.com/juspay/hyperswitch/commit/7eabd24a4da6f82fd30f8a4be739962538654214))
- Parse allowed_payment_method_types only if there is some value p… ([#2161](https://github.com/juspay/hyperswitch/pull/2161)) ([`46f1419`](https://github.com/juspay/hyperswitch/commit/46f14191ab7e036539ef3fd58acd9376b6b6b63c))
### Refactors
- **connector:**
- [Worldpay] Currency Unit Conversion ([#2436](https://github.com/juspay/hyperswitch/pull/2436)) ([`b78109b`](https://github.com/juspay/hyperswitch/commit/b78109bc93433e0886b0b8656231899df84da8cf))
- [noon] use connector_request_reference_id for sync ([#2558](https://github.com/juspay/hyperswitch/pull/2558)) ([`0889a6e`](https://github.com/juspay/hyperswitch/commit/0889a6ed0691abeed7bba44e7024545abcc74aef))
- [noon] update and add recommended fields ([#2381](https://github.com/juspay/hyperswitch/pull/2381)) ([`751f16e`](https://github.com/juspay/hyperswitch/commit/751f16eaee254ab8f0068e2e9e81e3e4b7fe133f))
- **worldline:** Use `connector_request_reference_id` as reference to the connector ([#2498](https://github.com/juspay/hyperswitch/pull/2498)) ([`efa5320`](https://github.com/juspay/hyperswitch/commit/efa53204e8ab1ef1192bcdc07ed99306475badbc))
### Revert
- Fix(connector): [noon] sync with reference_id ([#2556](https://github.com/juspay/hyperswitch/pull/2556)) ([`13be4d3`](https://github.com/juspay/hyperswitch/commit/13be4d36eac3d1e17d8ad9b3f3ef8993547f548b))
**Full Changelog:** [`v1.56.0...v1.57.0`](https://github.com/juspay/hyperswitch/compare/v1.56.0...v1.57.0)
- - -
## 1.56.0 (2023-10-11)
### Features
- **connector:**
- [Volt] Template generation ([#2480](https://github.com/juspay/hyperswitch/pull/2480)) ([`ee321bb`](https://github.com/juspay/hyperswitch/commit/ee321bb82686559643d8c2725b0491997af717b2)) | CHANGELOG.md#chunk48 | null | doc_chunk | 8,147 | doc | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct SdkEventMetricRow {
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
pub time_bucket: Option<String>,
pub payment_method: Option<String>,
pub platform: Option<String>,
pub browser_name: Option<String>,
pub source: Option<String>,
pub component: Option<String>,
pub payment_experience: Option<String>,
} | crates/analytics/src/sdk_events/metrics.rs | analytics | struct_definition | 82 | rust | SdkEventMetricRow | null | null | null | null | null | null | null | null | null | null | null |
pub fn create_address(self, source: Address) -> Address {
Address {
city: self.city,
country: self.country,
line1: self.line1,
line2: self.line2,
line3: self.line3,
state: self.state,
zip: self.zip,
first_name: self.first_name,
last_name: self.last_name,
phone_number: self.phone_number,
country_code: self.country_code,
modified_at: self.modified_at,
updated_by: self.updated_by,
origin_zip: self.origin_zip,
..source
}
} | crates/diesel_models/src/address.rs | diesel_models | function_signature | 128 | rust | null | null | null | null | create_address | null | null | null | null | null | null | null |
pub struct Balance; | crates/hyperswitch_domain_models/src/router_flow_types/payments.rs | hyperswitch_domain_models | struct_definition | 4 | rust | Balance | null | null | null | null | null | null | null | null | null | null | null |
pub struct TrustlyData {
trustly: TrustlyDetails,
#[serde(rename = "type")]
payment_method_type: AirwallexPaymentType,
} | crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs | hyperswitch_connectors | struct_definition | 34 | rust | TrustlyData | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentVoid for Stripe {} | crates/hyperswitch_connectors/src/connectors/stripe.rs | hyperswitch_connectors | impl_block | 8 | rust | null | Stripe | api::PaymentVoid for | impl api::PaymentVoid for for Stripe | null | null | null | null | null | null | null | null |
impl CardInfoBuilder<CardInfoUpdate> {
fn set_updated_card_info(
self,
card_info: card_info_models::CardInfo,
) -> CardInfoBuilder<CardInfoResponse> {
CardInfoBuilder {
state: std::marker::PhantomData,
card_info: Some(card_info),
}
}
} | crates/router/src/core/cards_info.rs | router | impl_block | 70 | rust | null | CardInfoBuilder | null | impl CardInfoBuilder | null | null | null | null | null | null | null | null |
impl DecisionEngineSRSubLevelInputConfig {
pub fn update(&mut self, new_config: Self) {
if let Some(payment_method_type) = new_config.payment_method_type {
self.payment_method_type = Some(payment_method_type);
}
if let Some(payment_method) = new_config.payment_method {
self.payment_method = Some(payment_method);
}
if let Some(latency_threshold) = new_config.latency_threshold {
self.latency_threshold = Some(latency_threshold);
}
if let Some(bucket_size) = new_config.bucket_size {
self.bucket_size = Some(bucket_size);
}
if let Some(hedging_percent) = new_config.hedging_percent {
self.hedging_percent = Some(hedging_percent);
}
if let Some(lower_reset_factor) = new_config.lower_reset_factor {
self.lower_reset_factor = Some(lower_reset_factor);
}
if let Some(upper_reset_factor) = new_config.upper_reset_factor {
self.upper_reset_factor = Some(upper_reset_factor);
}
if let Some(gateway_extra_score) = new_config.gateway_extra_score {
self.gateway_extra_score
.as_mut()
.map(|score| score.extend(gateway_extra_score));
}
}
} | crates/api_models/src/open_router.rs | api_models | impl_block | 262 | rust | null | DecisionEngineSRSubLevelInputConfig | null | impl DecisionEngineSRSubLevelInputConfig | null | null | null | null | null | null | null | null |
pub struct ConsumerSettings {
pub disabled: bool,
pub consumer_group: String,
} | crates/scheduler/src/configs/settings.rs | scheduler | struct_definition | 19 | rust | ConsumerSettings | null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_dynamic_routing_volume_split(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<routing_types::ToggleDynamicRoutingPath>,
) -> impl Responder {
let flow = Flow::VolumeSplitOnRoutingType;
let payload = path.into_inner();
Box::pin(oss_api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, auth: auth::AuthenticationData, payload, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
routing::retrieve_dynamic_routing_volume_split(
state,
merchant_context,
payload.profile_id,
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuthProfileFromRoute {
profile_id: payload.profile_id,
required_permission: Permission::ProfileRoutingRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/routes/routing.rs | router | function_signature | 248 | rust | null | null | null | null | get_dynamic_routing_volume_split | null | null | null | null | null | null | null |
pub struct PaymentAttempt {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub net_amount: NetAmount,
pub currency: Option<storage_enums::Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<String>,
pub error_message: Option<String>,
pub offer_amount: Option<MinorUnit>,
pub payment_method_id: Option<String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub connector_transaction_id: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<String>,
pub browser_info: Option<serde_json::Value>,
pub error_code: Option<String>,
pub payment_token: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_data: Option<serde_json::Value>,
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
// providing a location to store mandate details intermediately for transaction
pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub multiple_capture_count: Option<i16>,
// reference to the payment at connector side
pub connector_response_reference_id: Option<String>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<id_type::AuthenticationId>,
pub mandate_data: Option<MandateDetails>,
pub payment_method_billing_address_id: Option<String>,
pub fingerprint_id: Option<String>,
pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<PrimitiveDateTime>,
pub card_discovery: Option<common_enums::CardDiscovery>,
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
pub issuer_error_code: Option<String>,
pub issuer_error_message: Option<String>,
/// merchant who owns the credentials of the processor, i.e. processor owner
pub processor_merchant_id: id_type::MerchantId,
/// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard))
pub created_by: Option<CreatedBy>,
pub setup_future_usage_applied: Option<storage_enums::FutureUsage>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub connector_request_reference_id: Option<String>,
pub debit_routing_savings: Option<MinorUnit>,
pub network_transaction_id: Option<String>,
} | crates/hyperswitch_domain_models/src/payments/payment_attempt.rs | hyperswitch_domain_models | struct_definition | 916 | rust | PaymentAttempt | null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentSync for Nomupay {} | crates/hyperswitch_connectors/src/connectors/nomupay.rs | hyperswitch_connectors | impl_block | 10 | rust | null | Nomupay | api::PaymentSync for | impl api::PaymentSync for for Nomupay | null | null | null | null | null | null | null | null |
OpenAPI Block Path: paths."/events/{merchant_id}/{event_id}/attempts"
{
"get": {
"tags": [
"Event"
],
"summary": "Events - Delivery Attempt List",
"description": "List all delivery attempts for the specified Event.",
"operationId": "List all delivery attempts for an Event",
"parameters": [
{
"name": "merchant_id",
"in": "path",
"description": "The unique identifier for the Merchant Account.",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "event_id",
"in": "path",
"description": "The unique identifier for the Event",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "List of delivery attempts retrieved successfully",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/EventRetrieveResponse"
}
}
}
}
}
},
"security": [
{
"admin_api_key": []
}
]
}
} | ./hyperswitch/api-reference/v1/openapi_spec_v1.json | null | openapi_block | 283 | .json | null | null | null | null | null | openapi_spec | paths | [
"/events/{merchant_id}/{event_id}/attempts"
] | null | null | null | null |
impl AuthInfo for AuthenticationData {
fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
Some(self.merchant_account.get_id())
}
} | crates/router/src/services/authentication.rs | router | impl_block | 38 | rust | null | AuthenticationData | AuthInfo for | impl AuthInfo for for AuthenticationData | null | null | null | null | null | null | null | null |
impl ConnectorSpecifications for Opayo {} | crates/hyperswitch_connectors/src/connectors/opayo.rs | hyperswitch_connectors | impl_block | 7 | rust | null | Opayo | ConnectorSpecifications for | impl ConnectorSpecifications for for Opayo | null | null | null | null | null | null | null | null |
File: crates/currency_conversion/src/types.rs
Public functions: 5
Public structs: 2
use std::collections::HashMap;
use common_enums::Currency;
use rust_decimal::Decimal;
use rusty_money::iso;
use crate::error::CurrencyConversionError;
/// Cached currency store of base currency
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExchangeRates {
pub base_currency: Currency,
pub conversion: HashMap<Currency, CurrencyFactors>,
}
/// Stores the multiplicative factor for conversion between currency to base and vice versa
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CurrencyFactors {
/// The factor that will be multiplied to provide Currency output
pub to_factor: Decimal,
/// The factor that will be multiplied to provide for the base output
pub from_factor: Decimal,
}
impl CurrencyFactors {
pub fn new(to_factor: Decimal, from_factor: Decimal) -> Self {
Self {
to_factor,
from_factor,
}
}
}
impl ExchangeRates {
pub fn new(base_currency: Currency, conversion: HashMap<Currency, CurrencyFactors>) -> Self {
Self {
base_currency,
conversion,
}
}
/// The flow here is from_currency -> base_currency -> to_currency
/// from to_currency -> base currency
pub fn forward_conversion(
&self,
amt: Decimal,
from_currency: Currency,
) -> Result<Decimal, CurrencyConversionError> {
let from_factor = self
.conversion
.get(&from_currency)
.ok_or_else(|| {
CurrencyConversionError::ConversionNotSupported(from_currency.to_string())
})?
.from_factor;
amt.checked_mul(from_factor)
.ok_or(CurrencyConversionError::DecimalMultiplicationFailed)
}
/// from base_currency -> to_currency
pub fn backward_conversion(
&self,
amt: Decimal,
to_currency: Currency,
) -> Result<Decimal, CurrencyConversionError> {
let to_factor = self
.conversion
.get(&to_currency)
.ok_or_else(|| {
CurrencyConversionError::ConversionNotSupported(to_currency.to_string())
})?
.to_factor;
amt.checked_mul(to_factor)
.ok_or(CurrencyConversionError::DecimalMultiplicationFailed)
}
}
pub fn currency_match(currency: Currency) -> &'static iso::Currency {
match currency {
Currency::AED => iso::AED,
Currency::AFN => iso::AFN,
Currency::ALL => iso::ALL,
Currency::AMD => iso::AMD,
Currency::ANG => iso::ANG,
Currency::AOA => iso::AOA,
Currency::ARS => iso::ARS,
Currency::AUD => iso::AUD,
Currency::AWG => iso::AWG,
Currency::AZN => iso::AZN,
Currency::BAM => iso::BAM,
Currency::BBD => iso::BBD,
Currency::BDT => iso::BDT,
Currency::BGN => iso::BGN,
Currency::BHD => iso::BHD,
Currency::BIF => iso::BIF,
Currency::BMD => iso::BMD,
Currency::BND => iso::BND,
Currency::BOB => iso::BOB,
Currency::BRL => iso::BRL,
Currency::BSD => iso::BSD,
Currency::BTN => iso::BTN,
Currency::BWP => iso::BWP,
Currency::BYN => iso::BYN,
Currency::BZD => iso::BZD,
Currency::CAD => iso::CAD,
Currency::CDF => iso::CDF,
Currency::CHF => iso::CHF,
Currency::CLF => iso::CLF,
Currency::CLP => iso::CLP,
Currency::CNY => iso::CNY,
Currency::COP => iso::COP,
Currency::CRC => iso::CRC,
Currency::CUC => iso::CUC,
Currency::CUP => iso::CUP,
Currency::CVE => iso::CVE,
Currency::CZK => iso::CZK,
Currency::DJF => iso::DJF,
Currency::DKK => iso::DKK,
Currency::DOP => iso::DOP,
Currency::DZD => iso::DZD,
Currency::EGP => iso::EGP,
Currency::ERN => iso::ERN,
Currency::ETB => iso::ETB,
Currency::EUR => iso::EUR,
Currency::FJD => iso::FJD,
Currency::FKP => iso::FKP,
Currency::GBP => iso::GBP,
Currency::GEL => iso::GEL,
Currency::GHS => iso::GHS,
Currency::GIP => iso::GIP,
Currency::GMD => iso::GMD,
Currency::GNF => iso::GNF,
Currency::GTQ => iso::GTQ,
Currency::GYD => iso::GYD,
Currency::HKD => iso::HKD,
Currency::HNL => iso::HNL,
Currency::HRK => iso::HRK,
Currency::HTG => iso::HTG,
Currency::HUF => iso::HUF,
Currency::IDR => iso::IDR,
Currency::ILS => iso::ILS,
Currency::INR => iso::INR,
Currency::IQD => iso::IQD,
Currency::IRR => iso::IRR,
Currency::ISK => iso::ISK,
Currency::JMD => iso::JMD,
Currency::JOD => iso::JOD,
Currency::JPY => iso::JPY,
Currency::KES => iso::KES,
Currency::KGS => iso::KGS,
Currency::KHR => iso::KHR,
Currency::KMF => iso::KMF,
Currency::KPW => iso::KPW,
Currency::KRW => iso::KRW,
Currency::KWD => iso::KWD,
Currency::KYD => iso::KYD,
Currency::KZT => iso::KZT,
Currency::LAK => iso::LAK,
Currency::LBP => iso::LBP,
Currency::LKR => iso::LKR,
Currency::LRD => iso::LRD,
Currency::LSL => iso::LSL,
Currency::LYD => iso::LYD,
Currency::MAD => iso::MAD,
Currency::MDL => iso::MDL,
Currency::MGA => iso::MGA,
Currency::MKD => iso::MKD,
Currency::MMK => iso::MMK,
Currency::MNT => iso::MNT,
Currency::MOP => iso::MOP,
Currency::MRU => iso::MRU,
Currency::MUR => iso::MUR,
Currency::MVR => iso::MVR,
Currency::MWK => iso::MWK,
Currency::MXN => iso::MXN,
Currency::MYR => iso::MYR,
Currency::MZN => iso::MZN,
Currency::NAD => iso::NAD,
Currency::NGN => iso::NGN,
Currency::NIO => iso::NIO,
Currency::NOK => iso::NOK,
Currency::NPR => iso::NPR,
Currency::NZD => iso::NZD,
Currency::OMR => iso::OMR,
Currency::PAB => iso::PAB,
Currency::PEN => iso::PEN,
Currency::PGK => iso::PGK,
Currency::PHP => iso::PHP,
Currency::PKR => iso::PKR,
Currency::PLN => iso::PLN,
Currency::PYG => iso::PYG,
Currency::QAR => iso::QAR,
Currency::RON => iso::RON,
Currency::RSD => iso::RSD,
Currency::RUB => iso::RUB,
Currency::RWF => iso::RWF,
Currency::SAR => iso::SAR,
Currency::SBD => iso::SBD,
Currency::SCR => iso::SCR,
Currency::SDG => iso::SDG,
Currency::SEK => iso::SEK,
Currency::SGD => iso::SGD,
Currency::SHP => iso::SHP,
Currency::SLE => iso::SLE,
Currency::SLL => iso::SLL,
Currency::SOS => iso::SOS,
Currency::SRD => iso::SRD,
Currency::SSP => iso::SSP,
Currency::STD => iso::STD,
Currency::STN => iso::STN,
Currency::SVC => iso::SVC,
Currency::SYP => iso::SYP,
Currency::SZL => iso::SZL,
Currency::THB => iso::THB,
Currency::TJS => iso::TJS,
Currency::TND => iso::TND,
Currency::TMT => iso::TMT,
Currency::TOP => iso::TOP,
Currency::TTD => iso::TTD,
Currency::TRY => iso::TRY,
Currency::TWD => iso::TWD,
Currency::TZS => iso::TZS,
Currency::UAH => iso::UAH,
Currency::UGX => iso::UGX,
Currency::USD => iso::USD,
Currency::UYU => iso::UYU,
Currency::UZS => iso::UZS,
Currency::VES => iso::VES,
Currency::VND => iso::VND,
Currency::VUV => iso::VUV,
Currency::WST => iso::WST,
Currency::XAF => iso::XAF,
Currency::XCD => iso::XCD,
Currency::XOF => iso::XOF,
Currency::XPF => iso::XPF,
Currency::YER => iso::YER,
Currency::ZAR => iso::ZAR,
Currency::ZMW => iso::ZMW,
Currency::ZWL => iso::ZWL,
}
}
| crates/currency_conversion/src/types.rs | currency_conversion | full_file | 2,238 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl Recurly {
pub fn new() -> &'static Self {
&Self {}
}
fn get_signature_elements_from_header(
headers: &actix_web::http::header::HeaderMap,
) -> CustomResult<Vec<Vec<u8>>, errors::ConnectorError> {
let security_header = headers
.get("recurly-signature")
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
let security_header_str = security_header
.to_str()
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let header_parts: Vec<Vec<u8>> = security_header_str
.split(',')
.map(|part| part.trim().as_bytes().to_vec())
.collect();
Ok(header_parts)
}
} | crates/hyperswitch_connectors/src/connectors/recurly.rs | hyperswitch_connectors | impl_block | 164 | rust | null | Recurly | null | impl Recurly | null | null | null | null | null | null | null | null |
pub struct ErrorMessage {
pub error_code: String,
pub error_text: String,
} | crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs | hyperswitch_connectors | struct_definition | 19 | rust | ErrorMessage | null | null | null | null | null | null | null | null | null | null | null |
impl api::Payment for Payload {} | crates/hyperswitch_connectors/src/connectors/payload.rs | hyperswitch_connectors | impl_block | 7 | rust | null | Payload | api::Payment for | impl api::Payment for for Payload | null | null | null | null | null | null | null | null |
pub async fn update_payouts_and_payout_attempt(
payout_data: &mut PayoutData,
merchant_context: &domain::MerchantContext,
req: &payouts::PayoutCreateRequest,
state: &SessionState,
) -> CustomResult<(), errors::ApiErrorResponse> {
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
let payout_id = payout_attempt.payout_id.clone();
// Verify update feasibility
if is_payout_terminal_state(status) || is_payout_initiated(status) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {} cannot be updated for status {status}",
payout_id.get_string_repr()
),
}));
}
// Fetch customer details from request and create new or else use existing customer that was attached
let customer = get_customer_details_from_request(req);
let customer_id = if customer.customer_id.is_some()
|| customer.name.is_some()
|| customer.email.is_some()
|| customer.phone.is_some()
|| customer.phone_country_code.is_some()
{
payout_data.customer_details =
get_or_create_customer_details(state, &customer, merchant_context).await?;
payout_data
.customer_details
.as_ref()
.map(|customer| customer.customer_id.clone())
} else {
payout_data.payouts.customer_id.clone()
};
let (billing_address, address_id) = resolve_billing_address_for_payout(
state,
req.billing.as_ref(),
payout_data.payouts.address_id.as_ref(),
payout_data.payment_method.as_ref(),
merchant_context,
customer_id.as_ref(),
&payout_id,
)
.await?;
// Update payout state with resolved billing address
payout_data.billing_address = billing_address;
// Update DB with new data
let payouts = payout_data.payouts.to_owned();
let amount = MinorUnit::from(req.amount.unwrap_or(payouts.amount.into()));
let updated_payouts = storage::PayoutsUpdate::Update {
amount,
destination_currency: req
.currency
.to_owned()
.unwrap_or(payouts.destination_currency),
source_currency: req.currency.to_owned().unwrap_or(payouts.source_currency),
description: req
.description
.to_owned()
.clone()
.or(payouts.description.clone()),
recurring: req.recurring.to_owned().unwrap_or(payouts.recurring),
auto_fulfill: req.auto_fulfill.to_owned().unwrap_or(payouts.auto_fulfill),
return_url: req
.return_url
.to_owned()
.clone()
.or(payouts.return_url.clone()),
entity_type: req.entity_type.to_owned().unwrap_or(payouts.entity_type),
metadata: req.metadata.clone().or(payouts.metadata.clone()),
status: Some(status),
profile_id: Some(payout_attempt.profile_id.clone()),
confirm: req.confirm.to_owned(),
payout_type: req
.payout_type
.to_owned()
.or(payouts.payout_type.to_owned()),
address_id: address_id.clone(),
customer_id: customer_id.clone(),
};
let db = &*state.store;
payout_data.payouts = db
.update_payout(
&payouts,
updated_payouts,
&payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts")?;
let updated_business_country =
payout_attempt
.business_country
.map_or(req.business_country.to_owned(), |c| {
req.business_country
.to_owned()
.and_then(|nc| if nc != c { Some(nc) } else { None })
});
let updated_business_label =
payout_attempt
.business_label
.map_or(req.business_label.to_owned(), |l| {
req.business_label
.to_owned()
.and_then(|nl| if nl != l { Some(nl) } else { None })
});
if updated_business_country.is_some()
|| updated_business_label.is_some()
|| customer_id.is_some()
|| address_id.is_some()
{
let payout_attempt = &payout_data.payout_attempt;
let updated_payout_attempt = storage::PayoutAttemptUpdate::BusinessUpdate {
business_country: updated_business_country,
business_label: updated_business_label,
address_id,
customer_id,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt")?;
}
Ok(())
} | crates/router/src/core/payouts/helpers.rs | router | function_signature | 1,062 | rust | null | null | null | null | update_payouts_and_payout_attempt | null | null | null | null | null | null | null |
File: crates/analytics/src/disputes/metrics/total_amount_disputed.rs
use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct TotalAmountDisputed {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for TotalAmountDisputed
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
for dim in dimensions {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Sum {
field: "dispute_amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder.add_group_by_clause(dim).switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.add_filter_clause("dispute_status", "dispute_won")
.switch()?;
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| crates/analytics/src/disputes/metrics/total_amount_disputed.rs | analytics | full_file | 847 | null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::MandateSetup for Datatrans {} | crates/hyperswitch_connectors/src/connectors/datatrans.rs | hyperswitch_connectors | impl_block | 12 | rust | null | Datatrans | api::MandateSetup for | impl api::MandateSetup for for Datatrans | null | null | null | null | null | null | null | null |
impl api::PaymentToken for Tokenio {} | crates/hyperswitch_connectors/src/connectors/tokenio.rs | hyperswitch_connectors | impl_block | 9 | rust | null | Tokenio | api::PaymentToken for | impl api::PaymentToken for for Tokenio | null | null | null | null | null | null | null | null |
pub async fn customer_update(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
form_payload: web::Bytes,
) -> HttpResponse {
let payload: types::CustomerUpdateRequest = match qs_config.deserialize_bytes(&form_payload) {
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
let customer_id = path.into_inner().clone();
let request = customer_types::CustomerUpdateRequest::from(payload);
let request_internal = customer_types::CustomerUpdateRequestInternal {
customer_id,
request,
};
let flow = Flow::CustomersUpdate;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::CustomerUpdateResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
request_internal,
|state, auth: auth::AuthenticationData, request_internal, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
customers::update_customer(state, merchant_context, request_internal)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
} | crates/router/src/compatibility/stripe/customers.rs | router | function_signature | 342 | rust | null | null | null | null | customer_update | null | 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.