repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/disputes/transformers.rs | crates/router/src/core/disputes/transformers.rs | use api_models::disputes::EvidenceType;
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use crate::{
core::{errors, files::helpers::retrieve_file_and_provider_file_id_from_file_id},
routes::SessionState,
types::{
api::{self, DisputeEvidence},
domain,
transformers::ForeignFrom,
SubmitEvidenceRequestData,
},
};
pub async fn get_evidence_request_data(
state: &SessionState,
platform: &domain::Platform,
evidence_request: api_models::disputes::SubmitEvidenceRequest,
dispute: &diesel_models::dispute::Dispute,
) -> CustomResult<SubmitEvidenceRequestData, errors::ApiErrorResponse> {
let cancellation_policy_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.cancellation_policy,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let customer_communication_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.customer_communication,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let customer_sifnature_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.customer_signature,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let receipt_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.receipt,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let refund_policy_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.refund_policy,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let service_documentation_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.service_documentation,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let shipping_documentation_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.shipping_documentation,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let invoice_showing_distinct_transactions_file_info =
retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.invoice_showing_distinct_transactions,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let recurring_transaction_agreement_file_info =
retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.recurring_transaction_agreement,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
let uncategorized_file_info = retrieve_file_and_provider_file_id_from_file_id(
state,
evidence_request.uncategorized_file,
None,
platform,
api::FileDataRequired::NotRequired,
)
.await?;
Ok(SubmitEvidenceRequestData {
dispute_id: dispute.dispute_id.clone(),
dispute_status: dispute.dispute_status,
connector_dispute_id: dispute.connector_dispute_id.clone(),
access_activity_log: evidence_request.access_activity_log,
billing_address: evidence_request.billing_address,
cancellation_policy: cancellation_policy_file_info.file_data,
cancellation_policy_provider_file_id: cancellation_policy_file_info.provider_file_id,
cancellation_policy_disclosure: evidence_request.cancellation_policy_disclosure,
cancellation_rebuttal: evidence_request.cancellation_rebuttal,
customer_communication: customer_communication_file_info.file_data,
customer_communication_provider_file_id: customer_communication_file_info.provider_file_id,
customer_email_address: evidence_request.customer_email_address,
customer_name: evidence_request.customer_name,
customer_purchase_ip: evidence_request.customer_purchase_ip,
customer_signature: customer_sifnature_file_info.file_data,
customer_signature_provider_file_id: customer_sifnature_file_info.provider_file_id,
product_description: evidence_request.product_description,
receipt: receipt_file_info.file_data,
receipt_provider_file_id: receipt_file_info.provider_file_id,
refund_policy: refund_policy_file_info.file_data,
refund_policy_provider_file_id: refund_policy_file_info.provider_file_id,
refund_policy_disclosure: evidence_request.refund_policy_disclosure,
refund_refusal_explanation: evidence_request.refund_refusal_explanation,
service_date: evidence_request.service_date,
service_documentation: service_documentation_file_info.file_data,
service_documentation_provider_file_id: service_documentation_file_info.provider_file_id,
shipping_address: evidence_request.shipping_address,
shipping_carrier: evidence_request.shipping_carrier,
shipping_date: evidence_request.shipping_date,
shipping_documentation: shipping_documentation_file_info.file_data,
shipping_documentation_provider_file_id: shipping_documentation_file_info.provider_file_id,
shipping_tracking_number: evidence_request.shipping_tracking_number,
invoice_showing_distinct_transactions: invoice_showing_distinct_transactions_file_info
.file_data,
invoice_showing_distinct_transactions_provider_file_id:
invoice_showing_distinct_transactions_file_info.provider_file_id,
recurring_transaction_agreement: recurring_transaction_agreement_file_info.file_data,
recurring_transaction_agreement_provider_file_id: recurring_transaction_agreement_file_info
.provider_file_id,
uncategorized_file: uncategorized_file_info.file_data,
uncategorized_file_provider_file_id: uncategorized_file_info.provider_file_id,
uncategorized_text: evidence_request.uncategorized_text,
cancellation_policy_file_type: cancellation_policy_file_info.file_type,
customer_communication_file_type: customer_communication_file_info.file_type,
customer_signature_file_type: customer_sifnature_file_info.file_type,
receipt_file_type: receipt_file_info.file_type,
refund_policy_file_type: refund_policy_file_info.file_type,
service_documentation_file_type: service_documentation_file_info.file_type,
shipping_documentation_file_type: shipping_documentation_file_info.file_type,
invoice_showing_distinct_transactions_file_type:
invoice_showing_distinct_transactions_file_info.file_type,
recurring_transaction_agreement_file_type: recurring_transaction_agreement_file_info
.file_type,
uncategorized_file_type: uncategorized_file_info.file_type,
})
}
pub fn update_dispute_evidence(
dispute_evidence: DisputeEvidence,
evidence_type: api::EvidenceType,
file_id: String,
) -> DisputeEvidence {
match evidence_type {
api::EvidenceType::CancellationPolicy => DisputeEvidence {
cancellation_policy: Some(file_id),
..dispute_evidence
},
api::EvidenceType::CustomerCommunication => DisputeEvidence {
customer_communication: Some(file_id),
..dispute_evidence
},
api::EvidenceType::CustomerSignature => DisputeEvidence {
customer_signature: Some(file_id),
..dispute_evidence
},
api::EvidenceType::Receipt => DisputeEvidence {
receipt: Some(file_id),
..dispute_evidence
},
api::EvidenceType::RefundPolicy => DisputeEvidence {
refund_policy: Some(file_id),
..dispute_evidence
},
api::EvidenceType::ServiceDocumentation => DisputeEvidence {
service_documentation: Some(file_id),
..dispute_evidence
},
api::EvidenceType::ShippingDocumentation => DisputeEvidence {
shipping_documentation: Some(file_id),
..dispute_evidence
},
api::EvidenceType::InvoiceShowingDistinctTransactions => DisputeEvidence {
invoice_showing_distinct_transactions: Some(file_id),
..dispute_evidence
},
api::EvidenceType::RecurringTransactionAgreement => DisputeEvidence {
recurring_transaction_agreement: Some(file_id),
..dispute_evidence
},
api::EvidenceType::UncategorizedFile => DisputeEvidence {
uncategorized_file: Some(file_id),
..dispute_evidence
},
}
}
pub async fn get_dispute_evidence_block(
state: &SessionState,
platform: &domain::Platform,
evidence_type: EvidenceType,
file_id: String,
) -> CustomResult<api_models::disputes::DisputeEvidenceBlock, errors::ApiErrorResponse> {
let file_metadata = state
.store
.find_file_metadata_by_merchant_id_file_id(
platform.get_processor().get_account().get_id(),
&file_id,
)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)
.attach_printable("Unable to retrieve file_metadata")?;
let file_metadata_response =
api_models::files::FileMetadataResponse::foreign_from(file_metadata);
Ok(api_models::disputes::DisputeEvidenceBlock {
evidence_type,
file_metadata_response,
})
}
pub fn delete_evidence_file(
dispute_evidence: DisputeEvidence,
evidence_type: EvidenceType,
) -> DisputeEvidence {
match evidence_type {
EvidenceType::CancellationPolicy => DisputeEvidence {
cancellation_policy: None,
..dispute_evidence
},
EvidenceType::CustomerCommunication => DisputeEvidence {
customer_communication: None,
..dispute_evidence
},
EvidenceType::CustomerSignature => DisputeEvidence {
customer_signature: None,
..dispute_evidence
},
EvidenceType::Receipt => DisputeEvidence {
receipt: None,
..dispute_evidence
},
EvidenceType::RefundPolicy => DisputeEvidence {
refund_policy: None,
..dispute_evidence
},
EvidenceType::ServiceDocumentation => DisputeEvidence {
service_documentation: None,
..dispute_evidence
},
EvidenceType::ShippingDocumentation => DisputeEvidence {
shipping_documentation: None,
..dispute_evidence
},
EvidenceType::InvoiceShowingDistinctTransactions => DisputeEvidence {
invoice_showing_distinct_transactions: None,
..dispute_evidence
},
EvidenceType::RecurringTransactionAgreement => DisputeEvidence {
recurring_transaction_agreement: None,
..dispute_evidence
},
EvidenceType::UncategorizedFile => DisputeEvidence {
uncategorized_file: None,
..dispute_evidence
},
}
}
pub async fn get_dispute_evidence_vec(
state: &SessionState,
platform: domain::Platform,
dispute_evidence: DisputeEvidence,
) -> CustomResult<Vec<api_models::disputes::DisputeEvidenceBlock>, errors::ApiErrorResponse> {
let mut dispute_evidence_blocks: Vec<api_models::disputes::DisputeEvidenceBlock> = vec![];
if let Some(cancellation_policy_block) = dispute_evidence.cancellation_policy {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::CancellationPolicy,
cancellation_policy_block,
)
.await?,
)
}
if let Some(customer_communication_block) = dispute_evidence.customer_communication {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::CustomerCommunication,
customer_communication_block,
)
.await?,
)
}
if let Some(customer_signature_block) = dispute_evidence.customer_signature {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::CustomerSignature,
customer_signature_block,
)
.await?,
)
}
if let Some(receipt_block) = dispute_evidence.receipt {
dispute_evidence_blocks.push(
get_dispute_evidence_block(state, &platform, EvidenceType::Receipt, receipt_block)
.await?,
)
}
if let Some(refund_policy_block) = dispute_evidence.refund_policy {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::RefundPolicy,
refund_policy_block,
)
.await?,
)
}
if let Some(service_documentation_block) = dispute_evidence.service_documentation {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::ServiceDocumentation,
service_documentation_block,
)
.await?,
)
}
if let Some(shipping_documentation_block) = dispute_evidence.shipping_documentation {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::ShippingDocumentation,
shipping_documentation_block,
)
.await?,
)
}
if let Some(invoice_showing_distinct_transactions_block) =
dispute_evidence.invoice_showing_distinct_transactions
{
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::InvoiceShowingDistinctTransactions,
invoice_showing_distinct_transactions_block,
)
.await?,
)
}
if let Some(recurring_transaction_agreement_block) =
dispute_evidence.recurring_transaction_agreement
{
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::RecurringTransactionAgreement,
recurring_transaction_agreement_block,
)
.await?,
)
}
if let Some(uncategorized_file_block) = dispute_evidence.uncategorized_file {
dispute_evidence_blocks.push(
get_dispute_evidence_block(
state,
&platform,
EvidenceType::UncategorizedFile,
uncategorized_file_block,
)
.await?,
)
}
Ok(dispute_evidence_blocks)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/flows.rs | crates/router/src/core/fraud_check/flows.rs | pub mod checkout_flow;
pub mod fulfillment_flow;
pub mod record_return;
pub mod sale_flow;
pub mod transaction_flow;
use async_trait::async_trait;
use crate::{
core::{
errors::RouterResult,
payments::{self, flows::ConstructFlowSpecificData},
},
routes::SessionState,
services,
types::{
api::{Connector, FraudCheckConnectorData},
domain,
fraud_check::FraudCheckResponseData,
},
};
#[async_trait]
pub trait FeatureFrm<F, T> {
async fn decide_frm_flows<'a>(
self,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
platform: &domain::Platform,
) -> RouterResult<Self>
where
Self: Sized,
F: Clone,
dyn Connector: services::ConnectorIntegration<F, T, FraudCheckResponseData>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/types.rs | crates/router/src/core/fraud_check/types.rs | use api_models::{
enums as api_enums,
enums::{PaymentMethod, PaymentMethodType},
payments::Amount,
refunds::RefundResponse,
};
use common_enums::FrmSuggestion;
use common_utils::pii::SecretSerdeValue;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
pub use hyperswitch_domain_models::{
router_request_types::fraud_check::{
Address, Destination, FrmFulfillmentRequest, FulfillmentStatus, Fulfillments, Product,
},
types::OrderDetailsWithAmount,
};
use masking::Serialize;
use serde::Deserialize;
use utoipa::ToSchema;
use super::operation::BoxedFraudCheckOperation;
use crate::types::{
domain::MerchantAccount,
storage::{enums as storage_enums, fraud_check::FraudCheck},
PaymentAddress,
};
#[derive(Clone, Default, Debug)]
pub struct PaymentIntentCore {
pub payment_id: common_utils::id_type::PaymentId,
}
#[derive(Clone, Debug)]
pub struct PaymentAttemptCore {
pub attempt_id: String,
pub payment_details: Option<PaymentDetails>,
pub amount: Amount,
}
#[derive(Clone, Debug, Serialize)]
pub struct PaymentDetails {
pub amount: i64,
pub currency: Option<storage_enums::Currency>,
pub payment_method: Option<PaymentMethod>,
pub payment_method_type: Option<PaymentMethodType>,
pub refund_transaction_id: Option<String>,
}
#[derive(Clone, Default, Debug)]
pub struct FrmMerchantAccount {
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Clone, Debug)]
pub struct FrmData {
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub merchant_account: MerchantAccount,
pub fraud_check: FraudCheck,
pub address: PaymentAddress,
pub connector_details: ConnectorDetailsCore,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub refund: Option<RefundResponse>,
pub frm_metadata: Option<SecretSerdeValue>,
}
#[derive(Debug)]
pub struct FrmInfo<F, D> {
pub fraud_check_operation: BoxedFraudCheckOperation<F, D>,
pub frm_data: Option<FrmData>,
pub suggested_action: Option<FrmSuggestion>,
}
#[derive(Clone, Debug)]
pub struct ConnectorDetailsCore {
pub connector_name: String,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Clone)]
pub struct PaymentToFrmData {
pub amount: Amount,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub merchant_account: MerchantAccount,
pub address: PaymentAddress,
pub connector_details: ConnectorDetailsCore,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub frm_metadata: Option<SecretSerdeValue>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrmConfigsObject {
pub frm_enabled_pm: Option<PaymentMethod>,
pub frm_enabled_gateway: Option<api_models::enums::Connector>,
pub frm_preferred_flow_type: api_enums::FrmPreferredFlowTypes,
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiRequest {
///unique order_id for the order_details in the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED
#[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")]
pub fulfillment_status: Option<FulfillmentStatus>,
///contains details of the fulfillment
#[schema(value_type = Vec<Fulfillments>)]
pub fulfillments: Vec<Fulfillments>,
}
#[derive(Debug, ToSchema, Clone, Serialize)]
pub struct FrmFulfillmentResponse {
///unique order_id for the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///shipment_ids used in the fulfillment overall...also data from previous fulfillments for the same transactions/order is sent
#[schema(example = r#"["ship_101", "ship_102"]"#)]
pub shipment_ids: Vec<String>,
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "camelCase")]
pub struct FrmFulfillmentSignifydApiResponse {
///unique order_id for the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///shipment_ids used in the fulfillment overall...also data from previous fulfillments for the same transactions/order is sent
#[schema(example = r#"["ship_101","ship_102"]"#)]
pub shipment_ids: Vec<String>,
}
pub const CANCEL_INITIATED: &str = "Cancel Initiated with the processor";
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/operation.rs | crates/router/src/core/fraud_check/operation.rs | pub mod fraud_check_post;
pub mod fraud_check_pre;
use async_trait::async_trait;
use common_enums::FrmSuggestion;
use error_stack::{report, ResultExt};
pub use self::{fraud_check_post::FraudCheckPost, fraud_check_pre::FraudCheckPre};
use super::{
types::{ConnectorDetailsCore, FrmConfigsObject, PaymentToFrmData},
FrmData,
};
use crate::{
core::errors::{self, RouterResult},
routes::{app::ReqState, SessionState},
types::{domain, fraud_check::FrmRouterData},
};
pub type BoxedFraudCheckOperation<F, D> = Box<dyn FraudCheckOperation<F, D> + Send + Sync>;
pub trait FraudCheckOperation<F, D>: Send + std::fmt::Debug {
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("domain interface not found for {self:?}"))
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Err(report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable_lazy(|| format!("get tracker interface not found for {self:?}"))
}
}
#[async_trait]
pub trait GetTracker<D>: Send {
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: D,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>>;
}
#[async_trait]
#[allow(clippy::too_many_arguments)]
pub trait Domain<F, D>: Send + Sync {
async fn post_payment_frm<'a>(
&'a self,
state: &'a SessionState,
req_state: ReqState,
payment_data: &mut D,
frm_data: &mut FrmData,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>>
where
F: Send + Clone;
async fn pre_payment_frm<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut D,
frm_data: &mut FrmData,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
) -> RouterResult<FrmRouterData>
where
F: Send + Clone;
// To execute several tasks conditionally based on the result of post_flow.
// Eg: If the /sale(post flow) is returning the transaction as fraud we can execute refund in post task
#[allow(clippy::too_many_arguments)]
async fn execute_post_tasks(
&self,
_state: &SessionState,
_req_state: ReqState,
frm_data: &mut FrmData,
_platform: &domain::Platform,
_frm_configs: FrmConfigsObject,
_frm_suggestion: &mut Option<FrmSuggestion>,
_payment_data: &mut D,
_customer: &Option<domain::Customer>,
_should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>>
where
F: Send + Clone,
{
return Ok(Some(frm_data.to_owned()));
}
}
#[async_trait]
pub trait UpdateTracker<Fd, F: Clone, D>: Send {
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
frm_data: Fd,
payment_data: &mut D,
_frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<Fd>;
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs | crates/router/src/core/fraud_check/flows/fulfillment_flow.rs | use common_utils::ext_traits::{OptionExt, ValueExt};
use error_stack::ResultExt;
use router_env::tracing::{self, instrument};
use crate::{
core::{
errors::RouterResult, fraud_check::frm_core_types::FrmFulfillmentRequest,
payments::helpers, utils as core_utils,
},
errors,
types::{
domain,
fraud_check::{FraudCheckFulfillmentData, FrmFulfillmentRouterData},
storage, ConnectorAuthType, ErrorResponse, PaymentAddress, RouterData,
},
utils, SessionState,
};
#[cfg(feature = "v2")]
pub async fn construct_fulfillment_router_data<'a>(
_state: &'a SessionState,
_payment_intent: &'a storage::PaymentIntent,
_payment_attempt: &storage::PaymentAttempt,
_platform: &domain::Platform,
_connector: String,
_fulfillment_request: FrmFulfillmentRequest,
) -> RouterResult<FrmFulfillmentRouterData> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub async fn construct_fulfillment_router_data<'a>(
state: &'a SessionState,
payment_intent: &'a storage::PaymentIntent,
payment_attempt: &storage::PaymentAttempt,
platform: &domain::Platform,
connector: String,
fulfillment_request: FrmFulfillmentRequest,
) -> RouterResult<FrmFulfillmentRouterData> {
let profile_id = payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("profile_id is not set in payment_intent")?
.clone();
let connector_id = connector.clone();
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
platform.get_processor().get_account().get_id(),
None,
platform.get_processor().get_key_store(),
&profile_id,
&connector,
None,
)
.await?;
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let payment_method =
utils::OptionExt::get_required_value(payment_attempt.payment_method, "payment_method")?;
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: platform.get_processor().get_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
connector,
payment_id: payment_attempt.payment_id.get_string_repr().to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
status: payment_attempt.status,
payment_method,
payment_method_type: payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: payment_attempt.authentication_type.unwrap_or_default(),
connector_meta_data: merchant_connector_account.get_metadata(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: payment_intent
.amount_captured
.map(|amt| amt.get_amount_as_i64()),
minor_amount_captured: payment_intent.amount_captured,
payment_method_status: None,
request: FraudCheckFulfillmentData {
amount: payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: payment_intent.order_details.clone(),
fulfillment_req: fulfillment_request,
},
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
customer_id: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
&state.conf,
platform.get_processor(),
payment_intent,
payment_attempt,
&connector_id,
)?,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
payout_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/flows/transaction_flow.rs | crates/router/src/core/fraud_check/flows/transaction_flow.rs | use async_trait::async_trait;
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FrmData},
payments::{self, flows::ConstructFlowSpecificData, helpers},
},
errors, services,
types::{
api::fraud_check as frm_api,
domain,
fraud_check::{
FraudCheckResponseData, FraudCheckTransactionData, FrmTransactionRouterData,
},
storage::enums as storage_enums,
ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
SessionState,
};
#[async_trait]
impl
ConstructFlowSpecificData<
frm_api::Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
> for FrmData
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_platform: &domain::Platform,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let payment_method = self.payment_attempt.payment_method;
let currency = self.payment_attempt.currency;
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: platform.get_processor().get_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
status,
payment_method: self
.payment_attempt
.payment_method
.ok_or(errors::ApiErrorResponse::PaymentMethodNotFound)?,
payment_method_type: self.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckTransactionData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: self.order_details.clone(),
currency,
payment_method,
error_code: self.payment_attempt.error_code.clone(),
error_message: self.payment_attempt.error_message.clone(),
connector_transaction_id: self
.payment_attempt
.get_connector_payment_id()
.map(ToString::to_string),
connector: self.payment_attempt.connector.clone(),
}, // self.order_details
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
status: storage_enums::FraudCheckStatus::Pending,
score: None,
reason: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
payment_method_status: None,
apple_pay_flow: None,
frm_metadata: self.frm_metadata.clone(),
refund_id: None,
dispute_id: None,
payout_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
}
#[async_trait]
impl FeatureFrm<frm_api::Transaction, FraudCheckTransactionData> for FrmTransactionRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &frm_api::FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
platform: &domain::Platform,
) -> RouterResult<Self> {
decide_frm_flow(&mut self, state, connector, call_connector_action, platform).await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmTransactionRouterData,
state: &SessionState,
connector: &frm_api::FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_platform: &domain::Platform,
) -> RouterResult<FrmTransactionRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
frm_api::Transaction,
FraudCheckTransactionData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/flows/checkout_flow.rs | crates/router/src/core/fraud_check/flows/checkout_flow.rs | use async_trait::async_trait;
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::ResultExt;
use masking::ExposeInterface;
use super::{ConstructFlowSpecificData, FeatureFrm};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::types::FrmData,
payments::{self, helpers},
},
errors, services,
types::{
api::fraud_check::{self as frm_api, FraudCheckConnectorData},
domain,
fraud_check::{FraudCheckCheckoutData, FraudCheckResponseData, FrmCheckoutRouterData},
storage::enums as storage_enums,
BrowserInformation, ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
SessionState,
};
#[async_trait]
impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>
for FrmData
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_platform: &domain::Platform,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
use crate::connector::utils::PaymentsAttemptData;
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let browser_info: Option<BrowserInformation> = self.payment_attempt.get_browser_info().ok();
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: platform.get_processor().get_account().get_id().clone(),
customer_id,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
status,
payment_method: self
.payment_attempt
.payment_method
.ok_or(errors::ApiErrorResponse::PaymentMethodNotFound)?,
payment_method_type: self.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
payment_method_status: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckCheckoutData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: self.order_details.clone(),
currency: self.payment_attempt.currency,
browser_info,
payment_method_data: self
.payment_attempt
.payment_method_data
.as_ref()
.map(|pm_data| {
pm_data
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"AdditionalPaymentData",
)
})
.transpose()
.unwrap_or_default(),
email: customer
.clone()
.and_then(|customer_data| {
customer_data
.email
.map(|email| Email::try_from(email.into_inner().expose()))
})
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer.customer_data.email",
})?,
gateway: self.payment_attempt.connector.clone(),
}, // self.order_details
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
status: storage_enums::FraudCheckStatus::Pending,
score: None,
reason: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
apple_pay_flow: None,
frm_metadata: self.frm_metadata.clone(),
refund_id: None,
dispute_id: None,
payout_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
}
#[async_trait]
impl FeatureFrm<frm_api::Checkout, FraudCheckCheckoutData> for FrmCheckoutRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
platform: &domain::Platform,
) -> RouterResult<Self> {
decide_frm_flow(&mut self, state, connector, call_connector_action, platform).await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmCheckoutRouterData,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_platform: &domain::Platform,
) -> RouterResult<FrmCheckoutRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
frm_api::Checkout,
FraudCheckCheckoutData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/flows/sale_flow.rs | crates/router/src/core/fraud_check/flows/sale_flow.rs | use async_trait::async_trait;
use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::ResultExt;
use masking::ExposeInterface;
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FraudCheckConnectorData, FrmData},
payments::{self, flows::ConstructFlowSpecificData, helpers},
},
errors, services,
types::{
api::fraud_check as frm_api,
domain,
fraud_check::{FraudCheckResponseData, FraudCheckSaleData, FrmSaleRouterData},
storage::enums as storage_enums,
ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
SessionState,
};
#[async_trait]
impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>
for FrmData
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_platform: &domain::Platform,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: platform.get_processor().get_account().get_id().clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
tenant_id: state.tenant.tenant_id.clone(),
status,
payment_method: self
.payment_attempt
.payment_method
.ok_or(errors::ApiErrorResponse::PaymentMethodNotFound)?,
payment_method_type: self.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckSaleData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
order_details: self.order_details.clone(),
currency: self.payment_attempt.currency,
email: customer
.clone()
.and_then(|customer_data| {
customer_data
.email
.map(|email| Email::try_from(email.into_inner().expose()))
})
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer.customer_data.email",
})?,
},
response: Ok(FraudCheckResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
status: storage_enums::FraudCheckStatus::Pending,
score: None,
reason: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
payment_method_status: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
apple_pay_flow: None,
frm_metadata: self.frm_metadata.clone(),
refund_id: None,
dispute_id: None,
payout_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
}
#[async_trait]
impl FeatureFrm<frm_api::Sale, FraudCheckSaleData> for FrmSaleRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
platform: &domain::Platform,
) -> RouterResult<Self> {
decide_frm_flow(&mut self, state, connector, call_connector_action, platform).await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmSaleRouterData,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_platform: &domain::Platform,
) -> RouterResult<FrmSaleRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
frm_api::Sale,
FraudCheckSaleData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/flows/record_return.rs | crates/router/src/core/fraud_check/flows/record_return.rs | use async_trait::async_trait;
use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use crate::{
connector::signifyd::transformers::RefundMethod,
core::{
errors::{ConnectorErrorExt, RouterResult},
fraud_check::{FeatureFrm, FraudCheckConnectorData, FrmData},
payments::{self, flows::ConstructFlowSpecificData, helpers},
},
errors, services,
types::{
api::RecordReturn,
domain,
fraud_check::{
FraudCheckRecordReturnData, FraudCheckResponseData, FrmRecordReturnRouterData,
},
storage::enums as storage_enums,
ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
utils, SessionState,
};
#[async_trait]
impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>
for FrmData
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
_state: &SessionState,
_connector_id: &str,
_platform: &domain::Platform,
_customer: &Option<domain::Customer>,
_merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<MerchantRecipientData>,
_header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
_merchant_recipient_data: Option<MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
_payment_method: Option<common_enums::PaymentMethod>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
let status = storage_enums::AttemptStatus::Pending;
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
let customer_id = customer.to_owned().map(|customer| customer.customer_id);
let currency = self.payment_attempt.clone().currency;
let router_data = RouterData {
flow: std::marker::PhantomData,
merchant_id: platform.get_processor().get_account().get_id().clone(),
tenant_id: state.tenant.tenant_id.clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.get_string_repr().to_owned(),
attempt_id: self.payment_attempt.attempt_id.clone(),
status,
payment_method: utils::OptionExt::get_required_value(
self.payment_attempt.payment_method,
"payment_method",
)?,
payment_method_type: self.payment_attempt.payment_method_type,
connector_auth_type: auth_type,
description: None,
address: self.address.clone(),
auth_type: storage_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: FraudCheckRecordReturnData {
amount: self
.payment_attempt
.net_amount
.get_total_amount()
.get_amount_as_i64(),
refund_method: RefundMethod::OriginalPaymentInstrument, //we dont consume this data now in payments...hence hardcoded
currency,
refund_transaction_id: self.refund.clone().map(|refund| refund.refund_id),
}, // self.order_details
response: Ok(FraudCheckResponseData::RecordReturnResponse {
resource_id: ResponseId::ConnectorTransactionId("".to_string()),
connector_metadata: None,
return_id: None,
}),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
preprocessing_id: None,
payment_method_status: None,
connector_request_reference_id: uuid::Uuid::new_v4().to_string(),
test_mode: None,
recurring_mandate_payment_data: None,
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
payment_method_balance: None,
connector_http_status_code: None,
external_latency: None,
connector_api_version: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
payout_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
}
#[async_trait]
impl FeatureFrm<RecordReturn, FraudCheckRecordReturnData> for FrmRecordReturnRouterData {
async fn decide_frm_flows<'a>(
mut self,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
platform: &domain::Platform,
) -> RouterResult<Self> {
decide_frm_flow(&mut self, state, connector, call_connector_action, platform).await
}
}
pub async fn decide_frm_flow(
router_data: &mut FrmRecordReturnRouterData,
state: &SessionState,
connector: &FraudCheckConnectorData,
call_connector_action: payments::CallConnectorAction,
_platform: &domain::Platform,
) -> RouterResult<FrmRecordReturnRouterData> {
let connector_integration: services::BoxedFrmConnectorIntegrationInterface<
RecordReturn,
FraudCheckRecordReturnData,
FraudCheckResponseData,
> = connector.connector.get_connector_integration();
let resp = services::execute_connector_processing_step(
state,
connector_integration,
router_data,
call_connector_action,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(resp)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs | crates/router/src/core/fraud_check/operation/fraud_check_pre.rs | use async_trait::async_trait;
use common_enums::FrmSuggestion;
use common_utils::ext_traits::Encode;
use diesel_models::enums::FraudCheckLastStep;
use router_env::{instrument, tracing};
use uuid::Uuid;
use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker};
use crate::{
core::{
errors::RouterResult,
fraud_check::{
self as frm_core,
types::{FrmData, PaymentDetails, PaymentToFrmData},
ConnectorDetailsCore,
},
payments,
},
errors,
routes::app::ReqState,
types::{
api::fraud_check as frm_api,
domain,
fraud_check::{
FraudCheckCheckoutData, FraudCheckResponseData, FraudCheckTransactionData, FrmRequest,
FrmResponse, FrmRouterData,
},
storage::{
enums::{FraudCheckStatus, FraudCheckType},
fraud_check::{FraudCheckNew, FraudCheckUpdate},
},
ResponseId,
},
SessionState,
};
#[derive(Debug, Clone, Copy)]
pub struct FraudCheckPre;
impl<F, D> FraudCheckOperation<F, D> for &FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(*self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(*self)
}
}
impl<F, D> FraudCheckOperation<F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(self)
}
}
#[async_trait]
impl GetTracker<PaymentToFrmData> for FraudCheckPre {
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
let db = &*state.store;
let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
.encode_to_value()
.ok();
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.get_id().to_owned(),
payment_data.merchant_account.get_id().clone(),
)
.await
.ok();
let fraud_check = match existing_fraud_check {
Some(Some(fraud_check)) => Ok(fraud_check),
_ => {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: Uuid::new_v4().simple().to_string(),
payment_id: payment_data.payment_intent.get_id().to_owned(),
merchant_id: payment_data.merchant_account.get_id().clone(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
created_at: common_utils::date_time::now(),
frm_name: frm_connector_details.connector_name,
frm_transaction_id: None,
frm_transaction_type: FraudCheckType::PreFrm,
frm_status: FraudCheckStatus::Pending,
frm_score: None,
frm_reason: None,
frm_error: None,
payment_details,
metadata: None,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Processing,
payment_capture_method: payment_data.payment_attempt.capture_method,
})
.await
}
};
match fraud_check {
Ok(fraud_check_value) => {
let frm_data = FrmData {
payment_intent: payment_data.payment_intent,
payment_attempt: payment_data.payment_attempt,
merchant_account: payment_data.merchant_account,
address: payment_data.address,
fraud_check: fraud_check_value,
connector_details: payment_data.connector_details,
order_details: payment_data.order_details,
refund: None,
frm_metadata: payment_data.frm_metadata,
};
Ok(Some(frm_data))
}
Err(error) => {
router_env::logger::error!("inserting into fraud_check table failed {error:?}");
Ok(None)
}
}
}
}
#[async_trait]
impl<F, D> Domain<F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn post_payment_frm<'a>(
&'a self,
_state: &'a SessionState,
_req_state: ReqState,
_payment_data: &mut D,
_frm_data: &mut FrmData,
_platform: &domain::Platform,
_customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn post_payment_frm<'a>(
&'a self,
state: &'a SessionState,
_req_state: ReqState,
payment_data: &mut D,
frm_data: &mut FrmData,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>> {
let router_data = frm_core::call_frm_service::<F, frm_api::Transaction, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
platform,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund;
Ok(Some(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Transaction(FraudCheckTransactionData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
payment_method: Some(router_data.payment_method),
error_code: router_data.request.error_code,
error_message: router_data.request.error_message,
connector_transaction_id: router_data.request.connector_transaction_id,
connector: router_data.request.connector,
}),
response: FrmResponse::Transaction(router_data.response),
}))
}
async fn pre_payment_frm<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut D,
frm_data: &mut FrmData,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
) -> RouterResult<FrmRouterData> {
let router_data = frm_core::call_frm_service::<F, frm_api::Checkout, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
platform,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::CheckoutOrSale;
Ok(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Checkout(Box::new(FraudCheckCheckoutData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
browser_info: router_data.request.browser_info,
payment_method_data: router_data.request.payment_method_data,
email: router_data.request.email,
gateway: router_data.request.gateway,
})),
response: FrmResponse::Checkout(router_data.response),
})
}
}
#[async_trait]
impl<F, D> UpdateTracker<FrmData, F, D> for FraudCheckPre
where
F: Clone + Send,
D: payments::OperationSessionGetters<F> + Send + Sync + Clone,
{
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
_key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
_frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
let frm_check_update = match frm_router_data.response {
FrmResponse::Checkout(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse {
resource_id: _,
connector_metadata: _,
return_id: _,
} => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Checkout flow"
.to_string(),
)),
}),
},
},
FrmResponse::Transaction(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let frm_status = payment_data
.get_frm_message()
.as_ref()
.map_or(status, |frm_data| frm_data.frm_status);
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: None,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse {
resource_id: _,
connector_metadata: _,
return_id: _,
} => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Checkout flow"
.to_string(),
)),
}),
},
},
FrmResponse::Sale(_response)
| FrmResponse::Fulfillment(_response)
| FrmResponse::RecordReturn(_response) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Pre(Sale) flow response in current post flow".to_string(),
)),
}),
};
let db = &*state.store;
frm_data.fraud_check = match frm_check_update {
Some(fraud_check_update) => db
.update_fraud_check_response_with_attempt_id(
frm_data.clone().fraud_check,
fraud_check_update,
)
.await
.map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?,
None => frm_data.clone().fraud_check,
};
Ok(frm_data)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/fraud_check/operation/fraud_check_post.rs | crates/router/src/core/fraud_check/operation/fraud_check_post.rs | use async_trait::async_trait;
use common_enums::{CaptureMethod, FrmSuggestion};
use common_utils::ext_traits::Encode;
use hyperswitch_domain_models::payments::{
payment_attempt::PaymentAttemptUpdate, payment_intent::PaymentIntentUpdate, HeaderPayload,
};
use router_env::{instrument, logger, tracing};
use super::{Domain, FraudCheckOperation, GetTracker, UpdateTracker};
use crate::{
consts,
core::{
errors::{RouterResult, StorageErrorExt},
fraud_check::{
self as frm_core,
types::{FrmData, PaymentDetails, PaymentToFrmData, CANCEL_INITIATED},
ConnectorDetailsCore, FrmConfigsObject,
},
payments,
},
errors,
routes::app::ReqState,
services::{self, api},
types::{
api::{
enums::{AttemptStatus, IntentStatus},
fraud_check as frm_api, payments as payment_types, Capture, Void,
},
domain,
fraud_check::{
FraudCheckResponseData, FraudCheckSaleData, FrmRequest, FrmResponse, FrmRouterData,
},
storage::{
enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType, MerchantDecision},
fraud_check::{FraudCheckNew, FraudCheckUpdate},
},
ResponseId,
},
utils, SessionState,
};
#[derive(Debug, Clone, Copy)]
pub struct FraudCheckPost;
impl<F, D> FraudCheckOperation<F, D> for &FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(*self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(*self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(*self)
}
}
impl<F, D> FraudCheckOperation<F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<PaymentToFrmData> + Send + Sync)> {
Ok(self)
}
fn to_domain(&self) -> RouterResult<&dyn Domain<F, D>> {
Ok(self)
}
fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker<FrmData, F, D> + Send + Sync)> {
Ok(self)
}
}
#[async_trait]
impl GetTracker<PaymentToFrmData> for FraudCheckPost {
#[cfg(feature = "v2")]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_trackers<'a>(
&'a self,
state: &'a SessionState,
payment_data: PaymentToFrmData,
frm_connector_details: ConnectorDetailsCore,
) -> RouterResult<Option<FrmData>> {
let db = &*state.store;
let payment_details: Option<serde_json::Value> = PaymentDetails::from(payment_data.clone())
.encode_to_value()
.ok();
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.get_id().to_owned(),
payment_data.merchant_account.get_id().clone(),
)
.await
.ok();
let fraud_check = match existing_fraud_check {
Some(Some(fraud_check)) => Ok(fraud_check),
_ => {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: utils::generate_id(consts::ID_LENGTH, "frm"),
payment_id: payment_data.payment_intent.get_id().to_owned(),
merchant_id: payment_data.merchant_account.get_id().clone(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
created_at: common_utils::date_time::now(),
frm_name: frm_connector_details.connector_name,
frm_transaction_id: None,
frm_transaction_type: FraudCheckType::PostFrm,
frm_status: FraudCheckStatus::Pending,
frm_score: None,
frm_reason: None,
frm_error: None,
payment_details,
metadata: None,
modified_at: common_utils::date_time::now(),
last_step: FraudCheckLastStep::Processing,
payment_capture_method: payment_data.payment_attempt.capture_method,
})
.await
}
};
match fraud_check {
Ok(fraud_check_value) => {
let frm_data = FrmData {
payment_intent: payment_data.payment_intent,
payment_attempt: payment_data.payment_attempt,
merchant_account: payment_data.merchant_account,
address: payment_data.address,
fraud_check: fraud_check_value,
connector_details: payment_data.connector_details,
order_details: payment_data.order_details,
refund: None,
frm_metadata: payment_data.frm_metadata,
};
Ok(Some(frm_data))
}
Err(error) => {
router_env::logger::error!("inserting into fraud_check table failed {error:?}");
Ok(None)
}
}
}
}
#[async_trait]
impl<F, D> Domain<F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
#[instrument(skip_all)]
async fn post_payment_frm<'a>(
&'a self,
state: &'a SessionState,
_req_state: ReqState,
payment_data: &mut D,
frm_data: &mut FrmData,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
) -> RouterResult<Option<FrmRouterData>> {
if frm_data.fraud_check.last_step != FraudCheckLastStep::Processing {
logger::debug!("post_flow::Sale Skipped");
return Ok(None);
}
let router_data = frm_core::call_frm_service::<F, frm_api::Sale, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
platform,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::CheckoutOrSale;
Ok(Some(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id.clone(),
attempt_id: router_data.attempt_id,
request: FrmRequest::Sale(FraudCheckSaleData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
email: router_data.request.email,
}),
response: FrmResponse::Sale(router_data.response),
}))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn execute_post_tasks(
&self,
_state: &SessionState,
_req_state: ReqState,
_frm_data: &mut FrmData,
_platform: &domain::Platform,
_frm_configs: FrmConfigsObject,
_frm_suggestion: &mut Option<FrmSuggestion>,
_payment_data: &mut D,
_customer: &Option<domain::Customer>,
_should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>> {
todo!()
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn execute_post_tasks(
&self,
state: &SessionState,
req_state: ReqState,
frm_data: &mut FrmData,
platform: &domain::Platform,
_frm_configs: FrmConfigsObject,
frm_suggestion: &mut Option<FrmSuggestion>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
_should_continue_capture: &mut bool,
) -> RouterResult<Option<FrmData>> {
if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Fraud)
&& matches!(
frm_data.fraud_check.last_step,
FraudCheckLastStep::CheckoutOrSale
)
{
*frm_suggestion = Some(FrmSuggestion::FrmCancelTransaction);
let cancel_req = api_models::payments::PaymentsCancelRequest {
payment_id: frm_data.payment_intent.get_id().to_owned(),
cancellation_reason: frm_data.fraud_check.frm_error.clone(),
merchant_connector_details: None,
};
let cancel_res = Box::pin(payments::payments_core::<
Void,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<Void>,
>(
state.clone(),
req_state.clone(),
platform.clone(),
None,
payments::PaymentCancel,
cancel_req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
HeaderPayload::default(),
))
.await?;
logger::debug!("payment_id : {:?} has been cancelled since it has been found fraudulent by configured frm connector",payment_data.get_payment_attempt().payment_id);
if let services::ApplicationResponse::JsonWithHeaders((payments_response, _)) =
cancel_res
{
payment_data.set_payment_intent_status(payments_response.status);
}
let _router_data = frm_core::call_frm_service::<F, frm_api::RecordReturn, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
platform,
customer,
)
.await?;
frm_data.fraud_check.last_step = FraudCheckLastStep::TransactionOrRecordRefund;
} else if matches!(
frm_data.fraud_check.frm_status,
FraudCheckStatus::ManualReview
) {
*frm_suggestion = Some(FrmSuggestion::FrmManualReview);
} else if matches!(frm_data.fraud_check.frm_status, FraudCheckStatus::Legit)
&& matches!(
frm_data.fraud_check.payment_capture_method,
Some(CaptureMethod::Automatic) | Some(CaptureMethod::SequentialAutomatic)
)
{
let capture_request = api_models::payments::PaymentsCaptureRequest {
payment_id: frm_data.payment_intent.get_id().to_owned(),
merchant_id: None,
amount_to_capture: None,
refund_uncaptured_amount: None,
statement_descriptor_suffix: None,
statement_descriptor_prefix: None,
merchant_connector_details: None,
all_keys_required: None,
};
let capture_response = Box::pin(payments::payments_core::<
Capture,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<Capture>,
>(
state.clone(),
req_state.clone(),
platform.clone(),
None,
payments::PaymentCapture,
capture_request,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
HeaderPayload::default(),
))
.await?;
logger::debug!("payment_id : {:?} has been captured since it has been found legit by configured frm connector",payment_data.get_payment_attempt().payment_id);
if let services::ApplicationResponse::JsonWithHeaders((payments_response, _)) =
capture_response
{
payment_data.set_payment_intent_status(payments_response.status);
}
};
return Ok(Some(frm_data.to_owned()));
}
#[instrument(skip_all)]
async fn pre_payment_frm<'a>(
&'a self,
state: &'a SessionState,
payment_data: &mut D,
frm_data: &mut FrmData,
platform: &domain::Platform,
customer: &Option<domain::Customer>,
) -> RouterResult<FrmRouterData> {
let router_data = frm_core::call_frm_service::<F, frm_api::Sale, _, D>(
state,
payment_data,
&mut frm_data.to_owned(),
platform,
customer,
)
.await?;
Ok(FrmRouterData {
merchant_id: router_data.merchant_id,
connector: router_data.connector,
payment_id: router_data.payment_id,
attempt_id: router_data.attempt_id,
request: FrmRequest::Sale(FraudCheckSaleData {
amount: router_data.request.amount,
order_details: router_data.request.order_details,
currency: router_data.request.currency,
email: router_data.request.email,
}),
response: FrmResponse::Sale(router_data.response),
})
}
}
#[async_trait]
impl<F, D> UpdateTracker<FrmData, F, D> for FraudCheckPost
where
F: Clone + Send,
D: payments::OperationSessionGetters<F>
+ payments::OperationSessionSetters<F>
+ Send
+ Sync
+ Clone,
{
#[cfg(feature = "v2")]
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
todo!()
}
#[cfg(feature = "v1")]
async fn update_tracker<'b>(
&'b self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
mut frm_data: FrmData,
payment_data: &mut D,
frm_suggestion: Option<FrmSuggestion>,
frm_router_data: FrmRouterData,
) -> RouterResult<FrmData> {
let db = &*state.store;
let frm_check_update = match frm_router_data.response {
FrmResponse::Sale(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
},
FraudCheckResponseData::RecordReturnResponse { resource_id: _, connector_metadata: _, return_id: _ } => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Record Return Response response in current Sale flow".to_string(),
)),
})
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
},
},
FrmResponse::Fulfillment(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id,
connector_metadata,
status,
reason,
score,
} => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: status,
frm_transaction_id: connector_transaction_id,
frm_reason: reason,
frm_score: score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
FraudCheckResponseData::FulfillmentResponse {
order_id: _,
shipment_ids: _,
} => None,
FraudCheckResponseData::RecordReturnResponse { resource_id: _, connector_metadata: _, return_id: _ } => None,
},
},
FrmResponse::RecordReturn(response) => match response {
Err(err) => Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(err.message)),
}),
Ok(payments_response) => match payments_response {
FraudCheckResponseData::TransactionResponse {
resource_id: _,
connector_metadata: _,
status: _,
reason: _,
score: _,
} => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Transaction Response response in current Record Return flow".to_string(),
)),
})
},
FraudCheckResponseData::FulfillmentResponse {order_id: _, shipment_ids: _ } => {
None
},
FraudCheckResponseData::RecordReturnResponse { resource_id, connector_metadata, return_id: _ } => {
let connector_transaction_id = match resource_id {
ResponseId::NoResponseId => None,
ResponseId::ConnectorTransactionId(id) => Some(id),
ResponseId::EncodedData(id) => Some(id),
};
let fraud_check_update = FraudCheckUpdate::ResponseUpdate {
frm_status: frm_data.fraud_check.frm_status,
frm_transaction_id: connector_transaction_id,
frm_reason: frm_data.fraud_check.frm_reason.clone(),
frm_score: frm_data.fraud_check.frm_score,
metadata: connector_metadata,
modified_at: common_utils::date_time::now(),
last_step: frm_data.fraud_check.last_step,
payment_capture_method: frm_data.fraud_check.payment_capture_method,
};
Some(fraud_check_update)
}
},
},
FrmResponse::Checkout(_) | FrmResponse::Transaction(_) => {
Some(FraudCheckUpdate::ErrorUpdate {
status: FraudCheckStatus::TransactionFailure,
error_message: Some(Some(
"Error: Got Pre(Sale) flow response in current post flow".to_string(),
)),
})
}
};
if let Some(frm_suggestion) = frm_suggestion {
let (payment_attempt_status, payment_intent_status, merchant_decision, error_message) =
match frm_suggestion {
FrmSuggestion::FrmCancelTransaction => (
AttemptStatus::Failure,
IntentStatus::Failed,
Some(MerchantDecision::Rejected.to_string()),
Some(Some(CANCEL_INITIATED.to_string())),
),
FrmSuggestion::FrmManualReview => (
AttemptStatus::Unresolved,
IntentStatus::RequiresMerchantAction,
None,
None,
),
FrmSuggestion::FrmAuthorizeTransaction => (
AttemptStatus::Authorized,
IntentStatus::RequiresCapture,
None,
None,
),
};
let payment_attempt_update = PaymentAttemptUpdate::RejectUpdate {
status: payment_attempt_status,
error_code: Some(Some(frm_data.fraud_check.frm_status.to_string())),
error_message,
updated_by: frm_data.merchant_account.storage_scheme.to_string(),
};
#[cfg(feature = "v1")]
let payment_attempt = db
.update_payment_attempt_with_attempt_id(
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
frm_data.merchant_account.storage_scheme,
key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
#[cfg(feature = "v2")]
let payment_attempt = db
.update_payment_attempt_with_attempt_id(
key_manager_state,
key_store,
payment_data.get_payment_attempt().clone(),
payment_attempt_update,
frm_data.merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_attempt(payment_attempt);
let payment_intent = db
.update_payment_intent(
payment_data.get_payment_intent().clone(),
PaymentIntentUpdate::RejectUpdate {
status: payment_intent_status,
merchant_decision,
updated_by: frm_data.merchant_account.storage_scheme.to_string(),
},
key_store,
frm_data.merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.set_payment_intent(payment_intent);
}
frm_data.fraud_check = match frm_check_update {
Some(fraud_check_update) => db
.update_fraud_check_response_with_attempt_id(
frm_data.fraud_check.clone(),
fraud_check_update,
)
.await
.map_err(|error| error.change_context(errors::ApiErrorResponse::PaymentNotFound))?,
None => frm_data.fraud_check.clone(),
};
Ok(frm_data)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/pm_auth/helpers.rs | crates/router/src/core/pm_auth/helpers.rs | use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use pm_auth::types::{self as pm_auth_types, api::BoxedPaymentAuthConnector};
use crate::{
core::errors::{self, ApiErrorResponse},
types::{self, domain, transformers::ForeignTryFrom},
};
pub trait PaymentAuthConnectorDataExt {
fn get_connector_by_name(name: &str) -> errors::CustomResult<Self, ApiErrorResponse>
where
Self: Sized;
fn convert_connector(
connector_name: pm_auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<BoxedPaymentAuthConnector, ApiErrorResponse>;
}
pub fn get_connector_auth_type(
merchant_connector_account: domain::MerchantConnectorAccount,
) -> errors::CustomResult<pm_auth_types::ConnectorAuthType, ApiErrorResponse> {
let auth_type: types::ConnectorAuthType = merchant_connector_account
.connector_account_details
.parse_value("ConnectorAuthType")
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
id: "ConnectorAuthType".to_string(),
})?;
pm_auth_types::ConnectorAuthType::foreign_try_from(auth_type)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed while converting ConnectorAuthType")
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/core/pm_auth/transformers.rs | crates/router/src/core/pm_auth/transformers.rs | use pm_auth::types as pm_auth_types;
use crate::{core::errors, types, types::transformers::ForeignTryFrom};
impl From<types::MerchantAccountData> for pm_auth_types::MerchantAccountData {
fn from(from: types::MerchantAccountData) -> Self {
match from {
types::MerchantAccountData::Iban { iban, name, .. } => Self::Iban { iban, name },
types::MerchantAccountData::Bacs {
account_number,
sort_code,
name,
..
} => Self::Bacs {
account_number,
sort_code,
name,
},
types::MerchantAccountData::FasterPayments {
account_number,
sort_code,
name,
..
} => Self::FasterPayments {
account_number,
sort_code,
name,
},
types::MerchantAccountData::Sepa { iban, name, .. } => Self::Sepa { iban, name },
types::MerchantAccountData::SepaInstant { iban, name, .. } => {
Self::SepaInstant { iban, name }
}
types::MerchantAccountData::Elixir {
account_number,
iban,
name,
..
} => Self::Elixir {
account_number,
iban,
name,
},
types::MerchantAccountData::Bankgiro { number, name, .. } => {
Self::Bankgiro { number, name }
}
types::MerchantAccountData::Plusgiro { number, name, .. } => {
Self::Plusgiro { number, name }
}
}
}
}
impl From<types::MerchantRecipientData> for pm_auth_types::MerchantRecipientData {
fn from(value: types::MerchantRecipientData) -> Self {
match value {
types::MerchantRecipientData::ConnectorRecipientId(id) => {
Self::ConnectorRecipientId(id)
}
types::MerchantRecipientData::WalletId(id) => Self::WalletId(id),
types::MerchantRecipientData::AccountData(data) => Self::AccountData(data.into()),
}
}
}
impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType {
type Error = errors::ConnectorError;
fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::BodyKey { api_key, key1 } => {
Ok::<Self, errors::ConnectorError>(Self::BodyKey {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe.rs | crates/router/src/compatibility/stripe.rs | pub mod app;
pub mod customers;
pub mod payment_intents;
pub mod refunds;
pub mod setup_intents;
pub mod webhooks;
#[cfg(feature = "v1")]
use actix_web::{web, Scope};
pub mod errors;
#[cfg(feature = "v1")]
use crate::routes;
#[cfg(feature = "v1")]
pub struct StripeApis;
#[cfg(feature = "v1")]
impl StripeApis {
pub fn server(state: routes::AppState) -> Scope {
let max_depth = 10;
let strict = false;
web::scope("/vs/v1")
.app_data(web::Data::new(serde_qs::Config::new(max_depth, strict)))
.service(app::SetupIntents::server(state.clone()))
.service(app::PaymentIntents::server(state.clone()))
.service(app::Refunds::server(state.clone()))
.service(app::Customers::server(state.clone()))
.service(app::Webhooks::server(state.clone()))
.service(app::Mandates::server(state))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/wrap.rs | crates/router/src/compatibility/wrap.rs | use std::{future::Future, sync::Arc, time::Instant};
use actix_web::{HttpRequest, HttpResponse, Responder};
use common_utils::errors::{CustomResult, ErrorSwitch};
use router_env::{instrument, tracing, Tag};
use serde::Serialize;
use crate::{
core::{api_locking, errors},
events::api_logs::ApiEventMetric,
routes::{
app::{AppStateInfo, ReqState},
AppState, SessionState,
},
services::{self, api, authentication as auth, logger},
};
#[instrument(skip(request, payload, state, func, api_authentication))]
pub async fn compatibility_api_wrap<'a, 'b, U, T, Q, F, Fut, S, E, E2>(
flow: impl router_env::types::FlowMetric,
state: Arc<AppState>,
request: &'a HttpRequest,
payload: T,
func: F,
api_authentication: &dyn auth::AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> HttpResponse
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
Fut: Future<Output = CustomResult<api::ApplicationResponse<Q>, E2>>,
E2: ErrorSwitch<E> + std::error::Error + Send + Sync + 'static,
Q: Serialize + std::fmt::Debug + 'a + ApiEventMetric,
S: TryFrom<Q> + Serialize,
E: Serialize + error_stack::Context + actix_web::ResponseError + Clone,
errors::ApiErrorResponse: ErrorSwitch<E>,
T: std::fmt::Debug + Serialize + ApiEventMetric,
{
let request_method = request.method().as_str();
let url_path = request.path();
tracing::Span::current().record("request_method", request_method);
tracing::Span::current().record("request_url_path", url_path);
let start_instant = Instant::now();
logger::info!(tag = ?Tag::BeginRequest, payload = ?payload);
let server_wrap_util_res = api::server_wrap_util(
&flow,
state.clone().into(),
request.headers(),
request,
payload,
func,
api_authentication,
lock_action,
)
.await
.map(|response| {
logger::info!(api_response =? response);
response
});
let res = match server_wrap_util_res {
Ok(api::ApplicationResponse::Json(response)) => {
let response = S::try_from(response);
match response {
Ok(response) => match serde_json::to_string(&response) {
Ok(res) => api::http_response_json(res),
Err(_) => api::http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
},
Err(_) => api::http_response_err(
r#"{
"error": {
"message": "Error converting juspay response to stripe response"
}
}"#,
),
}
}
Ok(api::ApplicationResponse::JsonWithHeaders((response, headers))) => {
let response = S::try_from(response);
match response {
Ok(response) => match serde_json::to_string(&response) {
Ok(res) => api::http_response_json_with_headers(res, headers, None, None),
Err(_) => api::http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
},
Err(_) => api::http_response_err(
r#"{
"error": {
"message": "Error converting juspay response to stripe response"
}
}"#,
),
}
}
Ok(api::ApplicationResponse::StatusOk) => api::http_response_ok(),
Ok(api::ApplicationResponse::TextPlain(text)) => api::http_response_plaintext(text),
Ok(api::ApplicationResponse::FileData((file_data, content_type))) => {
api::http_response_file_data(file_data, content_type)
}
Ok(api::ApplicationResponse::JsonForRedirection(response)) => {
match serde_json::to_string(&response) {
Ok(res) => api::http_redirect_response(res, response),
Err(_) => api::http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Ok(api::ApplicationResponse::Form(redirection_data)) => {
let config = state.conf();
api::build_redirection_form(
&redirection_data.redirect_form,
redirection_data.payment_method_data,
redirection_data.amount,
redirection_data.currency,
config,
)
.respond_to(request)
.map_into_boxed_body()
}
Ok(api::ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => {
let link_type = (boxed_generic_link_data).data.to_string();
match services::generic_link_response::build_generic_link_html(
boxed_generic_link_data.data,
boxed_generic_link_data.locale,
) {
Ok(rendered_html) => api::http_response_html_data(rendered_html, None),
Err(_) => {
api::http_response_err(format!("Error while rendering {link_type} HTML page"))
}
}
}
Ok(api::ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => {
match *boxed_payment_link_data {
api::PaymentLinkAction::PaymentLinkFormData(payment_link_data) => {
match api::build_payment_link_html(payment_link_data) {
Ok(rendered_html) => api::http_response_html_data(rendered_html, None),
Err(_) => api::http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link html page"
}
}"#,
),
}
}
api::PaymentLinkAction::PaymentLinkStatus(payment_link_data) => {
match api::get_payment_link_status(payment_link_data) {
Ok(rendered_html) => api::http_response_html_data(rendered_html, None),
Err(_) => api::http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link status page"
}
}"#,
),
}
}
}
}
Err(error) => api::log_and_return_error_response(error),
};
let response_code = res.status().as_u16();
let end_instant = Instant::now();
let request_duration = end_instant.saturating_duration_since(start_instant);
logger::info!(
tag = ?Tag::EndRequest,
status_code = response_code,
time_taken_ms = request_duration.as_millis(),
);
res
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/app.rs | crates/router/src/compatibility/stripe/app.rs | use actix_web::{web, Scope};
#[cfg(feature = "v1")]
use super::{customers::*, payment_intents::*, setup_intents::*};
use super::{refunds::*, webhooks::*};
use crate::routes::{self, mandates, webhooks};
pub struct PaymentIntents;
#[cfg(feature = "v1")]
impl PaymentIntents {
pub fn server(state: routes::AppState) -> Scope {
let mut route = web::scope("/payment_intents").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route = route.service(web::resource("/list").route(web::get().to(payment_intent_list)))
}
route = route
.service(web::resource("").route(web::post().to(payment_intents_create)))
.service(
web::resource("/sync")
.route(web::post().to(payment_intents_retrieve_with_gateway_creds)),
)
.service(
web::resource("/{payment_id}")
.route(web::get().to(payment_intents_retrieve))
.route(web::post().to(payment_intents_update)),
)
.service(
web::resource("/{payment_id}/confirm")
.route(web::post().to(payment_intents_confirm)),
)
.service(
web::resource("/{payment_id}/capture")
.route(web::post().to(payment_intents_capture)),
)
.service(
web::resource("/{payment_id}/cancel").route(web::post().to(payment_intents_cancel)),
);
route
}
}
pub struct SetupIntents;
#[cfg(feature = "v1")]
impl SetupIntents {
pub fn server(state: routes::AppState) -> Scope {
web::scope("/setup_intents")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(setup_intents_create)))
.service(
web::resource("/{setup_id}")
.route(web::get().to(setup_intents_retrieve))
.route(web::post().to(setup_intents_update)),
)
.service(
web::resource("/{setup_id}/confirm").route(web::post().to(setup_intents_confirm)),
)
}
}
pub struct Refunds;
impl Refunds {
pub fn server(config: routes::AppState) -> Scope {
web::scope("/refunds")
.app_data(web::Data::new(config))
.service(web::resource("").route(web::post().to(refund_create)))
.service(
web::resource("/sync").route(web::post().to(refund_retrieve_with_gateway_creds)),
)
.service(
web::resource("/{refund_id}")
.route(web::get().to(refund_retrieve))
.route(web::post().to(refund_update)),
)
}
}
pub struct Customers;
#[cfg(feature = "v1")]
impl Customers {
pub fn server(config: routes::AppState) -> Scope {
web::scope("/customers")
.app_data(web::Data::new(config))
.service(web::resource("").route(web::post().to(customer_create)))
.service(
web::resource("/{customer_id}")
.route(web::get().to(customer_retrieve))
.route(web::post().to(customer_update))
.route(web::delete().to(customer_delete)),
)
.service(
web::resource("/{customer_id}/payment_methods")
.route(web::get().to(list_customer_payment_method_api)),
)
}
}
pub struct Webhooks;
impl Webhooks {
pub fn server(config: routes::AppState) -> Scope {
web::scope("/webhooks")
.app_data(web::Data::new(config))
.service(
web::resource("/{merchant_id}/{connector_name}")
.route(
web::post().to(webhooks::receive_incoming_webhook::<StripeOutgoingWebhook>),
)
.route(
web::get().to(webhooks::receive_incoming_webhook::<StripeOutgoingWebhook>),
),
)
}
}
pub struct Mandates;
impl Mandates {
pub fn server(config: routes::AppState) -> Scope {
web::scope("/payment_methods")
.app_data(web::Data::new(config))
.service(web::resource("/{id}/detach").route(web::post().to(mandates::revoke_mandate)))
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/errors.rs | crates/router/src/compatibility/stripe/errors.rs | use common_utils::{errors::ErrorSwitch, id_type};
use hyperswitch_domain_models::errors::api_error_response as errors;
use crate::core::errors::CustomersErrorResponse;
#[derive(Debug, router_derive::ApiError, Clone)]
#[error(error_type_enum = StripeErrorType)]
pub enum StripeErrorCode {
/*
"error": {
"message": "Invalid API Key provided: sk_jkjgs****nlgs",
"type": "invalid_request_error"
}
*/
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_01",
message = "Invalid API Key provided"
)]
Unauthorized,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL.")]
InvalidRequestUrl,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Missing required param: {field_name}.")]
ParameterMissing { field_name: String, param: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "parameter_unknown",
message = "{field_name} contains invalid data. Expected format is {expected_format}."
)]
ParameterUnknown {
field_name: String,
expected_format: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_06", message = "The refund amount exceeds the amount captured.")]
RefundAmountExceedsPaymentAmount { param: String },
#[error(error_type = StripeErrorType::ApiError, code = "payment_intent_authentication_failure", message = "Payment failed while processing with connector. Retry payment.")]
PaymentIntentAuthenticationFailure { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::ApiError, code = "payment_intent_payment_attempt_failed", message = "Capture attempt failed while processing with connector.")]
PaymentIntentPaymentAttemptFailed { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::ApiError, code = "dispute_failure", message = "Dispute failed while processing with connector. Retry operation.")]
DisputeFailed { data: Option<serde_json::Value> },
#[error(error_type = StripeErrorType::CardError, code = "expired_card", message = "Card Expired. Please use another card")]
ExpiredCard,
#[error(error_type = StripeErrorType::CardError, code = "invalid_card_type", message = "Card data is invalid")]
InvalidCardType,
#[error(
error_type = StripeErrorType::ConnectorError, code = "invalid_wallet_token",
message = "Invalid {wallet_name} wallet token"
)]
InvalidWalletToken { wallet_name: String },
#[error(error_type = StripeErrorType::ApiError, code = "refund_failed", message = "refund has failed")]
RefundFailed, // stripe error code
#[error(error_type = StripeErrorType::ApiError, code = "payout_failed", message = "payout has failed")]
PayoutFailed,
#[error(error_type = StripeErrorType::ApiError, code = "external_vault_failed", message = "external vault has failed")]
ExternalVaultFailed,
#[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")]
InternalServerError,
#[error(error_type = StripeErrorType::ApiError, code = "internal_server_error", message = "Server is down")]
DuplicateRefundRequest,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "active_mandate", message = "Customer has active mandate")]
MandateActive,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_redacted", message = "Customer has redacted")]
CustomerRedacted,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "customer_already_exists", message = "Customer with the given customer_id already exists")]
DuplicateCustomer,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such refund")]
RefundNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "client_secret_invalid", message = "Expected client secret to be included in the request")]
ClientSecretNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such customer")]
CustomerNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such config")]
ConfigNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "Duplicate config")]
DuplicateConfig,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment")]
PaymentNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payment method")]
PaymentMethodNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "{message}")]
GenericNotFoundError { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "duplicate_resource", message = "{message}")]
GenericDuplicateError { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such merchant account")]
MerchantAccountNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such resource ID")]
ResourceIdNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "Merchant connector account does not exist in our records")]
MerchantConnectorAccountNotFound { id: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "invalid_request", message = "The merchant connector account is disabled")]
MerchantConnectorAccountDisabled,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such mandate")]
MandateNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such API key")]
ApiKeyNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such payout")]
PayoutNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "resource_missing", message = "No such event")]
EventNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "Duplicate payout request")]
DuplicatePayout { payout_id: id_type::PayoutId },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "parameter_missing", message = "Return url is not available")]
ReturnUrlUnavailable,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate merchant account")]
DuplicateMerchantAccount,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")]
DuplicateMerchantConnectorAccount {
profile_id: String,
connector_label: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "token_already_used", message = "duplicate payment method")]
DuplicatePaymentMethod,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "" , message = "deserialization failed: {error_message}")]
SerdeQsError {
error_message: String,
param: Option<String>,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_intent_invalid_parameter" , message = "The client_secret provided does not match the client_secret associated with the PaymentIntent.")]
PaymentIntentInvalidParameter { param: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_05",
message = "{message}"
)]
InvalidRequestData { message: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "IR_10",
message = "{message}"
)]
PreconditionFailed { message: String },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "The payment has not succeeded yet"
)]
PaymentFailed,
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "The verification did not succeeded"
)]
VerificationFailed { data: Option<serde_json::Value> },
#[error(
error_type = StripeErrorType::InvalidRequestError, code = "",
message = "Reached maximum refund attempts"
)]
MaximumRefundCount,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID.")]
DuplicateMandate,
#[error(error_type= StripeErrorType::InvalidRequestError, code = "", message = "Successful payment not found for the given payment id")]
SuccessfulPaymentNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Address does not exist in our records.")]
AddressNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "This PaymentIntent could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}.")]
PaymentIntentUnexpectedState {
current_flow: String,
field_name: String,
current_value: String,
states: String,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")]
PaymentIntentMandateInvalid { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id already exists in our records.")]
DuplicatePayment { payment_id: id_type::PaymentId },
#[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")]
ExternalConnectorError {
code: String,
message: String,
connector: String,
status_code: u16,
},
#[error(error_type = StripeErrorType::CardError, code = "", message = "{code}: {message}")]
PaymentBlockedError {
code: u16,
message: String,
status: String,
reason: String,
},
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")]
IncorrectConnectorNameGiven,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "No such {object}: '{id}'")]
ResourceMissing { object: String, id: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File validation failed")]
FileValidationFailed,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not found in the request")]
MissingFile,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File puropse not found in the request")]
MissingFilePurpose,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File content type not found")]
MissingFileContentType,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Dispute id not found in the request")]
MissingDisputeId,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File does not exists in our records")]
FileNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "File not available")]
FileNotAvailable,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Not Supported because provider is not Router")]
FileProviderNotSupported,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "There was an issue with processing webhooks")]
WebhookProcessingError,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "payment_method_unactivated", message = "The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.")]
PaymentMethodUnactivated,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "{message}")]
HyperswitchUnprocessableEntity { message: String },
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "{message}")]
CurrencyNotSupported { message: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Payment Link does not exist in our records")]
PaymentLinkNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")]
LockTimeout,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")]
InvalidConnectorConfiguration { config: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")]
CurrencyConversionFailed,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
PaymentMethodDeleteFailed,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Extended card info does not exist")]
ExtendedCardInfoNotFound,
#[error(error_type = StripeErrorType::InvalidRequestError, code = "not_configured", message = "{message}")]
LinkConfigurationError { message: String },
#[error(error_type = StripeErrorType::ConnectorError, code = "CE", message = "{reason} as data mismatched for {field_names}")]
IntegrityCheckFailed {
reason: String,
field_names: String,
connector_transaction_id: Option<String>,
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_28", message = "Invalid tenant")]
InvalidTenant,
#[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert amount to {amount_type} type")]
AmountConversionFailed { amount_type: &'static str },
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Bad Request")]
PlatformBadRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Platform Unauthorized Request")]
PlatformUnauthorizedRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Connected Bad Request")]
ConnectedBadRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Connected Unauthorized Request")]
ConnectedUnauthorizedRequest,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Profile Acquirer not found")]
ProfileAcquirerNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "Subscription Error", message = "Subscription operation: {operation} failed with connector")]
SubscriptionError { operation: String },
// [#216]: https://github.com/juspay/hyperswitch/issues/216
// Implement the remaining stripe error codes
/*
AccountCountryInvalidAddress,
AccountErrorCountryChangeRequiresAdditionalSteps,
AccountInformationMismatch,
AccountInvalid,
AccountNumberInvalid,
AcssDebitSessionIncomplete,
AlipayUpgradeRequired,
AmountTooLarge,
AmountTooSmall,
ApiKeyExpired,
AuthenticationRequired,
BalanceInsufficient,
BankAccountBadRoutingNumbers,
BankAccountDeclined,
BankAccountExists,
BankAccountUnusable,
BankAccountUnverified,
BankAccountVerificationFailed,
BillingInvalidMandate,
BitcoinUpgradeRequired,
CardDeclineRateLimitExceeded,
CardDeclined,
CardholderPhoneNumberRequired,
ChargeAlreadyCaptured,
ChargeAlreadyRefunded,
ChargeDisputed,
ChargeExceedsSourceLimit,
ChargeExpiredForCapture,
ChargeInvalidParameter,
ClearingCodeUnsupported,
CountryCodeInvalid,
CountryUnsupported,
CouponExpired,
CustomerMaxPaymentMethods,
CustomerMaxSubscriptions,
DebitNotAuthorized,
EmailInvalid,
ExpiredCard,
IdempotencyKeyInUse,
IncorrectAddress,
IncorrectCvc,
IncorrectNumber,
IncorrectZip,
InstantPayoutsConfigDisabled,
InstantPayoutsCurrencyDisabled,
InstantPayoutsLimitExceeded,
InstantPayoutsUnsupported,
InsufficientFunds,
IntentInvalidState,
IntentVerificationMethodMissing,
InvalidCardType,
InvalidCharacters,
InvalidChargeAmount,
InvalidCvc,
InvalidExpiryMonth,
InvalidExpiryYear,
InvalidNumber,
InvalidSourceUsage,
InvoiceNoCustomerLineItems,
InvoiceNoPaymentMethodTypes,
InvoiceNoSubscriptionLineItems,
InvoiceNotEditable,
InvoiceOnBehalfOfNotEditable,
InvoicePaymentIntentRequiresAction,
InvoiceUpcomingNone,
LivemodeMismatch,
LockTimeout,
Missing,
NoAccount,
NotAllowedOnStandardAccount,
OutOfInventory,
ParameterInvalidEmpty,
ParameterInvalidInteger,
ParameterInvalidStringBlank,
ParameterInvalidStringEmpty,
ParametersExclusive,
PaymentIntentActionRequired,
PaymentIntentIncompatiblePaymentMethod,
PaymentIntentInvalidParameter,
PaymentIntentKonbiniRejectedConfirmationNumber,
PaymentIntentPaymentAttemptExpired,
PaymentIntentUnexpectedState,
PaymentMethodBankAccountAlreadyVerified,
PaymentMethodBankAccountBlocked,
PaymentMethodBillingDetailsAddressMissing,
PaymentMethodCurrencyMismatch,
PaymentMethodInvalidParameter,
PaymentMethodInvalidParameterTestmode,
PaymentMethodMicrodepositFailed,
PaymentMethodMicrodepositVerificationAmountsInvalid,
PaymentMethodMicrodepositVerificationAmountsMismatch,
PaymentMethodMicrodepositVerificationAttemptsExceeded,
PaymentMethodMicrodepositVerificationDescriptorCodeMismatch,
PaymentMethodMicrodepositVerificationTimeout,
PaymentMethodProviderDecline,
PaymentMethodProviderTimeout,
PaymentMethodUnexpectedState,
PaymentMethodUnsupportedType,
PayoutsNotAllowed,
PlatformAccountRequired,
PlatformApiKeyExpired,
PostalCodeInvalid,
ProcessingError,
ProductInactive,
RateLimit,
ReferToCustomer,
RefundDisputedPayment,
ResourceAlreadyExists,
ResourceMissing,
ReturnIntentAlreadyProcessed,
RoutingNumberInvalid,
SecretKeyRequired,
SepaUnsupportedAccount,
SetupAttemptFailed,
SetupIntentAuthenticationFailure,
SetupIntentInvalidParameter,
SetupIntentSetupAttemptExpired,
SetupIntentUnexpectedState,
ShippingCalculationFailed,
SkuInactive,
StateUnsupported,
StatusTransitionInvalid,
TaxIdInvalid,
TaxesCalculationFailed,
TerminalLocationCountryUnsupported,
TestmodeChargesOnly,
TlsVersionUnsupported,
TokenInUse,
TransferSourceBalanceParametersMismatch,
TransfersNotAllowed,
*/
}
impl ::core::fmt::Display for StripeErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{{\"error\": {}}}",
serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
)
}
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::enum_variant_names)]
pub enum StripeErrorType {
ApiError,
CardError,
InvalidRequestError,
ConnectorError,
HyperswitchError,
}
impl From<errors::ApiErrorResponse> for StripeErrorCode {
fn from(value: errors::ApiErrorResponse) -> Self {
match value {
errors::ApiErrorResponse::Unauthorized
| errors::ApiErrorResponse::InvalidJwtToken
| errors::ApiErrorResponse::InvalidBasicAuth
| errors::ApiErrorResponse::GenericUnauthorized { .. }
| errors::ApiErrorResponse::AccessForbidden { .. }
| errors::ApiErrorResponse::InvalidCookie
| errors::ApiErrorResponse::InvalidEphemeralKey
| errors::ApiErrorResponse::InvalidPaymentIdProvided { .. }
| errors::ApiErrorResponse::CookieNotFound => Self::Unauthorized,
errors::ApiErrorResponse::InvalidRequestUrl
| errors::ApiErrorResponse::InvalidHttpMethod
| errors::ApiErrorResponse::InvalidCardIin
| errors::ApiErrorResponse::InvalidCardIinLength => Self::InvalidRequestUrl,
errors::ApiErrorResponse::MissingRequiredField { field_name } => {
Self::ParameterMissing {
field_name: field_name.to_string(),
param: field_name.to_string(),
}
}
errors::ApiErrorResponse::UnprocessableEntity { message } => {
Self::HyperswitchUnprocessableEntity { message }
}
errors::ApiErrorResponse::MissingRequiredFields { field_names } => {
// Instead of creating a new error variant in StripeErrorCode for MissingRequiredFields, converted vec<&str> to String
Self::ParameterMissing {
field_name: field_names.clone().join(", "),
param: field_names.clone().join(", "),
}
}
errors::ApiErrorResponse::GenericNotFoundError { message } => {
Self::GenericNotFoundError { message }
}
errors::ApiErrorResponse::GenericDuplicateError { message } => {
Self::GenericDuplicateError { message }
}
// parameter unknown, invalid request error // actually if we type wrong values in address we get this error. Stripe throws parameter unknown. I don't know if stripe is validating email and stuff
errors::ApiErrorResponse::InvalidDataFormat {
field_name,
expected_format,
} => Self::ParameterUnknown {
field_name,
expected_format,
},
errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount => {
Self::RefundAmountExceedsPaymentAmount {
param: "amount".to_owned(),
}
}
errors::ApiErrorResponse::PaymentAuthorizationFailed { data }
| errors::ApiErrorResponse::PaymentAuthenticationFailed { data } => {
Self::PaymentIntentAuthenticationFailure { data }
}
errors::ApiErrorResponse::VerificationFailed { data } => {
Self::VerificationFailed { data }
}
errors::ApiErrorResponse::PaymentCaptureFailed { data } => {
Self::PaymentIntentPaymentAttemptFailed { data }
}
errors::ApiErrorResponse::DisputeFailed { data } => Self::DisputeFailed { data },
errors::ApiErrorResponse::InvalidCardData { data: _ } => Self::InvalidCardType, // Maybe it is better to de generalize this router error
errors::ApiErrorResponse::CardExpired { data: _ } => Self::ExpiredCard,
errors::ApiErrorResponse::RefundNotPossible { connector: _ } => Self::RefundFailed,
errors::ApiErrorResponse::RefundFailed { data: _ } => Self::RefundFailed, // Nothing at stripe to map
errors::ApiErrorResponse::PayoutFailed { data: _ } => Self::PayoutFailed,
errors::ApiErrorResponse::ExternalVaultFailed => Self::ExternalVaultFailed,
errors::ApiErrorResponse::MandateUpdateFailed
| errors::ApiErrorResponse::MandateSerializationFailed
| errors::ApiErrorResponse::MandateDeserializationFailed
| errors::ApiErrorResponse::InternalServerError
| errors::ApiErrorResponse::HealthCheckError { .. } => Self::InternalServerError, // not a stripe code
errors::ApiErrorResponse::ExternalConnectorError {
code,
message,
connector,
status_code,
..
} => Self::ExternalConnectorError {
code,
message,
connector,
status_code,
},
errors::ApiErrorResponse::IncorrectConnectorNameGiven => {
Self::IncorrectConnectorNameGiven
}
errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code
errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code
errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code
errors::ApiErrorResponse::DuplicateConfig => Self::DuplicateConfig, // not a stripe code
errors::ApiErrorResponse::DuplicateRefundRequest => Self::DuplicateRefundRequest,
errors::ApiErrorResponse::DuplicatePayout { payout_id } => {
Self::DuplicatePayout { payout_id }
}
errors::ApiErrorResponse::RefundNotFound => Self::RefundNotFound,
errors::ApiErrorResponse::CustomerNotFound => Self::CustomerNotFound,
errors::ApiErrorResponse::PaymentNotFound => Self::PaymentNotFound,
errors::ApiErrorResponse::PaymentMethodNotFound => Self::PaymentMethodNotFound,
errors::ApiErrorResponse::ClientSecretNotGiven
| errors::ApiErrorResponse::ClientSecretExpired => Self::ClientSecretNotFound,
errors::ApiErrorResponse::MerchantAccountNotFound => Self::MerchantAccountNotFound,
errors::ApiErrorResponse::PaymentLinkNotFound => Self::PaymentLinkNotFound,
errors::ApiErrorResponse::ResourceIdNotFound => Self::ResourceIdNotFound,
errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id } => {
Self::MerchantConnectorAccountNotFound { id }
}
errors::ApiErrorResponse::MandateNotFound => Self::MandateNotFound,
errors::ApiErrorResponse::ApiKeyNotFound => Self::ApiKeyNotFound,
errors::ApiErrorResponse::PayoutNotFound => Self::PayoutNotFound,
errors::ApiErrorResponse::EventNotFound => Self::EventNotFound,
errors::ApiErrorResponse::MandateValidationFailed { reason } => {
Self::PaymentIntentMandateInvalid { message: reason }
}
errors::ApiErrorResponse::ReturnUrlUnavailable => Self::ReturnUrlUnavailable,
errors::ApiErrorResponse::DuplicateMerchantAccount => Self::DuplicateMerchantAccount,
errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {
profile_id,
connector_label,
} => Self::DuplicateMerchantConnectorAccount {
profile_id,
connector_label,
},
errors::ApiErrorResponse::DuplicatePaymentMethod => Self::DuplicatePaymentMethod,
errors::ApiErrorResponse::PaymentBlockedError {
code,
message,
status,
reason,
} => Self::PaymentBlockedError {
code,
message,
status,
reason,
},
errors::ApiErrorResponse::ClientSecretInvalid => Self::PaymentIntentInvalidParameter {
param: "client_secret".to_owned(),
},
errors::ApiErrorResponse::InvalidRequestData { message } => {
Self::InvalidRequestData { message }
}
errors::ApiErrorResponse::PreconditionFailed { message } => {
Self::PreconditionFailed { message }
}
errors::ApiErrorResponse::InvalidDataValue { field_name } => Self::ParameterMissing {
field_name: field_name.to_string(),
param: field_name.to_string(),
},
errors::ApiErrorResponse::MaximumRefundCount => Self::MaximumRefundCount,
errors::ApiErrorResponse::PaymentNotSucceeded => Self::PaymentFailed,
errors::ApiErrorResponse::DuplicateMandate => Self::DuplicateMandate,
errors::ApiErrorResponse::SuccessfulPaymentNotFound => Self::SuccessfulPaymentNotFound,
errors::ApiErrorResponse::AddressNotFound => Self::AddressNotFound,
errors::ApiErrorResponse::NotImplemented { .. } => Self::Unauthorized,
errors::ApiErrorResponse::FlowNotSupported { .. } => Self::InternalServerError,
errors::ApiErrorResponse::MandatePaymentDataMismatch { .. } => Self::PlatformBadRequest,
errors::ApiErrorResponse::MaxFieldLengthViolated { .. } => Self::PlatformBadRequest,
errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow,
field_name,
current_value,
states,
} => Self::PaymentIntentUnexpectedState {
current_flow,
field_name,
current_value,
states,
},
errors::ApiErrorResponse::DuplicatePayment { payment_id } => {
Self::DuplicatePayment { payment_id }
}
errors::ApiErrorResponse::DisputeNotFound { dispute_id } => Self::ResourceMissing {
object: "dispute".to_owned(),
id: dispute_id,
},
errors::ApiErrorResponse::AuthenticationNotFound { id } => Self::ResourceMissing {
object: "authentication".to_owned(),
id,
},
errors::ApiErrorResponse::ProfileNotFound { id } => Self::ResourceMissing {
object: "business_profile".to_owned(),
id,
},
errors::ApiErrorResponse::PollNotFound { id } => Self::ResourceMissing {
object: "poll".to_owned(),
id,
},
errors::ApiErrorResponse::DisputeStatusValidationFailed { reason: _ } => {
Self::InternalServerError
}
errors::ApiErrorResponse::FileValidationFailed { .. } => Self::FileValidationFailed,
errors::ApiErrorResponse::MissingFile => Self::MissingFile,
errors::ApiErrorResponse::MissingFilePurpose => Self::MissingFilePurpose,
errors::ApiErrorResponse::MissingFileContentType => Self::MissingFileContentType,
errors::ApiErrorResponse::MissingDisputeId => Self::MissingDisputeId,
errors::ApiErrorResponse::FileNotFound => Self::FileNotFound,
errors::ApiErrorResponse::FileNotAvailable => Self::FileNotAvailable,
errors::ApiErrorResponse::MerchantConnectorAccountDisabled => {
Self::MerchantConnectorAccountDisabled
}
errors::ApiErrorResponse::NotSupported { .. } => Self::InternalServerError,
errors::ApiErrorResponse::CurrencyNotSupported { message } => {
Self::CurrencyNotSupported { message }
}
errors::ApiErrorResponse::FileProviderNotSupported { .. } => {
Self::FileProviderNotSupported
}
errors::ApiErrorResponse::WebhookBadRequest
| errors::ApiErrorResponse::WebhookResourceNotFound
| errors::ApiErrorResponse::WebhookProcessingFailure
| errors::ApiErrorResponse::WebhookAuthenticationFailed
| errors::ApiErrorResponse::WebhookUnprocessableEntity
| errors::ApiErrorResponse::WebhookInvalidMerchantSecret => {
Self::WebhookProcessingError
}
errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration => {
Self::PaymentMethodUnactivated
}
errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/refunds.rs | crates/router/src/compatibility/stripe/refunds.rs | pub mod types;
use actix_web::{web, HttpRequest, HttpResponse};
use error_stack::report;
use router_env::{instrument, tracing, Flow, Tag};
use crate::{
compatibility::{stripe::errors, wrap},
core::{api_locking, refunds},
logger, routes,
services::{api, authentication as auth},
types::api::refunds as refund_types,
};
#[instrument(skip_all, fields(flow = ?Flow::RefundsCreate, payment_id))]
pub async fn refund_create(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let payload: types::StripeCreateRefundRequest = match qs_config
.deserialize_bytes(&form_payload)
.map_err(|err| report!(errors::StripeErrorCode::from(err)))
{
Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err),
};
tracing::Span::current().record("payment_id", payload.payment_intent.get_string_repr());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload);
let create_refund_req: refund_types::RefundRequest = payload.into();
let flow = Flow::RefundsCreate;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeRefundResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
create_refund_req,
|state, auth: auth::AuthenticationData, req, _| {
refunds::refund_create_core(state, auth.platform, None, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow))]
pub async fn refund_retrieve_with_gateway_creds(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let refund_request: refund_types::RefundsRetrieveRequest = match qs_config
.deserialize_bytes(&form_payload)
.map_err(|err| report!(errors::StripeErrorCode::from(err)))
{
Ok(payload) => payload,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = match refund_request.force_sync {
Some(true) => Flow::RefundsRetrieveForceSync,
_ => Flow::RefundsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeRefundResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
refunds::refund_response_wrapper(
state,
auth.platform,
None,
refund_request,
refunds::refund_retrieve_core_with_refund_id,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::RefundsRetrieveForceSync))]
pub async fn refund_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let refund_request = refund_types::RefundsRetrieveRequest {
refund_id: path.into_inner(),
force_sync: Some(true),
merchant_connector_details: None,
all_keys_required: None,
};
let flow = Flow::RefundsRetrieveForceSync;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeRefundResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
refund_request,
|state, auth: auth::AuthenticationData, refund_request, _| {
refunds::refund_response_wrapper(
state,
auth.platform,
None,
refund_request,
refunds::refund_retrieve_core_with_refund_id,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::RefundsUpdate))]
pub async fn refund_update(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<String>,
form_payload: web::Form<types::StripeUpdateRefundRequest>,
) -> HttpResponse {
let mut payload = form_payload.into_inner();
payload.refund_id = path.into_inner();
let create_refund_update_req: refund_types::RefundUpdateRequest = payload.into();
let flow = Flow::RefundsUpdate;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeRefundResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
create_refund_update_req,
|state, auth: auth::AuthenticationData, req, _| {
refunds::refund_update_core(state, auth.platform, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/customers.rs | crates/router/src/compatibility/stripe/customers.rs | pub mod types;
#[cfg(feature = "v1")]
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(feature = "v1")]
use common_utils::id_type;
#[cfg(feature = "v1")]
use error_stack::report;
#[cfg(feature = "v1")]
use router_env::{instrument, tracing, Flow};
#[cfg(feature = "v1")]
use crate::{
compatibility::{stripe::errors, wrap},
core::{api_locking, customers, payment_methods::cards},
routes,
services::{api, authentication as auth},
types::api::{customers as customer_types, payment_methods},
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
pub async fn customer_create(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let payload: types::CreateCustomerRequest = 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 create_cust_req: customer_types::CustomerRequest = payload.into();
let flow = Flow::CustomersCreate;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::CreateCustomerResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
create_cust_req,
|state, auth: auth::AuthenticationData, req, _| {
customers::create_customer(state, auth.platform.get_provider().clone(), req, None)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersRetrieve))]
pub async fn customer_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
let customer_id = path.into_inner();
let flow = Flow::CustomersRetrieve;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::CustomerRetrieveResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
customers::retrieve_customer(
state,
auth.platform.get_provider().clone(),
None,
customer_id,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersUpdate))]
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, _| {
customers::update_customer(
state,
auth.platform.get_provider().clone(),
request_internal,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomersDelete))]
pub async fn customer_delete(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
let customer_id = path.into_inner();
let flow = Flow::CustomersDelete;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::CustomerDeleteResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
customers::delete_customer(state, auth.platform.get_provider().clone(), customer_id)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::CustomerPaymentMethodsList))]
pub async fn list_customer_payment_method_api(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
json_payload: web::Query<payment_methods::PaymentMethodListRequest>,
) -> HttpResponse {
let payload = json_payload.into_inner();
let customer_id = path.into_inner();
let flow = Flow::CustomerPaymentMethodsList;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::CustomerPaymentMethodListResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
cards::do_list_customer_pm_fetch_customer_if_not_passed(
state,
auth.platform,
Some(req),
Some(&customer_id),
None,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: true,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/setup_intents.rs | crates/router/src/compatibility/stripe/setup_intents.rs | pub mod types;
#[cfg(feature = "v1")]
use actix_web::{web, HttpRequest, HttpResponse};
#[cfg(feature = "v1")]
use api_models::payments as payment_types;
#[cfg(feature = "v1")]
use error_stack::report;
#[cfg(feature = "v1")]
use router_env::{instrument, tracing, Flow};
#[cfg(feature = "v1")]
use crate::{
compatibility::{
stripe::{errors, payment_intents::types as stripe_payment_types},
wrap,
},
core::{api_locking, payments},
routes,
services::{api, authentication as auth},
types::api as api_types,
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate))]
pub async fn setup_intents_create(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let payload: types::StripeSetupIntentRequest = 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 create_payment_req: payment_types::PaymentsRequest =
match payment_types::PaymentsRequest::try_from(payload) {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = Flow::PaymentsCreate;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeSetupIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
create_payment_req,
|state, auth: auth::AuthenticationData, req, req_state| {
payments::payments_core::<
api_types::SetupMandate,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::SetupMandate>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentCreate,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))]
pub async fn setup_intents_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
query_payload: web::Query<stripe_payment_types::StripePaymentRetrieveBody>,
) -> HttpResponse {
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()),
merchant_id: None,
force_sync: true,
connector: None,
param: None,
merchant_connector_details: None,
client_secret: query_payload.client_secret.clone(),
expand_attempts: None,
expand_captures: None,
all_keys_required: None,
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = Flow::PaymentsRetrieveForceSync;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeSetupIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, payload, req_state| {
payments::payments_core::<
api_types::PSync,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentStatus,
payload,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))]
pub async fn setup_intents_update(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let setup_id = path.into_inner();
let stripe_payload: types::StripeSetupIntentRequest = 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 mut payload: payment_types::PaymentsRequest =
match payment_types::PaymentsRequest::try_from(stripe_payload) {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id));
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = Flow::PaymentsUpdate;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeSetupIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
payments::payments_core::<
api_types::SetupMandate,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::SetupMandate>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentUpdate,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm))]
pub async fn setup_intents_confirm(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let setup_id = path.into_inner();
let stripe_payload: types::StripeSetupIntentRequest = 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 mut payload: payment_types::PaymentsRequest =
match payment_types::PaymentsRequest::try_from(stripe_payload) {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(setup_id));
payload.confirm = Some(true);
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = Flow::PaymentsConfirm;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripeSetupIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
payments::payments_core::<
api_types::SetupMandate,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::SetupMandate>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentConfirm,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
api_locking::LockAction::NotApplicable,
))
.await
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/webhooks.rs | crates/router/src/compatibility/stripe/webhooks.rs | #[cfg(feature = "payouts")]
use api_models::payouts as payout_models;
use api_models::{
enums::{Currency, DisputeStatus, MandateStatus},
webhooks::{self as api},
};
use common_utils::{crypto::SignMessage, date_time, ext_traits::Encode};
#[cfg(feature = "payouts")]
use common_utils::{
id_type,
pii::{self, Email},
};
use error_stack::ResultExt;
use router_env::logger;
use serde::Serialize;
use super::{
payment_intents::types::StripePaymentIntentResponse, refunds::types::StripeRefundResponse,
};
use crate::{
core::{
errors,
webhooks::types::{OutgoingWebhookPayloadWithSignature, OutgoingWebhookType},
},
headers,
services::request::Maskable,
};
#[derive(Serialize, Debug)]
pub struct StripeOutgoingWebhook {
id: String,
#[serde(rename = "type")]
stype: &'static str,
object: &'static str,
data: StripeWebhookObject,
created: u64,
// api_version: "2019-11-05", // not used
}
impl OutgoingWebhookType for StripeOutgoingWebhook {
fn get_outgoing_webhooks_signature(
&self,
payment_response_hash_key: Option<impl AsRef<[u8]>>,
) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError> {
let timestamp = self.created;
let payment_response_hash_key = payment_response_hash_key
.ok_or(errors::WebhooksFlowError::MerchantConfigNotFound)
.attach_printable("For stripe compatibility payment_response_hash_key is mandatory")?;
let webhook_signature_payload = self
.encode_to_string_of_json()
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("failed encoding outgoing webhook payload")?;
let new_signature_payload = format!("{timestamp}.{webhook_signature_payload}");
let v1 = hex::encode(
common_utils::crypto::HmacSha256::sign_message(
&common_utils::crypto::HmacSha256,
payment_response_hash_key.as_ref(),
new_signature_payload.as_bytes(),
)
.change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed)
.attach_printable("Failed to sign the message")?,
);
let t = timestamp;
let signature = Some(format!("t={t},v1={v1}"));
Ok(OutgoingWebhookPayloadWithSignature {
payload: webhook_signature_payload.into(),
signature,
})
}
fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String) {
header.push((
headers::STRIPE_COMPATIBLE_WEBHOOK_SIGNATURE.to_string(),
signature.into(),
))
}
}
#[derive(Serialize, Debug)]
#[serde(tag = "type", content = "object", rename_all = "snake_case")]
pub enum StripeWebhookObject {
PaymentIntent(Box<StripePaymentIntentResponse>),
Refund(StripeRefundResponse),
Dispute(StripeDisputeResponse),
Mandate(StripeMandateResponse),
#[cfg(feature = "payouts")]
Payout(StripePayoutResponse),
Subscriptions,
}
#[derive(Serialize, Debug)]
pub struct StripeDisputeResponse {
pub id: String,
pub amount: String,
pub currency: Currency,
pub payment_intent: id_type::PaymentId,
pub reason: Option<String>,
pub status: StripeDisputeStatus,
}
#[derive(Serialize, Debug)]
pub struct StripeMandateResponse {
pub mandate_id: String,
pub status: StripeMandateStatus,
pub payment_method_id: String,
pub payment_method: String,
}
#[cfg(feature = "payouts")]
#[derive(Clone, Serialize, Debug)]
pub struct StripePayoutResponse {
pub id: id_type::PayoutId,
pub amount: i64,
pub currency: String,
pub payout_type: Option<common_enums::PayoutType>,
pub status: StripePayoutStatus,
pub name: Option<masking::Secret<String>>,
pub email: Option<Email>,
pub phone: Option<masking::Secret<String>>,
pub phone_country_code: Option<String>,
pub created: Option<i64>,
pub metadata: Option<pii::SecretSerdeValue>,
pub entity_type: common_enums::PayoutEntityType,
pub recurring: bool,
pub error_message: Option<String>,
pub error_code: Option<String>,
}
#[cfg(feature = "payouts")]
#[derive(Clone, Serialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripePayoutStatus {
PayoutSuccess,
PayoutFailure,
PayoutProcessing,
PayoutCancelled,
PayoutInitiated,
PayoutExpired,
PayoutReversed,
}
#[cfg(feature = "payouts")]
impl From<common_enums::PayoutStatus> for StripePayoutStatus {
fn from(status: common_enums::PayoutStatus) -> Self {
match status {
common_enums::PayoutStatus::Success => Self::PayoutSuccess,
common_enums::PayoutStatus::Failed => Self::PayoutFailure,
common_enums::PayoutStatus::Cancelled => Self::PayoutCancelled,
common_enums::PayoutStatus::Initiated => Self::PayoutInitiated,
common_enums::PayoutStatus::Expired => Self::PayoutExpired,
common_enums::PayoutStatus::Reversed => Self::PayoutReversed,
common_enums::PayoutStatus::Pending
| common_enums::PayoutStatus::Ineligible
| common_enums::PayoutStatus::RequiresCreation
| common_enums::PayoutStatus::RequiresFulfillment
| common_enums::PayoutStatus::RequiresPayoutMethodData
| common_enums::PayoutStatus::RequiresVendorAccountCreation
| common_enums::PayoutStatus::RequiresConfirmation => Self::PayoutProcessing,
}
}
}
#[cfg(feature = "payouts")]
impl From<payout_models::PayoutCreateResponse> for StripePayoutResponse {
fn from(res: payout_models::PayoutCreateResponse) -> Self {
let (name, email, phone, phone_country_code) = match res.customer {
Some(customer) => (
customer.name,
customer.email,
customer.phone,
customer.phone_country_code,
),
None => (None, None, None, None),
};
Self {
id: res.payout_id,
amount: res.amount.get_amount_as_i64(),
currency: res.currency.to_string(),
payout_type: res.payout_type,
status: StripePayoutStatus::from(res.status),
name,
email,
phone,
phone_country_code,
created: res.created.map(|t| t.assume_utc().unix_timestamp()),
metadata: res.metadata,
entity_type: res.entity_type,
recurring: res.recurring,
error_message: res.error_message,
error_code: res.error_code,
}
}
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripeMandateStatus {
Active,
Inactive,
Pending,
}
#[derive(Serialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripeDisputeStatus {
WarningNeedsResponse,
WarningUnderReview,
WarningClosed,
NeedsResponse,
UnderReview,
ChargeRefunded,
Won,
Lost,
}
impl From<api_models::disputes::DisputeResponse> for StripeDisputeResponse {
fn from(res: api_models::disputes::DisputeResponse) -> Self {
Self {
id: res.dispute_id,
amount: res.amount.to_string(),
currency: res.currency,
payment_intent: res.payment_id,
reason: res.connector_reason,
status: StripeDisputeStatus::from(res.dispute_status),
}
}
}
impl From<api_models::mandates::MandateResponse> for StripeMandateResponse {
fn from(res: api_models::mandates::MandateResponse) -> Self {
Self {
mandate_id: res.mandate_id,
payment_method: res.payment_method,
payment_method_id: res.payment_method_id,
status: StripeMandateStatus::from(res.status),
}
}
}
impl From<MandateStatus> for StripeMandateStatus {
fn from(status: MandateStatus) -> Self {
match status {
MandateStatus::Active => Self::Active,
MandateStatus::Inactive | MandateStatus::Revoked => Self::Inactive,
MandateStatus::Pending => Self::Pending,
}
}
}
impl From<DisputeStatus> for StripeDisputeStatus {
fn from(status: DisputeStatus) -> Self {
match status {
DisputeStatus::DisputeOpened => Self::WarningNeedsResponse,
DisputeStatus::DisputeExpired => Self::Lost,
DisputeStatus::DisputeAccepted => Self::Lost,
DisputeStatus::DisputeCancelled => Self::WarningClosed,
DisputeStatus::DisputeChallenged => Self::WarningUnderReview,
DisputeStatus::DisputeWon => Self::Won,
DisputeStatus::DisputeLost => Self::Lost,
}
}
}
fn get_stripe_event_type(event_type: api_models::enums::EventType) -> &'static str {
match event_type {
api_models::enums::EventType::PaymentSucceeded => "payment_intent.succeeded",
api_models::enums::EventType::PaymentFailed => "payment_intent.payment_failed",
api_models::enums::EventType::PaymentProcessing
| api_models::enums::EventType::PaymentPartiallyAuthorized => "payment_intent.processing",
api_models::enums::EventType::PaymentCancelled
| api_models::enums::EventType::PaymentCancelledPostCapture
| api_models::enums::EventType::PaymentExpired => "payment_intent.canceled",
// the below are not really stripe compatible because stripe doesn't provide this
api_models::enums::EventType::ActionRequired => "action.required",
api_models::enums::EventType::RefundSucceeded => "refund.succeeded",
api_models::enums::EventType::RefundFailed => "refund.failed",
api_models::enums::EventType::DisputeOpened => "dispute.failed",
api_models::enums::EventType::DisputeExpired => "dispute.expired",
api_models::enums::EventType::DisputeAccepted => "dispute.accepted",
api_models::enums::EventType::DisputeCancelled => "dispute.cancelled",
api_models::enums::EventType::DisputeChallenged => "dispute.challenged",
api_models::enums::EventType::DisputeWon => "dispute.won",
api_models::enums::EventType::DisputeLost => "dispute.lost",
api_models::enums::EventType::MandateActive => "mandate.active",
api_models::enums::EventType::MandateRevoked => "mandate.revoked",
// as per this doc https://stripe.com/docs/api/events/types#event_types-payment_intent.amount_capturable_updated
api_models::enums::EventType::PaymentAuthorized => {
"payment_intent.amount_capturable_updated"
}
// stripe treats partially captured payments as succeeded.
api_models::enums::EventType::PaymentCaptured => "payment_intent.succeeded",
api_models::enums::EventType::PayoutSuccess => "payout.paid",
api_models::enums::EventType::PayoutFailed => "payout.failed",
api_models::enums::EventType::PayoutInitiated => "payout.created",
api_models::enums::EventType::PayoutCancelled => "payout.canceled",
api_models::enums::EventType::PayoutProcessing => "payout.created",
api_models::enums::EventType::PayoutExpired => "payout.failed",
api_models::enums::EventType::PayoutReversed => "payout.reconciliation_completed",
api_models::enums::EventType::InvoicePaid => "invoice.paid",
}
}
impl From<api::OutgoingWebhook> for StripeOutgoingWebhook {
fn from(value: api::OutgoingWebhook) -> Self {
Self {
id: value.event_id,
stype: get_stripe_event_type(value.event_type),
data: StripeWebhookObject::from(value.content),
object: "event",
// put this conversion it into a function
created: u64::try_from(value.timestamp.assume_utc().unix_timestamp()).unwrap_or_else(
|error| {
logger::error!(
%error,
"incorrect value for `webhook.timestamp` provided {}", value.timestamp
);
// Current timestamp converted to Unix timestamp should have a positive value
// for many years to come
u64::try_from(date_time::now().assume_utc().unix_timestamp())
.unwrap_or_default()
},
),
}
}
}
impl From<api::OutgoingWebhookContent> for StripeWebhookObject {
fn from(value: api::OutgoingWebhookContent) -> Self {
match value {
api::OutgoingWebhookContent::PaymentDetails(payment) => {
Self::PaymentIntent(Box::new((*payment).into()))
}
api::OutgoingWebhookContent::RefundDetails(refund) => Self::Refund((*refund).into()),
api::OutgoingWebhookContent::DisputeDetails(dispute) => {
Self::Dispute((*dispute).into())
}
api::OutgoingWebhookContent::MandateDetails(mandate) => {
Self::Mandate((*mandate).into())
}
#[cfg(feature = "payouts")]
api::OutgoingWebhookContent::PayoutDetails(payout) => Self::Payout((*payout).into()),
api_models::webhooks::OutgoingWebhookContent::SubscriptionDetails(_) => {
Self::Subscriptions
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/payment_intents.rs | crates/router/src/compatibility/stripe/payment_intents.rs | pub mod types;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::payments as payment_types;
#[cfg(feature = "v1")]
use error_stack::report;
#[cfg(feature = "v1")]
use router_env::Tag;
use router_env::{instrument, tracing, Flow};
use crate::{
compatibility::{stripe::errors, wrap},
core::payments,
routes::{self},
services::{api, authentication as auth},
};
#[cfg(feature = "v1")]
use crate::{
core::api_locking::GetLockingInput, logger, routes::payments::get_or_generate_payment_id,
types::api as api_types,
};
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCreate, payment_id))]
pub async fn payment_intents_create(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let payload: types::StripePaymentIntentRequest = match qs_config
.deserialize_bytes(&form_payload)
.map_err(|err| report!(errors::StripeErrorCode::from(err)))
{
Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err),
};
tracing::Span::current().record(
"payment_id",
payload
.id
.as_ref()
.map(|payment_id| payment_id.get_string_repr())
.unwrap_or_default(),
);
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?payload);
let mut create_payment_req: payment_types::PaymentsRequest = match payload.try_into() {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
if let Err(err) = get_or_generate_payment_id(&mut create_payment_req) {
return api::log_and_return_error_response(err);
}
let flow = Flow::PaymentsCreate;
let locking_action = create_payment_req.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
create_payment_req,
|state, auth: auth::AuthenticationData, req, req_state| {
let eligible_connectors = req.connector.clone();
payments::payments_core::<
api_types::Authorize,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentCreate,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
eligible_connectors,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsRetrieveForceSync))]
pub async fn payment_intents_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
query_payload: web::Query<types::StripePaymentRetrieveBody>,
) -> HttpResponse {
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: api_types::PaymentIdType::PaymentIntentId(path.into_inner()),
merchant_id: None,
force_sync: true,
connector: None,
param: None,
merchant_connector_details: None,
client_secret: query_payload.client_secret.clone(),
expand_attempts: None,
expand_captures: None,
all_keys_required: None,
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = Flow::PaymentsRetrieveForceSync;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, payload, req_state| {
payments::payments_core::<
api_types::PSync,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentStatus,
payload,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow))]
pub async fn payment_intents_retrieve_with_gateway_creds(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
) -> HttpResponse {
let json_payload: payment_types::PaymentRetrieveBodyWithCredentials = match qs_config
.deserialize_bytes(&form_payload)
.map_err(|err| report!(errors::StripeErrorCode::from(err)))
{
Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err),
};
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
merchant_connector_details: json_payload.merchant_connector_details.clone(),
..Default::default()
};
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentStatus,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsUpdate))]
pub async fn payment_intents_update(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let payment_id = path.into_inner();
let stripe_payload: types::StripePaymentIntentRequest = 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 mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id));
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = Flow::PaymentsUpdate;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
let eligible_connectors = req.connector.clone();
payments::payments_core::<
api_types::Authorize,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentUpdate,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
eligible_connectors,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))]
pub async fn payment_intents_confirm(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let payment_id = path.into_inner();
let stripe_payload: types::StripePaymentIntentRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
tracing::Span::current().record(
"payment_id",
stripe_payload.id.as_ref().map(|id| id.get_string_repr()),
);
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload);
let mut payload: payment_types::PaymentsRequest = match stripe_payload.try_into() {
Ok(req) => req,
Err(err) => return api::log_and_return_error_response(err),
};
payload.payment_id = Some(api_types::PaymentIdType::PaymentIntentId(payment_id));
payload.confirm = Some(true);
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) =
match auth::check_client_secret_and_get_auth(req.headers(), &payload, api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
let flow = Flow::PaymentsConfirm;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
let eligible_connectors = req.connector.clone();
payments::payments_core::<
api_types::Authorize,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Authorize>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentConfirm,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
eligible_connectors,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCapture, payment_id))]
pub async fn payment_intents_capture(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let stripe_payload: payment_types::PaymentsCaptureRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
tracing::Span::current().record("payment_id", stripe_payload.payment_id.get_string_repr());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload);
let payload = payment_types::PaymentsCaptureRequest {
payment_id: path.into_inner(),
..stripe_payload
};
let flow = Flow::PaymentsCapture;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth: auth::AuthenticationData, payload, req_state| {
payments::payments_core::<
api_types::Capture,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Capture>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentCapture,
payload,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
locking_action,
))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all, fields(flow = ?Flow::PaymentsCancel, payment_id))]
pub async fn payment_intents_cancel(
state: web::Data<routes::AppState>,
qs_config: web::Data<serde_qs::Config>,
req: HttpRequest,
form_payload: web::Bytes,
path: web::Path<common_utils::id_type::PaymentId>,
) -> HttpResponse {
let payment_id = path.into_inner();
let stripe_payload: types::StripePaymentCancelRequest = match qs_config
.deserialize_bytes(&form_payload)
{
Ok(p) => p,
Err(err) => {
return api::log_and_return_error_response(report!(errors::StripeErrorCode::from(err)))
}
};
tracing::Span::current().record("payment_id", payment_id.get_string_repr());
logger::info!(tag = ?Tag::CompatibilityLayerRequest, payload = ?stripe_payload);
let mut payload: payment_types::PaymentsCancelRequest = stripe_payload.into();
payload.payment_id = payment_id;
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
};
let (auth_type, auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
let flow = Flow::PaymentsCancel;
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth, req, req_state| {
payments::payments_core::<
api_types::Void,
api_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::Void>,
>(
state,
req_state,
auth.platform,
None,
payments::PaymentCancel,
req,
auth_flow,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
#[instrument(skip_all, fields(flow = ?Flow::PaymentsList))]
#[cfg(feature = "olap")]
pub async fn payment_intent_list(
state: web::Data<routes::AppState>,
req: HttpRequest,
payload: web::Query<types::StripePaymentListConstraints>,
) -> HttpResponse {
let payload = match payment_types::PaymentListConstraints::try_from(payload.into_inner()) {
Ok(p) => p,
Err(err) => return api::log_and_return_error_response(err),
};
use crate::core::api_locking;
let flow = Flow::PaymentsList;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::StripePaymentIntentListResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
payments::list_payments(state, auth.platform, None, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/refunds/types.rs | crates/router/src/compatibility/stripe/refunds/types.rs | use std::{convert::From, default::Default};
use common_utils::pii;
use serde::{Deserialize, Serialize};
use crate::types::api::{admin, refunds};
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct StripeCreateRefundRequest {
pub refund_id: Option<String>,
pub amount: Option<i64>,
pub payment_intent: common_utils::id_type::PaymentId,
pub reason: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct StripeUpdateRefundRequest {
#[serde(skip)]
pub refund_id: String,
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Clone, Serialize, PartialEq, Eq, Debug)]
pub struct StripeRefundResponse {
pub id: String,
pub amount: i64,
pub currency: String,
pub payment_intent: common_utils::id_type::PaymentId,
pub status: StripeRefundStatus,
pub created: Option<i64>,
pub metadata: pii::SecretSerdeValue,
}
#[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripeRefundStatus {
Succeeded,
Failed,
Pending,
RequiresAction,
}
impl From<StripeCreateRefundRequest> for refunds::RefundRequest {
fn from(req: StripeCreateRefundRequest) -> Self {
Self {
refund_id: req.refund_id,
amount: req.amount.map(common_utils::types::MinorUnit::new),
payment_id: req.payment_intent,
reason: req.reason,
refund_type: Some(refunds::RefundType::Instant),
metadata: req.metadata,
merchant_connector_details: req.merchant_connector_details,
..Default::default()
}
}
}
impl From<StripeUpdateRefundRequest> for refunds::RefundUpdateRequest {
fn from(req: StripeUpdateRefundRequest) -> Self {
Self {
refund_id: req.refund_id,
metadata: req.metadata,
reason: None,
}
}
}
impl From<refunds::RefundStatus> for StripeRefundStatus {
fn from(status: refunds::RefundStatus) -> Self {
match status {
refunds::RefundStatus::Succeeded => Self::Succeeded,
refunds::RefundStatus::Failed => Self::Failed,
refunds::RefundStatus::Pending => Self::Pending,
refunds::RefundStatus::Review => Self::RequiresAction,
}
}
}
impl From<refunds::RefundResponse> for StripeRefundResponse {
fn from(res: refunds::RefundResponse) -> Self {
Self {
id: res.refund_id,
amount: res.amount.get_amount_as_i64(),
currency: res.currency.to_ascii_lowercase(),
payment_intent: res.payment_id,
status: res.status.into(),
created: res.created_at.map(|t| t.assume_utc().unix_timestamp()),
metadata: res
.metadata
.unwrap_or_else(|| masking::Secret::new(serde_json::json!({}))),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/setup_intents/types.rs | crates/router/src/compatibility/stripe/setup_intents/types.rs | use std::str::FromStr;
use api_models::payments;
use common_utils::{date_time, ext_traits::StringExt, id_type, pii as secret};
use error_stack::ResultExt;
use router_env::logger;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
compatibility::stripe::{
payment_intents::types as payment_intent, refunds::types as stripe_refunds,
},
consts,
core::errors,
pii::{self, PeekInterface},
types::{
api::{self as api_types, admin, enums as api_enums},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct StripeBillingDetails {
pub address: Option<payments::AddressDetails>,
pub email: Option<pii::Email>,
pub name: Option<String>,
pub phone: Option<pii::Secret<String>>,
}
impl From<StripeBillingDetails> for payments::Address {
fn from(details: StripeBillingDetails) -> Self {
Self {
address: details.address,
phone: Some(payments::PhoneDetails {
number: details.phone,
country_code: None,
}),
email: details.email,
}
}
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct StripeCard {
pub number: cards::CardNumber,
pub exp_month: pii::Secret<String>,
pub exp_year: pii::Secret<String>,
pub cvc: pii::Secret<String>,
}
// ApplePay wallet param is not available in stripe Docs
#[derive(Serialize, PartialEq, Eq, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripeWallet {
ApplePay(payments::ApplePayWalletData),
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodType {
#[default]
Card,
Wallet,
}
impl From<StripePaymentMethodType> for api_enums::PaymentMethod {
fn from(item: StripePaymentMethodType) -> Self {
match item {
StripePaymentMethodType::Card => Self::Card,
StripePaymentMethodType::Wallet => Self::Wallet,
}
}
}
#[derive(Default, PartialEq, Eq, Deserialize, Clone)]
pub struct StripePaymentMethodData {
#[serde(rename = "type")]
pub stype: StripePaymentMethodType,
pub billing_details: Option<StripeBillingDetails>,
#[serde(flatten)]
pub payment_method_details: Option<StripePaymentMethodDetails>, // enum
pub metadata: Option<Value>,
}
#[derive(PartialEq, Eq, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodDetails {
Card(StripeCard),
Wallet(StripeWallet),
}
impl From<StripeCard> for payments::Card {
fn from(card: StripeCard) -> Self {
Self {
card_number: card.number,
card_exp_month: card.exp_month,
card_exp_year: card.exp_year,
card_holder_name: Some(masking::Secret::new("stripe_cust".to_owned())),
card_cvc: card.cvc,
card_issuer: None,
card_network: None,
bank_code: None,
card_issuing_country: None,
card_issuing_country_code: None,
card_type: None,
nick_name: None,
}
}
}
impl From<StripeWallet> for payments::WalletData {
fn from(wallet: StripeWallet) -> Self {
match wallet {
StripeWallet::ApplePay(data) => Self::ApplePay(data),
}
}
}
impl From<StripePaymentMethodDetails> for payments::PaymentMethodData {
fn from(item: StripePaymentMethodDetails) -> Self {
match item {
StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)),
StripePaymentMethodDetails::Wallet(wallet) => {
Self::Wallet(payments::WalletData::from(wallet))
}
}
}
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct Shipping {
pub address: Option<payments::AddressDetails>,
pub name: Option<String>,
pub carrier: Option<String>,
pub phone: Option<pii::Secret<String>>,
pub tracking_number: Option<pii::Secret<String>>,
}
impl From<Shipping> for payments::Address {
fn from(details: Shipping) -> Self {
Self {
address: details.address,
phone: Some(payments::PhoneDetails {
number: details.phone,
country_code: None,
}),
email: None,
}
}
}
#[derive(Default, Deserialize, Clone)]
pub struct StripeSetupIntentRequest {
pub confirm: Option<bool>,
pub customer: Option<id_type::CustomerId>,
pub connector: Option<Vec<api_enums::RoutableConnectors>>,
pub description: Option<String>,
pub currency: Option<String>,
pub payment_method_data: Option<StripePaymentMethodData>,
pub receipt_email: Option<pii::Email>,
pub return_url: Option<url::Url>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub shipping: Option<Shipping>,
pub billing_details: Option<StripeBillingDetails>,
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub metadata: Option<secret::SecretSerdeValue>,
pub client_secret: Option<pii::Secret<String>>,
pub payment_method_options: Option<payment_intent::StripePaymentMethodOptions>,
pub payment_method: Option<String>,
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
pub receipt_ipaddress: Option<String>,
pub user_agent: Option<String>,
pub mandate_data: Option<payment_intent::MandateData>,
pub connector_metadata: Option<payments::ConnectorMetadata>,
}
impl TryFrom<StripeSetupIntentRequest> for payments::PaymentsRequest {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: StripeSetupIntentRequest) -> errors::RouterResult<Self> {
let routable_connector: Option<api_enums::RoutableConnectors> =
item.connector.and_then(|v| v.into_iter().next());
let routing = routable_connector
.map(|connector| {
api_models::routing::StaticRoutingAlgorithm::Single(Box::new(
api_models::routing::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id: None,
},
))
})
.map(|r| {
serde_json::to_value(r)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("converting to routing failed")
})
.transpose()?;
let ip_address = item
.receipt_ipaddress
.map(|ip| std::net::IpAddr::from_str(ip.as_str()))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "receipt_ipaddress".to_string(),
expected_format: "127.0.0.1".to_string(),
})?;
let metadata_object = item
.metadata
.clone()
.parse_value("metadata")
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "metadata mapping failed",
})?;
let request = Ok(Self {
amount: Some(api_types::Amount::Zero),
capture_method: None,
amount_to_capture: None,
confirm: item.confirm,
customer_id: item.customer,
currency: item
.currency
.as_ref()
.map(|c| c.to_uppercase().parse_enum("currency"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "currency",
})?,
email: item.receipt_email,
name: item
.billing_details
.as_ref()
.and_then(|b| b.name.as_ref().map(|x| masking::Secret::new(x.to_owned()))),
phone: item.shipping.as_ref().and_then(|s| s.phone.clone()),
description: item.description,
return_url: item.return_url,
payment_method_data: item.payment_method_data.as_ref().and_then(|pmd| {
pmd.payment_method_details
.as_ref()
.map(|spmd| payments::PaymentMethodDataRequest {
payment_method_data: Some(payments::PaymentMethodData::from(
spmd.to_owned(),
)),
billing: pmd.billing_details.clone().map(payments::Address::from),
})
}),
payment_method: item
.payment_method_data
.as_ref()
.map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())),
shipping: item
.shipping
.as_ref()
.map(|s| payments::Address::from(s.to_owned())),
billing: item
.billing_details
.as_ref()
.map(|b| payments::Address::from(b.to_owned())),
statement_descriptor_name: item.statement_descriptor,
statement_descriptor_suffix: item.statement_descriptor_suffix,
metadata: metadata_object,
client_secret: item.client_secret.map(|s| s.peek().clone()),
setup_future_usage: item.setup_future_usage,
merchant_connector_details: item.merchant_connector_details,
routing,
authentication_type: match item.payment_method_options {
Some(pmo) => {
let payment_intent::StripePaymentMethodOptions::Card {
request_three_d_secure,
}: payment_intent::StripePaymentMethodOptions = pmo;
Some(api_enums::AuthenticationType::foreign_from(
request_three_d_secure,
))
}
None => None,
},
mandate_data: ForeignTryFrom::foreign_try_from((
item.mandate_data,
item.currency.to_owned(),
))?,
browser_info: Some(
serde_json::to_value(crate::types::BrowserInformation {
ip_address,
user_agent: item.user_agent,
..Default::default()
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("convert to browser info failed")?,
),
connector_metadata: item.connector_metadata,
..Default::default()
});
request
}
}
#[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StripeSetupStatus {
Succeeded,
Canceled,
#[default]
Processing,
RequiresAction,
RequiresPaymentMethod,
RequiresConfirmation,
}
impl From<api_enums::IntentStatus> for StripeSetupStatus {
fn from(item: api_enums::IntentStatus) -> Self {
match item {
api_enums::IntentStatus::Succeeded | api_enums::IntentStatus::PartiallyCaptured => {
Self::Succeeded
}
api_enums::IntentStatus::Failed | api_enums::IntentStatus::Expired => Self::Canceled,
api_enums::IntentStatus::Processing
| api_enums::IntentStatus::PartiallyCapturedAndProcessing
| api_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => Self::Processing,
api_enums::IntentStatus::RequiresCustomerAction => Self::RequiresAction,
api_enums::IntentStatus::RequiresMerchantAction
| api_enums::IntentStatus::Conflicted => Self::RequiresAction,
api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod,
api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation,
api_enums::IntentStatus::RequiresCapture
| api_enums::IntentStatus::PartiallyCapturedAndCapturable => {
logger::error!("Invalid status change");
Self::Canceled
}
api_enums::IntentStatus::Cancelled | api_enums::IntentStatus::CancelledPostCapture => {
Self::Canceled
}
}
}
}
#[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CancellationReason {
Duplicate,
Fraudulent,
RequestedByCustomer,
Abandoned,
}
#[derive(Debug, Deserialize, Serialize, Copy, Clone)]
pub struct StripePaymentCancelRequest {
cancellation_reason: Option<CancellationReason>,
}
impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest {
fn from(item: StripePaymentCancelRequest) -> Self {
Self {
cancellation_reason: item.cancellation_reason.map(|c| c.to_string()),
..Self::default()
}
}
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct RedirectUrl {
pub return_url: Option<String>,
pub url: Option<String>,
}
#[derive(Eq, PartialEq, serde::Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StripeNextAction {
RedirectToUrl {
redirect_to_url: RedirectUrl,
},
DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData,
},
ThirdPartySdkSessionToken {
session_token: Option<payments::SessionToken>,
},
QrCodeInformation {
image_data_url: Option<url::Url>,
display_to_timestamp: Option<i64>,
qr_code_url: Option<url::Url>,
border_color: Option<String>,
display_text: Option<String>,
},
FetchQrCodeInformation {
qr_code_fetch_url: url::Url,
},
DisplayVoucherInformation {
voucher_details: payments::VoucherNextStepData,
},
WaitScreenInformation {
display_from_timestamp: i128,
display_to_timestamp: Option<i128>,
poll_config: Option<payments::PollConfig>,
},
InvokeSdkClient {
next_action_data: payments::SdkNextActionData,
},
CollectOtp {
consent_data_required: payments::MobilePaymentConsent,
},
InvokeHiddenIframe {
iframe_data: payments::IframeData,
},
InvokeUpiIntentSdk {
sdk_uri: url::Url,
},
InvokeUpiQrFlow {
sdk_uri: url::Url,
},
}
pub(crate) fn into_stripe_next_action(
next_action: Option<payments::NextActionData>,
return_url: Option<String>,
) -> Option<StripeNextAction> {
next_action.map(|next_action_data| match next_action_data {
payments::NextActionData::RedirectToUrl { redirect_to_url } => {
StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url,
url: Some(redirect_to_url),
},
}
}
payments::NextActionData::RedirectInsidePopup { popup_url, .. } => {
StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url,
url: Some(popup_url),
},
}
}
payments::NextActionData::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details,
} => StripeNextAction::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details,
},
payments::NextActionData::ThirdPartySdkSessionToken { session_token } => {
StripeNextAction::ThirdPartySdkSessionToken { session_token }
}
payments::NextActionData::QrCodeInformation {
image_data_url,
display_to_timestamp,
qr_code_url,
display_text,
border_color,
} => StripeNextAction::QrCodeInformation {
image_data_url,
display_to_timestamp,
qr_code_url,
display_text,
border_color,
},
payments::NextActionData::FetchQrCodeInformation { qr_code_fetch_url } => {
StripeNextAction::FetchQrCodeInformation { qr_code_fetch_url }
}
payments::NextActionData::DisplayVoucherInformation { voucher_details } => {
StripeNextAction::DisplayVoucherInformation { voucher_details }
}
payments::NextActionData::WaitScreenInformation {
display_from_timestamp,
display_to_timestamp,
poll_config: _,
} => StripeNextAction::WaitScreenInformation {
display_from_timestamp,
display_to_timestamp,
poll_config: None,
},
payments::NextActionData::ThreeDsInvoke { .. } => StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url: None,
url: None,
},
},
payments::NextActionData::InvokeSdkClient { next_action_data } => {
StripeNextAction::InvokeSdkClient { next_action_data }
}
payments::NextActionData::CollectOtp {
consent_data_required,
} => StripeNextAction::CollectOtp {
consent_data_required,
},
payments::NextActionData::InvokeHiddenIframe { iframe_data } => {
StripeNextAction::InvokeHiddenIframe { iframe_data }
}
payments::NextActionData::InvokeUpiIntentSdk { sdk_uri, .. } => {
StripeNextAction::InvokeUpiIntentSdk { sdk_uri }
}
payments::NextActionData::InvokeUpiQrFlow { qr_code_url, .. } => {
StripeNextAction::InvokeUpiQrFlow {
sdk_uri: qr_code_url,
}
}
})
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct StripeSetupIntentResponse {
pub id: id_type::PaymentId,
pub object: String,
pub status: StripeSetupStatus,
pub client_secret: Option<masking::Secret<String>>,
pub metadata: Option<Value>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created: Option<time::PrimitiveDateTime>,
pub customer: Option<id_type::CustomerId>,
pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>,
pub mandate_id: Option<String>,
pub next_action: Option<StripeNextAction>,
pub last_payment_error: Option<LastPaymentError>,
pub charges: payment_intent::Charges,
pub connector_transaction_id: Option<String>,
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct LastPaymentError {
charge: Option<String>,
code: Option<String>,
decline_code: Option<String>,
message: String,
param: Option<String>,
payment_method: StripePaymentMethod,
#[serde(rename = "type")]
error_type: String,
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct StripePaymentMethod {
#[serde(rename = "id")]
payment_method_id: String,
object: &'static str,
card: Option<StripeCard>,
created: u64,
#[serde(rename = "type")]
method_type: String,
livemode: bool,
}
impl From<payments::PaymentsResponse> for StripeSetupIntentResponse {
fn from(resp: payments::PaymentsResponse) -> Self {
Self {
object: "setup_intent".to_owned(),
status: StripeSetupStatus::from(resp.status),
client_secret: resp.client_secret,
charges: payment_intent::Charges::new(),
created: resp.created,
customer: resp.customer_id,
metadata: resp.metadata,
id: resp.payment_id,
refunds: resp
.refunds
.map(|a| a.into_iter().map(Into::into).collect()),
mandate_id: resp.mandate_id,
next_action: into_stripe_next_action(resp.next_action, resp.return_url),
last_payment_error: resp.error_code.map(|code| -> LastPaymentError {
LastPaymentError {
charge: None,
code: Some(code.to_owned()),
decline_code: None,
message: resp
.error_message
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
param: None,
payment_method: StripePaymentMethod {
payment_method_id: "place_holder_id".to_string(),
object: "payment_method",
card: None,
created: u64::try_from(date_time::now().assume_utc().unix_timestamp())
.unwrap_or_default(),
method_type: "card".to_string(),
livemode: false,
},
error_type: code,
}
}),
connector_transaction_id: resp.connector_transaction_id,
}
}
}
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StripePaymentListConstraints {
pub customer: Option<id_type::CustomerId>,
pub starting_after: Option<id_type::PaymentId>,
pub ending_before: Option<id_type::PaymentId>,
#[serde(default = "default_limit")]
pub limit: u32,
pub created: Option<i64>,
#[serde(rename = "created[lt]")]
pub created_lt: Option<i64>,
#[serde(rename = "created[gt]")]
pub created_gt: Option<i64>,
#[serde(rename = "created[lte]")]
pub created_lte: Option<i64>,
#[serde(rename = "created[gte]")]
pub created_gte: Option<i64>,
}
fn default_limit() -> u32 {
10
}
impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> {
Ok(Self {
customer_id: item.customer,
starting_after: item.starting_after,
ending_before: item.ending_before,
limit: item.limit,
created: from_timestamp_to_datetime(item.created)?,
created_lt: from_timestamp_to_datetime(item.created_lt)?,
created_gt: from_timestamp_to_datetime(item.created_gt)?,
created_lte: from_timestamp_to_datetime(item.created_lte)?,
created_gte: from_timestamp_to_datetime(item.created_gte)?,
})
}
}
#[inline]
fn from_timestamp_to_datetime(
time: Option<i64>,
) -> Result<Option<time::PrimitiveDateTime>, errors::ApiErrorResponse> {
if let Some(time) = time {
let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|err| {
logger::error!("Error: from_unix_timestamp: {}", err);
errors::ApiErrorResponse::InvalidRequestData {
message: "Error while converting timestamp".to_string(),
}
})?;
Ok(Some(time::PrimitiveDateTime::new(time.date(), time.time())))
} else {
Ok(None)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/payment_intents/types.rs | crates/router/src/compatibility/stripe/payment_intents/types.rs | use std::str::FromStr;
use api_models::payments;
use common_types::payments as common_payments_types;
use common_utils::{
crypto::Encryptable,
date_time,
ext_traits::StringExt,
id_type,
pii::{IpAddress, SecretSerdeValue, UpiVpaMaskingStrategy},
types::MinorUnit,
};
use error_stack::ResultExt;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{
compatibility::stripe::refunds::types as stripe_refunds,
connector::utils::AddressData,
consts,
core::errors,
pii::{Email, PeekInterface},
types::{
api::{admin, enums as api_enums},
transformers::{ForeignFrom, ForeignTryFrom},
},
};
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct StripeBillingDetails {
pub address: Option<AddressDetails>,
pub email: Option<Email>,
pub name: Option<String>,
pub phone: Option<masking::Secret<String>>,
}
impl From<StripeBillingDetails> for payments::Address {
fn from(details: StripeBillingDetails) -> Self {
Self {
phone: Some(payments::PhoneDetails {
number: details.phone,
country_code: details.address.as_ref().and_then(|address| {
address.country.as_ref().map(|country| country.to_string())
}),
}),
email: details.email,
address: details.address.map(|address| payments::AddressDetails {
city: address.city,
country: address.country,
line1: address.line1,
line2: address.line2,
zip: address.postal_code,
state: address.state,
first_name: None,
line3: None,
last_name: None,
origin_zip: None,
}),
}
}
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct StripeCard {
pub number: cards::CardNumber,
pub exp_month: masking::Secret<String>,
pub exp_year: masking::Secret<String>,
pub cvc: masking::Secret<String>,
pub holder_name: Option<masking::Secret<String>>,
}
// ApplePay wallet param is not available in stripe Docs
#[derive(Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripeWallet {
ApplePay(payments::ApplePayWalletData),
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct StripeUpi {
pub vpa_id: masking::Secret<String, UpiVpaMaskingStrategy>,
}
#[derive(Debug, Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodType {
#[default]
Card,
Wallet,
Upi,
BankRedirect,
RealTimePayment,
}
impl From<StripePaymentMethodType> for api_enums::PaymentMethod {
fn from(item: StripePaymentMethodType) -> Self {
match item {
StripePaymentMethodType::Card => Self::Card,
StripePaymentMethodType::Wallet => Self::Wallet,
StripePaymentMethodType::Upi => Self::Upi,
StripePaymentMethodType::BankRedirect => Self::BankRedirect,
StripePaymentMethodType::RealTimePayment => Self::RealTimePayment,
}
}
}
#[derive(Default, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct StripePaymentMethodData {
#[serde(rename = "type")]
pub stype: StripePaymentMethodType,
pub billing_details: Option<StripeBillingDetails>,
#[serde(flatten)]
pub payment_method_details: Option<StripePaymentMethodDetails>, // enum
pub metadata: Option<SecretSerdeValue>,
}
#[derive(PartialEq, Eq, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodDetails {
Card(StripeCard),
Wallet(StripeWallet),
Upi(StripeUpi),
}
impl From<StripeCard> for payments::Card {
fn from(card: StripeCard) -> Self {
Self {
card_number: card.number,
card_exp_month: card.exp_month,
card_exp_year: card.exp_year,
card_holder_name: card.holder_name,
card_cvc: card.cvc,
card_issuer: None,
card_network: None,
bank_code: None,
card_issuing_country: None,
card_issuing_country_code: None,
card_type: None,
nick_name: None,
}
}
}
impl From<StripeWallet> for payments::WalletData {
fn from(wallet: StripeWallet) -> Self {
match wallet {
StripeWallet::ApplePay(data) => Self::ApplePay(data),
}
}
}
impl From<StripeUpi> for payments::UpiData {
fn from(upi_data: StripeUpi) -> Self {
Self::UpiCollect(payments::UpiCollectData {
vpa_id: Some(upi_data.vpa_id),
})
}
}
impl From<StripePaymentMethodDetails> for payments::PaymentMethodData {
fn from(item: StripePaymentMethodDetails) -> Self {
match item {
StripePaymentMethodDetails::Card(card) => Self::Card(payments::Card::from(card)),
StripePaymentMethodDetails::Wallet(wallet) => {
Self::Wallet(payments::WalletData::from(wallet))
}
StripePaymentMethodDetails::Upi(upi) => Self::Upi(payments::UpiData::from(upi)),
}
}
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct Shipping {
pub address: AddressDetails,
pub name: Option<masking::Secret<String>>,
pub carrier: Option<String>,
pub phone: Option<masking::Secret<String>>,
pub tracking_number: Option<masking::Secret<String>>,
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct AddressDetails {
pub city: Option<String>,
pub country: Option<api_enums::CountryAlpha2>,
pub line1: Option<masking::Secret<String>>,
pub line2: Option<masking::Secret<String>>,
pub postal_code: Option<masking::Secret<String>>,
pub state: Option<masking::Secret<String>>,
}
impl From<Shipping> for payments::Address {
fn from(details: Shipping) -> Self {
Self {
phone: Some(payments::PhoneDetails {
number: details.phone,
country_code: details.address.country.map(|country| country.to_string()),
}),
email: None,
address: Some(payments::AddressDetails {
city: details.address.city,
country: details.address.country,
line1: details.address.line1,
line2: details.address.line2,
zip: details.address.postal_code,
state: details.address.state,
first_name: details.name,
line3: None,
last_name: None,
origin_zip: None,
}),
}
}
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct MandateData {
pub customer_acceptance: CustomerAcceptance,
pub mandate_type: Option<StripeMandateType>,
pub amount: Option<i64>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub start_date: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub end_date: Option<PrimitiveDateTime>,
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone, Debug)]
pub struct CustomerAcceptance {
#[serde(rename = "type")]
pub acceptance_type: Option<AcceptanceType>,
pub accepted_at: Option<PrimitiveDateTime>,
pub online: Option<OnlineMandate>,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum AcceptanceType {
Online,
#[default]
Offline,
}
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct OnlineMandate {
pub ip_address: masking::Secret<String, IpAddress>,
pub user_agent: String,
}
#[derive(Deserialize, Clone, Debug)]
pub struct StripePaymentIntentRequest {
pub id: Option<id_type::PaymentId>,
pub amount: Option<i64>, // amount in cents, hence passed as integer
pub connector: Option<Vec<api_enums::RoutableConnectors>>,
pub currency: Option<String>,
#[serde(rename = "amount_to_capture")]
pub amount_capturable: Option<i64>,
pub confirm: Option<bool>,
pub capture_method: Option<api_enums::CaptureMethod>,
pub customer: Option<id_type::CustomerId>,
pub description: Option<String>,
pub payment_method_data: Option<StripePaymentMethodData>,
pub receipt_email: Option<Email>,
pub return_url: Option<url::Url>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub shipping: Option<Shipping>,
pub statement_descriptor: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub metadata: Option<serde_json::Value>,
pub client_secret: Option<masking::Secret<String>>,
pub payment_method_options: Option<StripePaymentMethodOptions>,
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
pub mandate: Option<String>,
pub off_session: Option<bool>,
pub payment_method_types: Option<api_enums::PaymentMethodType>,
pub receipt_ipaddress: Option<String>,
pub user_agent: Option<String>,
pub mandate_data: Option<MandateData>,
pub automatic_payment_methods: Option<SecretSerdeValue>, // not used
pub payment_method: Option<String>, // not used
pub confirmation_method: Option<String>, // not used
pub error_on_requires_action: Option<String>, // not used
pub radar_options: Option<SecretSerdeValue>, // not used
pub connector_metadata: Option<payments::ConnectorMetadata>,
}
impl TryFrom<StripePaymentIntentRequest> for payments::PaymentsRequest {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: StripePaymentIntentRequest) -> errors::RouterResult<Self> {
let routable_connector: Option<api_enums::RoutableConnectors> =
item.connector.and_then(|v| v.into_iter().next());
let routing = routable_connector
.map(|connector| {
api_models::routing::StaticRoutingAlgorithm::Single(Box::new(
api_models::routing::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id: None,
},
))
})
.map(|r| {
serde_json::to_value(r)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("converting to routing failed")
})
.transpose()?;
let ip_address = item
.receipt_ipaddress
.map(|ip| std::net::IpAddr::from_str(ip.as_str()))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "receipt_ipaddress".to_string(),
expected_format: "127.0.0.1".to_string(),
})?;
let amount = item.amount.map(|amount| MinorUnit::new(amount).into());
let payment_method_data = item.payment_method_data.as_ref().map(|pmd| {
let billing = pmd.billing_details.clone().map(payments::Address::from);
let payment_method_data = match pmd.payment_method_details.as_ref() {
Some(spmd) => Some(payments::PaymentMethodData::from(spmd.to_owned())),
None => get_pmd_based_on_payment_method_type(
item.payment_method_types,
billing.clone().map(From::from),
),
};
payments::PaymentMethodDataRequest {
payment_method_data,
billing,
}
});
let request = Ok(Self {
payment_id: item.id.map(payments::PaymentIdType::PaymentIntentId),
amount,
currency: item
.currency
.as_ref()
.map(|c| c.to_uppercase().parse_enum("currency"))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "currency",
})?,
capture_method: item.capture_method,
amount_to_capture: item.amount_capturable.map(MinorUnit::new),
confirm: item.confirm,
customer_id: item.customer,
email: item.receipt_email,
phone: item.shipping.as_ref().and_then(|s| s.phone.clone()),
description: item.description,
return_url: item.return_url,
payment_method_data,
payment_method: item
.payment_method_data
.as_ref()
.map(|pmd| api_enums::PaymentMethod::from(pmd.stype.to_owned())),
shipping: item
.shipping
.as_ref()
.map(|s| payments::Address::from(s.to_owned())),
billing: item
.payment_method_data
.and_then(|pmd| pmd.billing_details.map(payments::Address::from)),
statement_descriptor_name: item.statement_descriptor,
statement_descriptor_suffix: item.statement_descriptor_suffix,
metadata: item.metadata,
client_secret: item.client_secret.map(|s| s.peek().clone()),
authentication_type: match item.payment_method_options {
Some(pmo) => {
let StripePaymentMethodOptions::Card {
request_three_d_secure,
}: StripePaymentMethodOptions = pmo;
Some(api_enums::AuthenticationType::foreign_from(
request_three_d_secure,
))
}
None => None,
},
mandate_data: ForeignTryFrom::foreign_try_from((
item.mandate_data,
item.currency.to_owned(),
))?,
merchant_connector_details: item.merchant_connector_details,
setup_future_usage: item.setup_future_usage,
mandate_id: item.mandate,
off_session: item.off_session,
payment_method_type: item.payment_method_types,
routing,
browser_info: Some(
serde_json::to_value(crate::types::BrowserInformation {
ip_address,
user_agent: item.user_agent,
..Default::default()
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("convert to browser info failed")?,
),
connector_metadata: item.connector_metadata,
..Self::default()
});
request
}
}
#[derive(Clone, Default, Eq, PartialEq, Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentStatus {
Succeeded,
Canceled,
#[default]
Processing,
RequiresAction,
RequiresPaymentMethod,
RequiresConfirmation,
RequiresCapture,
}
impl From<api_enums::IntentStatus> for StripePaymentStatus {
fn from(item: api_enums::IntentStatus) -> Self {
match item {
api_enums::IntentStatus::Succeeded | api_enums::IntentStatus::PartiallyCaptured => {
Self::Succeeded
}
api_enums::IntentStatus::Failed | api_enums::IntentStatus::Expired => Self::Canceled,
api_enums::IntentStatus::Processing
| api_enums::IntentStatus::PartiallyCapturedAndProcessing => Self::Processing,
api_enums::IntentStatus::RequiresCustomerAction
| api_enums::IntentStatus::RequiresMerchantAction
| api_enums::IntentStatus::Conflicted => Self::RequiresAction,
api_enums::IntentStatus::RequiresPaymentMethod => Self::RequiresPaymentMethod,
api_enums::IntentStatus::RequiresConfirmation => Self::RequiresConfirmation,
api_enums::IntentStatus::RequiresCapture
| api_enums::IntentStatus::PartiallyCapturedAndCapturable
| api_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
Self::RequiresCapture
}
api_enums::IntentStatus::Cancelled | api_enums::IntentStatus::CancelledPostCapture => {
Self::Canceled
}
}
}
}
#[derive(Debug, Serialize, Deserialize, Copy, Clone, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CancellationReason {
Duplicate,
Fraudulent,
RequestedByCustomer,
Abandoned,
}
#[derive(Debug, Deserialize, Serialize, Copy, Clone)]
pub struct StripePaymentCancelRequest {
cancellation_reason: Option<CancellationReason>,
}
impl From<StripePaymentCancelRequest> for payments::PaymentsCancelRequest {
fn from(item: StripePaymentCancelRequest) -> Self {
Self {
cancellation_reason: item.cancellation_reason.map(|c| c.to_string()),
..Self::default()
}
}
}
#[derive(Default, Eq, PartialEq, Serialize, Debug)]
pub struct StripePaymentIntentResponse {
pub id: id_type::PaymentId,
pub object: &'static str,
pub amount: i64,
pub amount_received: Option<i64>,
pub amount_capturable: i64,
pub currency: String,
pub status: StripePaymentStatus,
pub client_secret: Option<masking::Secret<String>>,
pub created: Option<i64>,
pub customer: Option<id_type::CustomerId>,
pub refunds: Option<Vec<stripe_refunds::StripeRefundResponse>>,
pub mandate: Option<String>,
pub metadata: Option<serde_json::Value>,
pub charges: Charges,
pub connector: Option<String>,
pub description: Option<String>,
pub mandate_data: Option<payments::MandateData>,
pub setup_future_usage: Option<api_models::enums::FutureUsage>,
pub off_session: Option<bool>,
pub authentication_type: Option<api_models::enums::AuthenticationType>,
pub next_action: Option<StripeNextAction>,
pub cancellation_reason: Option<String>,
pub payment_method: Option<api_models::enums::PaymentMethod>,
pub payment_method_data: Option<payments::PaymentMethodDataResponse>,
pub shipping: Option<payments::Address>,
pub billing: Option<payments::Address>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
pub payment_token: Option<String>,
pub email: Option<Email>,
pub phone: Option<masking::Secret<String>>,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor_name: Option<String>,
pub capture_method: Option<api_models::enums::CaptureMethod>,
pub name: Option<masking::Secret<String>>,
pub last_payment_error: Option<LastPaymentError>,
pub connector_transaction_id: Option<String>,
}
#[derive(Default, Eq, PartialEq, Serialize, Debug)]
pub struct LastPaymentError {
charge: Option<String>,
code: Option<String>,
decline_code: Option<String>,
message: String,
param: Option<String>,
payment_method: StripePaymentMethod,
#[serde(rename = "type")]
error_type: String,
}
impl From<payments::PaymentsResponse> for StripePaymentIntentResponse {
fn from(resp: payments::PaymentsResponse) -> Self {
Self {
object: "payment_intent",
id: resp.payment_id,
status: StripePaymentStatus::from(resp.status),
amount: resp.amount.get_amount_as_i64(),
amount_capturable: resp.amount_capturable.get_amount_as_i64(),
amount_received: resp.amount_received.map(|amt| amt.get_amount_as_i64()),
connector: resp.connector,
client_secret: resp.client_secret,
created: resp.created.map(|t| t.assume_utc().unix_timestamp()),
currency: resp.currency.to_lowercase(),
customer: resp.customer_id,
description: resp.description,
refunds: resp
.refunds
.map(|a| a.into_iter().map(Into::into).collect()),
mandate: resp.mandate_id,
mandate_data: resp.mandate_data,
setup_future_usage: resp.setup_future_usage,
off_session: resp.off_session,
capture_on: resp.capture_on,
capture_method: resp.capture_method,
payment_method: resp.payment_method,
payment_method_data: resp
.payment_method_data
.and_then(|pmd| pmd.payment_method_data),
payment_token: resp.payment_token,
shipping: resp.shipping,
billing: resp.billing,
email: resp.email.map(|inner| inner.into()),
name: resp.name.map(Encryptable::into_inner),
phone: resp.phone.map(Encryptable::into_inner),
authentication_type: resp.authentication_type,
statement_descriptor_name: resp.statement_descriptor_name,
statement_descriptor_suffix: resp.statement_descriptor_suffix,
next_action: into_stripe_next_action(resp.next_action, resp.return_url),
cancellation_reason: resp.cancellation_reason,
metadata: resp.metadata,
charges: Charges::new(),
last_payment_error: resp.error_code.map(|code| LastPaymentError {
charge: None,
code: Some(code.to_owned()),
decline_code: None,
message: resp
.error_message
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
param: None,
payment_method: StripePaymentMethod {
payment_method_id: "place_holder_id".to_string(),
object: "payment_method",
card: None,
created: u64::try_from(date_time::now().assume_utc().unix_timestamp())
.unwrap_or_default(),
method_type: "card".to_string(),
livemode: false,
},
error_type: code,
}),
connector_transaction_id: resp.connector_transaction_id,
}
}
}
#[derive(Default, Eq, PartialEq, Serialize, Debug)]
pub struct StripePaymentMethod {
#[serde(rename = "id")]
payment_method_id: String,
object: &'static str,
card: Option<StripeCard>,
created: u64,
#[serde(rename = "type")]
method_type: String,
livemode: bool,
}
#[derive(Default, Eq, PartialEq, Serialize, Debug)]
pub struct Charges {
object: &'static str,
data: Vec<String>,
has_more: bool,
total_count: i32,
url: String,
}
impl Charges {
pub fn new() -> Self {
Self {
object: "list",
data: vec![],
has_more: false,
total_count: 0,
url: "http://placeholder".to_string(),
}
}
}
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StripePaymentListConstraints {
pub customer: Option<id_type::CustomerId>,
pub starting_after: Option<id_type::PaymentId>,
pub ending_before: Option<id_type::PaymentId>,
#[serde(default = "default_limit")]
pub limit: u32,
pub created: Option<i64>,
#[serde(rename = "created[lt]")]
pub created_lt: Option<i64>,
#[serde(rename = "created[gt]")]
pub created_gt: Option<i64>,
#[serde(rename = "created[lte]")]
pub created_lte: Option<i64>,
#[serde(rename = "created[gte]")]
pub created_gte: Option<i64>,
}
fn default_limit() -> u32 {
10
}
impl TryFrom<StripePaymentListConstraints> for payments::PaymentListConstraints {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn try_from(item: StripePaymentListConstraints) -> Result<Self, Self::Error> {
Ok(Self {
customer_id: item.customer,
starting_after: item.starting_after,
ending_before: item.ending_before,
limit: item.limit,
created: from_timestamp_to_datetime(item.created)?,
created_lt: from_timestamp_to_datetime(item.created_lt)?,
created_gt: from_timestamp_to_datetime(item.created_gt)?,
created_lte: from_timestamp_to_datetime(item.created_lte)?,
created_gte: from_timestamp_to_datetime(item.created_gte)?,
})
}
}
#[inline]
fn from_timestamp_to_datetime(
time: Option<i64>,
) -> Result<Option<PrimitiveDateTime>, errors::ApiErrorResponse> {
if let Some(time) = time {
let time = time::OffsetDateTime::from_unix_timestamp(time).map_err(|_| {
errors::ApiErrorResponse::InvalidRequestData {
message: "Error while converting timestamp".to_string(),
}
})?;
Ok(Some(PrimitiveDateTime::new(time.date(), time.time())))
} else {
Ok(None)
}
}
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct StripePaymentIntentListResponse {
pub object: String,
pub url: String,
pub has_more: bool,
pub data: Vec<StripePaymentIntentResponse>,
}
impl From<payments::PaymentListResponse> for StripePaymentIntentListResponse {
fn from(it: payments::PaymentListResponse) -> Self {
Self {
object: "list".to_string(),
url: "/v1/payment_intents".to_string(),
has_more: false,
data: it.data.into_iter().map(Into::into).collect(),
}
}
}
#[derive(PartialEq, Eq, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum StripePaymentMethodOptions {
Card {
request_three_d_secure: Option<Request3DS>,
},
}
#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum StripeMandateType {
SingleUse,
MultiUse,
}
#[derive(PartialEq, Eq, Clone, Default, Deserialize, Serialize, Debug)]
pub struct MandateOption {
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub accepted_at: Option<PrimitiveDateTime>,
pub user_agent: Option<String>,
pub ip_address: Option<masking::Secret<String, IpAddress>>,
pub mandate_type: Option<StripeMandateType>,
pub amount: Option<i64>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub start_date: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub end_date: Option<PrimitiveDateTime>,
}
impl ForeignTryFrom<(Option<MandateData>, Option<String>)> for Option<payments::MandateData> {
type Error = error_stack::Report<errors::ApiErrorResponse>;
fn foreign_try_from(
(mandate_data, currency): (Option<MandateData>, Option<String>),
) -> errors::RouterResult<Self> {
let currency = currency
.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "currency",
}
.into(),
)
.and_then(|c| {
c.to_uppercase().parse_enum("currency").change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "currency",
},
)
})?;
let mandate_data = mandate_data.map(|mandate| payments::MandateData {
mandate_type: match mandate.mandate_type {
Some(item) => match item {
StripeMandateType::SingleUse => Some(payments::MandateType::SingleUse(
payments::MandateAmountData {
amount: MinorUnit::new(mandate.amount.unwrap_or_default()),
currency,
start_date: mandate.start_date,
end_date: mandate.end_date,
metadata: None,
},
)),
StripeMandateType::MultiUse => Some(payments::MandateType::MultiUse(Some(
payments::MandateAmountData {
amount: MinorUnit::new(mandate.amount.unwrap_or_default()),
currency,
start_date: mandate.start_date,
end_date: mandate.end_date,
metadata: None,
},
))),
},
None => Some(payments::MandateType::MultiUse(Some(
payments::MandateAmountData {
amount: MinorUnit::new(mandate.amount.unwrap_or_default()),
currency,
start_date: mandate.start_date,
end_date: mandate.end_date,
metadata: None,
},
))),
},
customer_acceptance: Some(common_payments_types::CustomerAcceptance {
acceptance_type: common_payments_types::AcceptanceType::Online,
accepted_at: mandate.customer_acceptance.accepted_at,
online: mandate.customer_acceptance.online.map(|online| {
common_payments_types::OnlineMandate {
ip_address: Some(online.ip_address),
user_agent: online.user_agent,
}
}),
}),
update_mandate_id: None,
});
Ok(mandate_data)
}
}
#[derive(Default, Eq, PartialEq, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Request3DS {
#[default]
Automatic,
Any,
}
impl ForeignFrom<Option<Request3DS>> for api_models::enums::AuthenticationType {
fn foreign_from(item: Option<Request3DS>) -> Self {
match item.unwrap_or_default() {
Request3DS::Automatic => Self::NoThreeDs,
Request3DS::Any => Self::ThreeDs,
}
}
}
#[derive(Default, Eq, PartialEq, Serialize, Debug)]
pub struct RedirectUrl {
pub return_url: Option<String>,
pub url: Option<String>,
}
#[derive(Eq, PartialEq, serde::Serialize, Debug)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StripeNextAction {
RedirectToUrl {
redirect_to_url: RedirectUrl,
},
DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details: payments::BankTransferNextStepsData,
},
ThirdPartySdkSessionToken {
session_token: Option<payments::SessionToken>,
},
QrCodeInformation {
image_data_url: Option<url::Url>,
display_to_timestamp: Option<i64>,
qr_code_url: Option<url::Url>,
border_color: Option<String>,
display_text: Option<String>,
},
FetchQrCodeInformation {
qr_code_fetch_url: url::Url,
},
DisplayVoucherInformation {
voucher_details: payments::VoucherNextStepData,
},
WaitScreenInformation {
display_from_timestamp: i128,
display_to_timestamp: Option<i128>,
poll_config: Option<payments::PollConfig>,
},
InvokeSdkClient {
next_action_data: payments::SdkNextActionData,
},
CollectOtp {
consent_data_required: payments::MobilePaymentConsent,
},
InvokeHiddenIframe {
iframe_data: payments::IframeData,
},
InvokeUpiIntentSdk {
sdk_uri: url::Url,
},
InvokeUpiQrFlow {
sdk_uri: url::Url,
},
}
pub(crate) fn into_stripe_next_action(
next_action: Option<payments::NextActionData>,
return_url: Option<String>,
) -> Option<StripeNextAction> {
next_action.map(|next_action_data| match next_action_data {
payments::NextActionData::RedirectToUrl { redirect_to_url } => {
StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url,
url: Some(redirect_to_url),
},
}
}
payments::NextActionData::RedirectInsidePopup { popup_url, .. } => {
StripeNextAction::RedirectToUrl {
redirect_to_url: RedirectUrl {
return_url,
url: Some(popup_url),
},
}
}
payments::NextActionData::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details,
} => StripeNextAction::DisplayBankTransferInformation {
bank_transfer_steps_and_charges_details,
},
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/compatibility/stripe/customers/types.rs | crates/router/src/compatibility/stripe/customers/types.rs | use std::{convert::From, default::Default};
#[cfg(feature = "v1")]
use api_models::payment_methods as api_types;
use api_models::payments;
#[cfg(feature = "v1")]
use common_utils::{crypto::Encryptable, date_time};
use common_utils::{
id_type,
pii::{self, Email},
types::Description,
};
use serde::{Deserialize, Serialize};
#[cfg(feature = "v1")]
use crate::logger;
use crate::types::{api, api::enums as api_enums};
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct Shipping {
pub address: StripeAddressDetails,
pub name: Option<masking::Secret<String>>,
pub carrier: Option<String>,
pub phone: Option<masking::Secret<String>>,
pub tracking_number: Option<masking::Secret<String>>,
}
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct StripeAddressDetails {
pub city: Option<String>,
pub country: Option<api_enums::CountryAlpha2>,
pub line1: Option<masking::Secret<String>>,
pub line2: Option<masking::Secret<String>>,
pub postal_code: Option<masking::Secret<String>>,
pub state: Option<masking::Secret<String>>,
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CreateCustomerRequest {
pub email: Option<Email>,
pub invoice_prefix: Option<String>,
pub name: Option<masking::Secret<String>>,
pub phone: Option<masking::Secret<String>>,
pub address: Option<StripeAddressDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub description: Option<Description>,
pub shipping: Option<Shipping>,
pub payment_method: Option<String>, // not used
pub balance: Option<i64>, // not used
pub cash_balance: Option<pii::SecretSerdeValue>, // not used
pub coupon: Option<String>, // not used
pub invoice_settings: Option<pii::SecretSerdeValue>, // not used
pub next_invoice_sequence: Option<String>, // not used
pub preferred_locales: Option<String>, // not used
pub promotion_code: Option<String>, // not used
pub source: Option<String>, // not used
pub tax: Option<pii::SecretSerdeValue>, // not used
pub tax_exempt: Option<String>, // not used
pub tax_id_data: Option<String>, // not used
pub test_clock: Option<String>, // not used
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CustomerUpdateRequest {
pub description: Option<Description>,
pub email: Option<Email>,
pub phone: Option<masking::Secret<String, masking::WithType>>,
pub name: Option<masking::Secret<String>>,
pub address: Option<StripeAddressDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub shipping: Option<Shipping>,
pub payment_method: Option<String>, // not used
pub balance: Option<i64>, // not used
pub cash_balance: Option<pii::SecretSerdeValue>, // not used
pub coupon: Option<String>, // not used
pub default_source: Option<String>, // not used
pub invoice_settings: Option<pii::SecretSerdeValue>, // not used
pub next_invoice_sequence: Option<String>, // not used
pub preferred_locales: Option<String>, // not used
pub promotion_code: Option<String>, // not used
pub source: Option<String>, // not used
pub tax: Option<pii::SecretSerdeValue>, // not used
pub tax_exempt: Option<String>, // not used
}
#[derive(Serialize, PartialEq, Eq)]
pub struct CreateCustomerResponse {
pub id: id_type::CustomerId,
pub object: String,
pub created: u64,
pub description: Option<Description>,
pub email: Option<Email>,
pub metadata: Option<pii::SecretSerdeValue>,
pub name: Option<masking::Secret<String>>,
pub phone: Option<masking::Secret<String, masking::WithType>>,
}
pub type CustomerRetrieveResponse = CreateCustomerResponse;
pub type CustomerUpdateResponse = CreateCustomerResponse;
#[derive(Serialize, PartialEq, Eq)]
pub struct CustomerDeleteResponse {
pub id: id_type::CustomerId,
pub deleted: bool,
}
impl From<StripeAddressDetails> for payments::AddressDetails {
fn from(address: StripeAddressDetails) -> Self {
Self {
city: address.city,
country: address.country,
line1: address.line1,
line2: address.line2,
zip: address.postal_code,
state: address.state,
first_name: None,
line3: None,
last_name: None,
origin_zip: None,
}
}
}
#[cfg(feature = "v1")]
impl From<CreateCustomerRequest> for api::CustomerRequest {
fn from(req: CreateCustomerRequest) -> Self {
Self {
customer_id: Some(common_utils::generate_customer_id_of_default_length()),
name: req.name,
phone: req.phone,
email: req.email,
description: req.description,
metadata: req.metadata,
address: req.address.map(|s| s.into()),
..Default::default()
}
}
}
#[cfg(feature = "v1")]
impl From<CustomerUpdateRequest> for api::CustomerUpdateRequest {
fn from(req: CustomerUpdateRequest) -> Self {
Self {
name: req.name,
phone: req.phone,
email: req.email,
description: req.description,
metadata: req.metadata,
address: req.address.map(|s| s.into()),
..Default::default()
}
}
}
#[cfg(feature = "v1")]
impl From<api::CustomerResponse> for CreateCustomerResponse {
fn from(cust: api::CustomerResponse) -> Self {
let cust = cust.into_inner();
Self {
id: cust.customer_id,
object: "customer".to_owned(),
created: u64::try_from(cust.created_at.assume_utc().unix_timestamp()).unwrap_or_else(
|error| {
logger::error!(
%error,
"incorrect value for `customer.created_at` provided {}", cust.created_at
);
// Current timestamp converted to Unix timestamp should have a positive value
// for many years to come
u64::try_from(date_time::now().assume_utc().unix_timestamp())
.unwrap_or_default()
},
),
description: cust.description,
email: cust.email.map(|inner| inner.into()),
metadata: cust.metadata,
name: cust.name.map(Encryptable::into_inner),
phone: cust.phone.map(Encryptable::into_inner),
}
}
}
#[cfg(feature = "v1")]
impl From<api::CustomerDeleteResponse> for CustomerDeleteResponse {
fn from(cust: api::CustomerDeleteResponse) -> Self {
Self {
id: cust.customer_id,
deleted: cust.customer_deleted,
}
}
}
#[derive(Default, Serialize, PartialEq, Eq)]
pub struct CustomerPaymentMethodListResponse {
pub object: &'static str,
pub data: Vec<PaymentMethodData>,
}
#[derive(Default, Serialize, PartialEq, Eq)]
pub struct PaymentMethodData {
pub id: Option<String>,
pub object: &'static str,
pub card: Option<CardDetails>,
pub created: Option<time::PrimitiveDateTime>,
}
#[derive(Default, Serialize, PartialEq, Eq)]
pub struct CardDetails {
pub country: Option<String>,
pub last4: Option<String>,
pub exp_month: Option<masking::Secret<String>>,
pub exp_year: Option<masking::Secret<String>>,
pub fingerprint: Option<masking::Secret<String>>,
}
#[cfg(feature = "v1")]
impl From<api::CustomerPaymentMethodsListResponse> for CustomerPaymentMethodListResponse {
fn from(item: api::CustomerPaymentMethodsListResponse) -> Self {
let customer_payment_methods = item.customer_payment_methods;
let data = customer_payment_methods
.into_iter()
.map(From::from)
.collect();
Self {
object: "list",
data,
}
}
}
#[cfg(feature = "v1")]
impl From<api_types::CustomerPaymentMethod> for PaymentMethodData {
fn from(item: api_types::CustomerPaymentMethod) -> Self {
let card = item.card.map(From::from);
Self {
id: Some(item.payment_token),
object: "payment_method",
card,
created: item.created,
}
}
}
#[cfg(feature = "v1")]
impl From<api_types::CardDetailFromLocker> for CardDetails {
fn from(item: api_types::CardDetailFromLocker) -> Self {
Self {
country: item.issuer_country,
last4: item.last4_digits,
exp_month: item.expiry_month,
exp_year: item.expiry_year,
fingerprint: item.card_fingerprint,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/integration_demo.rs | crates/router/tests/integration_demo.rs | mod utils;
use masking::PeekInterface;
use test_utils::connector_auth::ConnectorAuthentication;
use utils::{mk_service, ApiKey, AppClient, MerchantId, PaymentId, Status};
/// Example of unit test
/// Kind of test: output-based testing
/// 1) Create Merchant account
#[actix_web::test]
async fn create_merchant_account() {
let server = Box::pin(mk_service()).await;
let client = AppClient::guest();
let admin_client = client.admin("test_admin");
let expected = "merchant_12345";
let expected_merchant_id_type =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_12345"))
.unwrap();
let hlist_pat![merchant_id, _api_key]: HList![MerchantId, ApiKey] = admin_client
.create_merchant_account(&server, expected.to_owned())
.await;
assert_eq!(expected_merchant_id_type, *merchant_id);
}
/// Example of unit test
/// Kind of test: communication-based testing
/// ```pseudocode
/// mk_service =
/// app_state <- AppState(StorageImpl::Mock) // Instantiate a mock database to simulate real world SQL database.
/// actix_web::test::init_service(<..>) // Initialize service from application builder instance .
/// ```
/// ### Tests with mocks are typically structured like so:
/// 1) create mock objects and specify what values they return
/// 2) run code under test, passing mock objects to it
/// 3) assert mocks were called the expected number of times, with the expected arguments
/// ```
/// fn show_users(get_users: impl FnOnce() -> Vec<&'static str>) -> String {
/// get_users().join(", ")
/// }
/// // GIVEN[1]:
/// let get_users = || vec!["Andrey", "Alisa"];
/// // WHEN[2]:
/// let list_users = show_users(get_users);
/// // THEN[3]:
/// assert_eq!(list_users, "Andrey, Alisa");
/// ```
/// ### Test case
/// 1) Create Merchant account (Get the API key)
/// 2) Create a connector
/// 3) Create a payment for 100 USD
/// 4) Confirm a payment (let it get processed through Stripe)
/// 5) Refund for 50USD success
/// 6) Another refund for 50USD success
///
/// ### Useful resources
/// * <https://blog.ploeh.dk/2016/03/18/functional-architecture-is-ports-and-adapters>
/// * <https://www.parsonsmatt.org/2017/07/27/inverted_mocking.html>
/// * <https://www.parsonsmatt.org/2018/03/22/three_layer_haskell_cake.html>
#[actix_web::test]
async fn partial_refund() {
let authentication = ConnectorAuthentication::new();
let server = Box::pin(mk_service()).await;
let client = AppClient::guest();
let admin_client = client.admin("test_admin");
let hlist_pat![merchant_id, api_key]: HList![MerchantId, ApiKey] =
admin_client.create_merchant_account(&server, None).await;
let _connector: serde_json::Value = admin_client
.create_connector(
&server,
&merchant_id,
"stripe",
authentication.checkout.unwrap().api_key.peek(),
)
.await;
let user_client = client.user(&api_key);
let hlist_pat![payment_id]: HList![PaymentId] =
user_client.create_payment(&server, 100, 100).await;
let hlist_pat![status]: HList![Status] =
user_client.create_refund(&server, &payment_id, 50).await;
assert_eq!(&*status, "pending");
let hlist_pat![status]: HList![Status] =
user_client.create_refund(&server, &payment_id, 50).await;
assert_eq!(&*status, "pending");
}
/// Example of unit test
/// Kind of test: communication-based testing
/// ```pseudocode
/// mk_service =
/// app_state <- AppState(StorageImpl::Mock) // Instantiate a mock database to simulate real world SQL database.
/// actix_web::test::init_service(<..>) // Initialize service from application builder instance .
/// ```
/// ### Tests with mocks are typically structured like so:
/// 1) create mock objects and specify what values they return
/// 2) run code under test, passing mock objects to it
/// 3) assert mocks were called the expected number of times, with the expected arguments
/// ```
/// fn show_users(get_users: impl FnOnce() -> Vec<&'static str>) -> String {
/// get_users().join(", ")
/// }
/// // GIVEN[1]:
/// let get_users = || vec!["Andrey", "Alisa"];
/// // WHEN[2]:
/// let list_users = show_users(get_users);
/// // THEN[3]:
/// assert_eq!(list_users, "Andrey, Alisa");
/// ```
/// Test case
/// 1) Create a payment for 100 USD
/// 2) Confirm a payment (let it get processed through Stripe)
/// 3) Refund for 50USD successfully
/// 4) Try another refund for 100USD
/// 5) Get an error for second refund
///
/// ### Useful resources
/// * <https://blog.ploeh.dk/2016/03/18/functional-architecture-is-ports-and-adapters>
/// * <https://www.parsonsmatt.org/2017/07/27/inverted_mocking.html>
/// * <https://www.parsonsmatt.org/2018/03/22/three_layer_haskell_cake.html>
#[actix_web::test]
async fn exceed_refund() {
let authentication = ConnectorAuthentication::new();
let server = Box::pin(mk_service()).await;
let client = AppClient::guest();
let admin_client = client.admin("test_admin");
let hlist_pat![merchant_id, api_key]: HList![MerchantId, ApiKey] =
admin_client.create_merchant_account(&server, None).await;
let _connector: serde_json::Value = admin_client
.create_connector(
&server,
&merchant_id,
"stripe",
authentication.checkout.unwrap().api_key.peek(),
)
.await;
let user_client = client.user(&api_key);
let hlist_pat![payment_id]: HList![PaymentId] =
user_client.create_payment(&server, 100, 100).await;
let hlist_pat![status]: HList![Status] =
user_client.create_refund(&server, &payment_id, 50).await;
assert_eq!(&*status, "pending");
let message: serde_json::Value = user_client.create_refund(&server, &payment_id, 100).await;
assert_eq!(
message.get("error").unwrap().get("message").unwrap(),
"The refund amount exceeds the amount captured."
);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/services.rs | crates/router/tests/services.rs | use std::sync::{atomic, Arc};
use router::{configs::settings::Settings, routes, services};
mod utils;
#[tokio::test]
#[should_panic]
async fn get_redis_conn_failure() {
// Arrange
utils::setup().await;
let (tx, _) = tokio::sync::oneshot::channel();
let app_state = Box::pin(routes::AppState::new(
Settings::default(),
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let _ = state.store.get_redis_conn().map(|conn| {
conn.is_redis_available
.store(false, atomic::Ordering::SeqCst)
});
// Act
let _ = state.store.get_redis_conn();
// Assert
// based on #[should_panic] attribute
}
#[tokio::test]
async fn get_redis_conn_success() {
// Arrange
Box::pin(utils::setup()).await;
let (tx, _) = tokio::sync::oneshot::channel();
let app_state = Box::pin(routes::AppState::new(
Settings::default(),
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
// Act
let result = state.store.get_redis_conn();
// Assert
assert!(result.is_ok())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/refunds.rs | crates/router/tests/refunds.rs | use utils::{mk_service, AppClient};
mod utils;
// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid
// do we'll test refund and payment in same tests and later implement thread_local variables.
// When test-connector feature is enabled, you can pass the connector name in description
#[actix_web::test]
// verify the API-KEY/merchant id has stripe as first choice
async fn refund_create_fail_stripe() {
let app = Box::pin(mk_service()).await;
let client = AppClient::guest();
let user_client = client.user("321");
let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let refund: serde_json::Value = user_client.create_refund(&app, &payment_id, 10).await;
assert_eq!(refund.get("error").unwrap().get("message").unwrap(), "Access forbidden, invalid API key was used. Please create your new API key from the Dashboard Settings section.");
}
#[actix_web::test]
// verify the API-KEY/merchant id has adyen as first choice
async fn refund_create_fail_adyen() {
let app = Box::pin(mk_service()).await;
let client = AppClient::guest();
let user_client = client.user("321");
let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let refund: serde_json::Value = user_client.create_refund(&app, &payment_id, 10).await;
assert_eq!(refund.get("error").unwrap().get("message").unwrap(), "Access forbidden, invalid API key was used. Please create your new API key from the Dashboard Settings section.");
}
#[actix_web::test]
#[ignore]
async fn refunds_todo() {
Box::pin(utils::setup()).await;
let client = awc::Client::default();
let mut response;
let mut response_body;
let get_endpoints = vec!["list"];
let post_endpoints: Vec<&str> = vec![];
for endpoint in get_endpoints {
response = client
.get(format!("http://127.0.0.1:8080/refunds/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
for endpoint in post_endpoints {
response = client
.post(format!("http://127.0.0.1:8080/refunds/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/customers.rs | crates/router/tests/customers.rs | mod utils;
// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid
// do we'll test refund and payment in same tests and later implement thread_local variables.
// When test-connector feature is enabled, you can pass the connector name in description
#[actix_web::test]
#[ignore]
// verify the API-KEY/merchant id has stripe as first choice
async fn customer_success() {
Box::pin(utils::setup()).await;
let customer_id = format!("customer_{}", uuid::Uuid::new_v4());
let api_key = ("API-KEY", "MySecretApiKey");
let name = "Doe";
let new_name = "new Doe";
let request = serde_json::json!({
"customer_id" : customer_id,
"name" : name,
});
let update_request = serde_json::json!({
"name" : new_name,
});
let client = awc::Client::default();
let mut response;
let mut response_body;
// create customer
response = client
.post("http://127.0.0.1:8080/customers")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("customer-create: {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
// retrieve customer
response = client
.get(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send()
.await
.unwrap();
response_body = response.body().await;
println!("customer-retrieve: {response:?} =:= {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
// update customer
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send_json(&update_request)
.await
.unwrap();
response_body = response.body().await;
println!("customer-update: {response:?} =:= {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
// delete customer
response = client
.delete(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send()
.await
.unwrap();
response_body = response.body().await;
println!("customer-delete : {response:?} =:= {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
#[actix_web::test]
#[ignore]
// verify the API-KEY/merchant id has stripe as first choice
async fn customer_failure() {
Box::pin(utils::setup()).await;
let customer_id = format!("customer_{}", uuid::Uuid::new_v4());
let api_key = ("api-key", "MySecretApiKey");
let mut request = serde_json::json!({
"email" : "abcd",
});
let client = awc::Client::default();
let mut response;
let mut response_body;
// insert the customer with invalid email when id not found
response = client
.post("http://127.0.0.1:8080/customers")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(
response.status(),
awc::http::StatusCode::UNPROCESSABLE_ENTITY
);
// retrieve a customer with customer id which is not in DB
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::BAD_REQUEST);
// update customer id with customer id which is not in DB
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(
response.status(),
awc::http::StatusCode::UNPROCESSABLE_ENTITY
);
// delete a customer with customer id which is not in DB
response = client
.delete(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::BAD_REQUEST);
// email validation for customer update
request = serde_json::json!({ "customer_id": customer_id });
response = client
.post("http://127.0.0.1:8080/customers")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
request = serde_json::json!({
"email": "abch"
});
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(
response.status(),
awc::http::StatusCode::UNPROCESSABLE_ENTITY
);
// address validation
request = serde_json::json!({
"email": "abch"
});
response = client
.post(format!("http://127.0.0.1:8080/customers/{customer_id}"))
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
response_body = response.body().await;
println!("{response:?} : {response_body:?}");
assert_eq!(
response.status(),
awc::http::StatusCode::UNPROCESSABLE_ENTITY
);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/webhooks.rs | crates/router/tests/webhooks.rs | // use std::sync;
// use router::{configs::settings, connection, core::webhooks, types::api};
// mod utils;
// fn get_config() -> settings::Settings {
// settings::Settings::new().expect("Settings")
// }
// struct TestApp {
// redis_conn: connection::RedisPool,
// }
// impl TestApp {
// async fn init() -> Self {
// utils::setup().await;
// let conf = get_config();
// Self {
// redis_conn: sync::Arc::new(connection::redis_connection(&conf.redis).await),
// }
// }
// }
// #[actix_web::test]
// async fn test_webhook_config_lookup() {
// let app = TestApp::init().await;
// let timestamp = router::utils::date_time::now();
// let merchant_id = format!("merchant_{timestamp}");
// let connector_id = "stripe";
// let config = serde_json::json!(["payment_intent_success"]);
// let lookup_res = webhooks::utils::lookup_webhook_event(
// connector_id,
// &merchant_id,
// &api::IncomingWebhookEvent::PaymentIntentSuccess,
// sync::Arc::clone(&app.redis_conn),
// )
// .await;
// assert!(lookup_res);
// app.redis_conn
// .serialize_and_set_key(&format!("whconf_{merchant_id}_{connector_id}"), &config)
// .await
// .expect("Save merchant webhook config");
// let lookup_res = webhooks::utils::lookup_webhook_event(
// connector_id,
// &merchant_id,
// &api::IncomingWebhookEvent::PaymentIntentSuccess,
// sync::Arc::clone(&app.redis_conn),
// )
// .await;
// assert!(lookup_res);
// }
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/health_check.rs | crates/router/tests/health_check.rs | mod utils;
use utils::{mk_service, AppClient};
#[actix_web::test]
async fn health_check() {
let server = Box::pin(mk_service()).await;
let client = AppClient::guest();
assert_eq!(client.health(&server).await, "health is good");
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/payouts.rs | crates/router/tests/payouts.rs | mod utils;
#[actix_web::test]
async fn payouts_todo() {
Box::pin(utils::setup()).await;
let client = awc::Client::default();
let mut response;
let mut response_body;
let get_endpoints = vec!["retrieve", "accounts"];
let post_endpoints = vec!["create", "update", "reverse", "cancel"];
for endpoint in get_endpoints {
response = client
.get(format!("http://127.0.0.1:8080/payouts/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
for endpoint in post_endpoints {
response = client
.post(format!("http://127.0.0.1:8080/payouts/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/utils.rs | crates/router/tests/utils.rs | #![allow(
unused,
clippy::expect_used,
clippy::missing_panics_doc,
clippy::unwrap_used
)]
use actix_http::{body::MessageBody, Request};
use actix_web::{
dev::{Service, ServiceResponse},
test::{call_and_read_body_json, TestRequest},
};
use derive_deref::Deref;
use router::{configs::settings::Settings, routes::AppState, services};
use router_env::tracing::Instrument;
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::{json, Value};
use tokio::sync::{oneshot, OnceCell};
static SERVER: OnceCell<bool> = OnceCell::const_new();
async fn spawn_server() -> bool {
let conf = Settings::new().expect("invalid settings");
let server = Box::pin(router::start_server(conf))
.await
.expect("failed to create server");
let _server = tokio::spawn(server.in_current_span());
true
}
pub async fn setup() {
Box::pin(SERVER.get_or_init(spawn_server)).await;
}
const STRIPE_MOCK: &str = "http://localhost:12111/";
async fn stripemock() -> Option<String> {
// not working: https://github.com/stripe/stripe-mock/issues/231
None
}
pub async fn mk_service(
) -> impl Service<Request, Response = ServiceResponse<impl MessageBody>, Error = actix_web::Error> {
let mut conf = Settings::new().unwrap();
let request_body_limit = conf.server.request_body_limit;
if let Some(url) = stripemock().await {
conf.connectors.stripe.base_url = url;
}
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(AppState::with_storage(
conf,
router::db::StorageImpl::Mock,
tx,
Box::new(services::MockApiClient),
))
.await;
actix_web::test::init_service(router::mk_app(app_state, request_body_limit)).await
}
pub struct Guest;
pub struct Admin {
authkey: String,
}
pub struct User {
authkey: String,
}
#[allow(dead_code)]
pub struct AppClient<T> {
state: T,
}
impl AppClient<Guest> {
pub fn guest() -> Self {
Self { state: Guest }
}
}
impl AppClient<Admin> {
pub async fn create_merchant_account<T: DeserializeOwned, S, B>(
&self,
app: &S,
merchant_id: impl Into<Option<String>>,
) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::post()
.uri("/accounts")
.append_header(("api-key".to_owned(), self.state.authkey.clone()))
.set_json(mk_merchant_account(merchant_id.into()))
.to_request();
call_and_read_body_json(app, request).await
}
pub async fn create_connector<T: DeserializeOwned, S, B>(
&self,
app: &S,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
api_key: &str,
) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::post()
.uri(&format!(
"/account/{}/connectors",
merchant_id.get_string_repr()
))
.append_header(("api-key".to_owned(), self.state.authkey.clone()))
.set_json(mk_connector(connector_name, api_key))
.to_request();
call_and_read_body_json(app, request).await
}
}
impl AppClient<User> {
pub async fn create_payment<T: DeserializeOwned, S, B>(
&self,
app: &S,
amount: i64,
amount_to_capture: i32,
) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::post()
.uri("/payments")
.append_header(("api-key".to_owned(), self.state.authkey.clone()))
.set_json(mk_payment(amount, amount_to_capture))
.to_request();
call_and_read_body_json(app, request).await
}
pub async fn create_refund<T: DeserializeOwned, S, B>(
&self,
app: &S,
payment_id: &common_utils::id_type::PaymentId,
amount: usize,
) -> T
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::post()
.uri("/refunds")
.append_header(("api-key".to_owned(), self.state.authkey.clone()))
.set_json(mk_refund(payment_id, amount))
.to_request();
call_and_read_body_json(app, request).await
}
}
impl<T> AppClient<T> {
pub fn admin(&self, authkey: &str) -> AppClient<Admin> {
AppClient {
state: Admin {
authkey: authkey.to_string(),
},
}
}
pub fn user(&self, authkey: &str) -> AppClient<User> {
AppClient {
state: User {
authkey: authkey.to_string(),
},
}
}
pub async fn health<S, B>(&self, app: &S) -> String
where
S: Service<Request, Response = ServiceResponse<B>, Error = actix_web::Error>,
B: MessageBody,
{
let request = TestRequest::get().uri("/health").to_request();
let bytes = actix_web::test::call_and_read_body(app, request).await;
String::from_utf8(bytes.to_vec()).unwrap()
}
}
fn mk_merchant_account(merchant_id: Option<String>) -> Value {
let merchant_id = merchant_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
json!({
"merchant_id": merchant_id,
"merchant_name": "NewAge Retailer",
"merchant_details": {
"primary_contact_person": "John Test",
"primary_email": "JohnTest@test.com",
"primary_phone": "sunt laborum",
"secondary_contact_person": "John Test2",
"secondary_email": "JohnTest2@test.com",
"secondary_phone": "cillum do dolor id",
"website": "www.example.com",
"about_business": "Online Retail with a wide selection of organic products for North America",
"address": {
"line1": "Juspay Router",
"line2": "Koramangala",
"line3": "Stallion",
"city": "Bangalore",
"state": "Karnataka",
"zip": "560095",
"country": "IN"
}
},
"return_url": "www.example.com/success",
"webhook_details": {
"webhook_version": "1.0.1",
"webhook_username": "ekart_retail",
"webhook_password": "password_ekart@123",
},
"routing_algorithm": {
"type": "single",
"data": "stripe"
},
"sub_merchants_enabled": false,
"metadata": {
"city": "NY",
"unit": "245"
}
})
}
fn mk_payment(amount: i64, amount_to_capture: i32) -> Value {
json!({
"amount": amount,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-10-10T10:11:12Z",
"amount_to_capture": amount_to_capture,
"customer_id": "cus_udst2tfldj6upmye2reztkmm4i",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "35",
"card_holder_name": "John Doe",
"card_cvc": "123"
}
},
"statement_descriptor_name": "Hyperswitch",
"statement_descriptor_suffix": "Hyperswitch",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
})
}
fn mk_connector(connector_name: &str, api_key: &str) -> Value {
json!({
"connector_type": "fiz_operations",
"connector_name": connector_name,
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": api_key,
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "wallet",
"payment_method_types": [
"upi_collect",
"upi_intent"
],
"payment_method_issuers": [
"labore magna ipsum",
"aute"
],
"payment_schemes": [
"Discover",
"Discover"
],
"accepted_currencies": [
"AED",
"AED"
],
"accepted_countries": [
"in",
"us"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
],
"metadata": {
"city": "NY",
"unit": "245"
}
})
}
fn _mk_payment_confirm() -> Value {
json!({
"return_url": "http://example.com/payments",
"setup_future_usage": "on_session",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "35",
"card_holder_name": "John Doe",
"card_cvc": "123"
}
},
"shipping": {},
"billing": {}
})
}
fn mk_refund(payment_id: &common_utils::id_type::PaymentId, amount: usize) -> Value {
let timestamp = common_utils::date_time::now().to_string();
json!({
"payment_id": payment_id,
"refund_id": timestamp.get(23..),
"amount": amount,
"reason": "Customer returned product",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
})
}
pub struct HNil;
impl<'de> Deserialize<'de> for HNil {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_any(serde::de::IgnoredAny)?;
Ok(Self)
}
}
#[derive(Deserialize)]
pub struct HCons<H, T> {
#[serde(flatten)]
pub head: H,
#[serde(flatten)]
pub tail: T,
}
#[macro_export]
macro_rules! HList {
() => { $crate::utils::HNil };
($head:ty $(, $rest:ty)* $(,)?) => { $crate::utils::HCons<$head, HList![$($rest),*]> };
}
#[macro_export]
macro_rules! hlist_pat {
() => { $crate::utils::HNil };
($head:pat $(, $rest:pat)* $(,)?) => { $crate::utils::HCons { head: $head, tail: hlist_pat!($($rest),*) } };
}
#[derive(Deserialize, Deref)]
pub struct MerchantId {
merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Deserialize, Deref)]
pub struct ApiKey {
api_key: String,
}
#[derive(Deserialize)]
pub struct Error {
pub message: Message,
}
#[derive(Deserialize, Deref)]
pub struct Message {
message: String,
}
#[derive(Deserialize, Deref)]
pub struct PaymentId {
payment_id: common_utils::id_type::PaymentId,
}
#[derive(Deserialize, Deref)]
pub struct Status {
status: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/macros.rs | crates/router/tests/macros.rs | #[cfg(test)]
mod flat_struct_test {
use std::collections::HashMap;
use router_derive::FlatStruct;
use serde::Serialize;
#[test]
fn test_flat_struct() {
#[derive(FlatStruct, Serialize)]
struct User {
address: Address,
}
#[derive(Serialize)]
struct Address {
line1: String,
zip: String,
city: String,
}
let line1 = "1397".to_string();
let zip = "Some street".to_string();
let city = "941222".to_string();
let address = Address {
line1: line1.clone(),
zip: zip.clone(),
city: city.clone(),
};
let user = User { address };
let flat_user_map = user.flat_struct();
let mut required_map = HashMap::new();
required_map.insert("address.line1".to_string(), line1);
required_map.insert("address.zip".to_string(), zip);
required_map.insert("address.city".to_string(), city);
assert_eq!(flat_user_map, required_map);
}
}
#[cfg(test)]
mod validate_schema_test {
use router_derive::ValidateSchema;
use url::Url;
#[test]
fn test_validate_schema() {
#[derive(ValidateSchema)]
struct Payment {
#[schema(min_length = 5, max_length = 12)]
payment_id: String,
#[schema(min_length = 10, max_length = 100)]
description: Option<String>,
#[schema(max_length = 255)]
return_url: Option<Url>,
}
// Valid case
let valid_payment = Payment {
payment_id: "payment_123".to_string(),
description: Some("This is a valid description".to_string()),
return_url: Some("https://example.com/return".parse().unwrap()),
};
assert!(valid_payment.validate().is_ok());
// Invalid: payment_id too short
let invalid_id = Payment {
payment_id: "pay".to_string(),
description: Some("This is a valid description".to_string()),
return_url: Some("https://example.com/return".parse().unwrap()),
};
let err = invalid_id.validate().unwrap_err();
assert!(
err.contains("payment_id must be at least 5 characters long. Received 3 characters")
);
// Invalid: payment_id too long
let invalid_desc = Payment {
payment_id: "payment_12345".to_string(),
description: Some("This is a valid description".to_string()),
return_url: Some("https://example.com/return".parse().unwrap()),
};
let err = invalid_desc.validate().unwrap_err();
assert!(
err.contains("payment_id must be at most 12 characters long. Received 13 characters")
);
// None values should pass validation
let none_values = Payment {
payment_id: "payment_123".to_string(),
description: None,
return_url: None,
};
assert!(none_values.validate().is_ok());
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/payments2.rs | crates/router/tests/payments2.rs | #![allow(clippy::unwrap_in_result)]
mod utils;
use std::{borrow::Cow, sync::Arc};
use common_utils::{id_type, types::MinorUnit};
use router::{
core::payments,
db::StorageImpl,
types::api::{self, enums as api_enums},
*,
};
use time::macros::datetime;
use tokio::sync::oneshot;
use uuid::Uuid;
#[test]
fn connector_list() {
let connector_list = types::ConnectorsList {
connectors: vec![String::from("stripe"), "adyen".to_string()],
};
let json = serde_json::to_string(&connector_list).unwrap();
println!("{}", &json);
let newlist: types::ConnectorsList = serde_json::from_str(&json).unwrap();
println!("{newlist:#?}");
assert_eq!(true, true);
}
#[cfg(feature = "v1")]
// FIXME: broken test?
#[ignore]
#[actix_rt::test]
async fn payments_create_core() {
use router::configs::settings::Settings;
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();
let state = Arc::new(app_state)
.get_session_state(
&id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.unwrap();
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(&merchant_id, &key_store)
.await
.unwrap();
let platform = hyperswitch_domain_models::platform::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
let payment_id =
id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();
let req = api::PaymentsRequest {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(MinorUnit::new(6540)),
capture_on: Some(datetime!(2022-09-10 10:11:12)),
confirm: Some(true),
customer_id: None,
email: None,
name: None,
description: Some("Its my first payment request".to_string()),
return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: None,
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethodDataRequest {
payment_method_data: Some(api::PaymentMethodData::Card(api::Card {
card_number: "4242424242424242".to_string().try_into().unwrap(),
card_exp_month: "10".to_string().into(),
card_exp_year: "35".to_string().into(),
card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
})),
billing: None,
}),
payment_method: Some(api_enums::PaymentMethod::Card),
shipping: Some(api::Address {
address: None,
phone: None,
email: None,
}),
billing: Some(api::Address {
address: None,
phone: None,
email: None,
}),
statement_descriptor_name: Some("Hyperswitch".to_string()),
statement_descriptor_suffix: Some("Hyperswitch".to_string()),
three_ds_data: None,
..<_>::default()
};
let expected_response = api::PaymentsResponse {
payment_id,
status: api_enums::IntentStatus::Succeeded,
amount: MinorUnit::new(6540),
amount_capturable: MinorUnit::new(0),
amount_received: None,
client_secret: None,
created: None,
modified_at: None,
currency: "USD".to_string(),
customer_id: None,
description: Some("Its my first payment request".to_string()),
refunds: None,
mandate_id: None,
merchant_id,
net_amount: MinorUnit::new(6540),
connector: None,
customer: None,
disputes: None,
attempts: None,
captures: None,
mandate_data: None,
setup_future_usage: None,
off_session: None,
capture_on: None,
capture_method: None,
payment_method: None,
payment_method_data: None,
payment_token: None,
shipping: None,
billing: None,
order_details: None,
email: None,
name: None,
phone: None,
return_url: None,
authentication_type: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
payment_method_type: None,
connector_label: None,
business_country: None,
business_label: None,
business_sub_label: None,
allowed_payment_method_types: None,
manual_retry_allowed: None,
connector_transaction_id: None,
frm_message: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
profile_id: None,
surcharge_details: None,
attempt_count: 1,
merchant_decision: None,
merchant_connector_id: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
browser_info: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
merchant_order_reference_id: None,
capture_before: None,
extended_authorization_applied: None,
extended_authorization_last_applied_at: None,
order_tax_amount: None,
connector_mandate_id: None,
mit_category: None,
tokenization: None,
shipping_cost: None,
card_discovery: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
issuer_error_code: None,
issuer_error_message: None,
is_iframe_redirection_enabled: None,
whole_connector_response: None,
payment_channel: None,
network_transaction_id: None,
enable_partial_authorization: None,
is_overcapture_enabled: None,
enable_overcapture: None,
network_details: None,
is_stored_credential: None,
request_extended_authorization: None,
billing_descriptor: None,
partner_merchant_identifier_details: None,
payment_method_tokenization_details: None,
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
state.get_req_state(),
platform,
None,
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await
.unwrap();
assert_eq!(expected_response, actual_response);
}
// FIXME: broken test? It looks like we haven't updated the test after removing the `core::payments::payments_start_core` method from the codebase.
// #[ignore]
// #[actix_rt::test]
// async fn payments_start_core_stripe_redirect() {
// use router::configs::settings::Settings;
// let conf = Settings::new().expect("invalid settings");
//
// let state = routes::AppState {
// flow_name: String::from("default"),
// pg_pool: connection::make_pg_pool(&conf).await,
// redis_conn: connection::redis_connection(&conf).await,
// };
//
// let customer_id = format!("cust_{}", Uuid::new_v4());
// let merchant_id = "jarnura".to_string();
// let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string();
// let customer_data = api::CreateCustomerRequest {
// customer_id: customer_id.clone(),
// merchant_id: merchant_id.clone(),
// ..api::CreateCustomerRequest::default()
// };
//
// let _customer = customer_data.insert(&*state.store).await.unwrap();
//
// let merchant_account = services::authenticate(&state, "123").await.unwrap();
// let payment_attempt = storage::PaymentAttempt::find_by_payment_id_merchant_id(
// &*state.store,
// &payment_id,
// &merchant_id,
// )
// .await
// .unwrap();
// let payment_intent = storage::PaymentIntent::find_by_payment_id_merchant_id(
// &*state.store,
// &payment_id,
// &merchant_id,
// )
// .await
// .unwrap();
// let payment_intent_update = storage::PaymentIntentUpdate::ReturnUrlUpdate {
// return_url: "http://example.com/payments".to_string(),
// status: None,
// };
// payment_intent
// .update(&*state.store, payment_intent_update)
// .await
// .unwrap();
//
// let expected_response = services::ApplicationResponse::Form(services::RedirectForm {
// url: "http://example.com/payments".to_string(),
// method: services::Method::Post,
// form_fields: HashMap::from([("payment_id".to_string(), payment_id.clone())]),
// });
// let actual_response = payments_start_core(
// &state,
// merchant_account,
// api::PaymentsStartRequest {
// payment_id,
// merchant_id,
// txn_id: payment_attempt.txn_id.to_owned(),
// },
// )
// .await
// .unwrap();
// assert_eq!(expected_response, actual_response);
// }
#[cfg(feature = "v1")]
// FIXME: broken test?
#[ignore]
#[actix_rt::test]
async fn payments_create_core_adyen_no_redirect() {
use router::configs::settings::Settings;
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let customer_id = format!("cust_{}", Uuid::new_v4());
let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();
let payment_id =
id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.unwrap();
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(&merchant_id, &key_store)
.await
.unwrap();
let platform = hyperswitch_domain_models::platform::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
let req = api::PaymentsRequest {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(MinorUnit::new(6540)),
capture_on: Some(datetime!(2022-09-10 10:11:12)),
confirm: Some(true),
customer_id: Some(id_type::CustomerId::try_from(Cow::from(customer_id)).unwrap()),
description: Some("Its my first payment request".to_string()),
return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OffSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethodDataRequest {
payment_method_data: Some(api::PaymentMethodData::Card(api::Card {
card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(),
card_exp_month: "03".to_string().into(),
card_exp_year: "2030".to_string().into(),
card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "737".to_string().into(),
bank_code: None,
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
})),
billing: None,
}),
payment_method: Some(api_enums::PaymentMethod::Card),
shipping: Some(api::Address {
address: None,
phone: None,
email: None,
}),
billing: Some(api::Address {
address: None,
phone: None,
email: None,
}),
statement_descriptor_name: Some("Juspay".to_string()),
statement_descriptor_suffix: Some("Router".to_string()),
three_ds_data: None,
..Default::default()
};
let expected_response = services::ApplicationResponse::JsonWithHeaders((
api::PaymentsResponse {
payment_id: payment_id.clone(),
status: api_enums::IntentStatus::Processing,
amount: MinorUnit::new(6540),
amount_capturable: MinorUnit::new(0),
amount_received: None,
client_secret: None,
created: None,
modified_at: None,
currency: "USD".to_string(),
customer_id: None,
description: Some("Its my first payment request".to_string()),
refunds: None,
mandate_id: None,
merchant_id,
net_amount: MinorUnit::new(6540),
connector: None,
customer: None,
disputes: None,
attempts: None,
captures: None,
mandate_data: None,
setup_future_usage: None,
off_session: None,
capture_on: None,
capture_method: None,
payment_method: None,
payment_method_data: None,
payment_token: None,
shipping: None,
billing: None,
order_details: None,
email: None,
name: None,
phone: None,
return_url: None,
authentication_type: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
payment_method_type: None,
connector_label: None,
business_country: None,
business_label: None,
business_sub_label: None,
allowed_payment_method_types: None,
manual_retry_allowed: None,
connector_transaction_id: None,
frm_message: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
profile_id: None,
surcharge_details: None,
attempt_count: 1,
merchant_decision: None,
merchant_connector_id: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
browser_info: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
merchant_order_reference_id: None,
capture_before: None,
extended_authorization_applied: None,
extended_authorization_last_applied_at: None,
order_tax_amount: None,
mit_category: None,
tokenization: None,
connector_mandate_id: None,
shipping_cost: None,
card_discovery: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
issuer_error_code: None,
issuer_error_message: None,
is_iframe_redirection_enabled: None,
whole_connector_response: None,
payment_channel: None,
network_transaction_id: None,
enable_partial_authorization: None,
is_overcapture_enabled: None,
enable_overcapture: None,
network_details: None,
is_stored_credential: None,
request_extended_authorization: None,
billing_descriptor: None,
partner_merchant_identifier_details: None,
payment_method_tokenization_details: None,
},
vec![],
));
let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
state.get_req_state(),
platform,
None,
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await
.unwrap();
assert_eq!(expected_response, actual_response);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/cache.rs | crates/router/tests/cache.rs | use std::sync::Arc;
use router::{configs::settings::Settings, routes, services};
use storage_impl::redis::cache::{self, CacheKey};
mod utils;
#[actix_web::test]
async fn invalidate_existing_cache_success() {
// Arrange
Box::pin(utils::setup()).await;
let (tx, _) = tokio::sync::oneshot::channel();
let app_state = Box::pin(routes::AppState::new(
Settings::default(),
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let cache_key = "cacheKey".to_string();
let cache_key_value = "val".to_string();
let _ = state
.store
.get_redis_conn()
.unwrap()
.set_key(&cache_key.clone().into(), cache_key_value.clone())
.await;
let api_key = ("api-key", "test_admin");
let client = awc::Client::default();
cache::CONFIG_CACHE
.push(
CacheKey {
key: cache_key.clone(),
prefix: String::default(),
},
cache_key_value.clone(),
)
.await;
cache::ACCOUNTS_CACHE
.push(
CacheKey {
key: cache_key.clone(),
prefix: String::default(),
},
cache_key_value.clone(),
)
.await;
// Act
let mut response = client
.post(format!(
"http://127.0.0.1:8080/cache/invalidate/{cache_key}"
))
.insert_header(api_key)
.send()
.await
.unwrap();
// Assert
let response_body = response.body().await;
println!("invalidate Cache: {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
assert!(cache::CONFIG_CACHE
.get_val::<String>(CacheKey {
key: cache_key.clone(),
prefix: String::default()
})
.await
.is_none());
assert!(cache::ACCOUNTS_CACHE
.get_val::<String>(CacheKey {
key: cache_key,
prefix: String::default()
})
.await
.is_none());
}
#[actix_web::test]
async fn invalidate_non_existing_cache_success() {
// Arrange
Box::pin(utils::setup()).await;
let cache_key = "cacheKey".to_string();
let api_key = ("api-key", "test_admin");
let client = awc::Client::default();
// Act
let mut response = client
.post(format!(
"http://127.0.0.1:8080/cache/invalidate/{cache_key}"
))
.insert_header(api_key)
.send()
.await
.unwrap();
// Assert
let response_body = response.body().await;
println!("invalidate Cache: {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::NOT_FOUND);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/payments.rs | crates/router/tests/payments.rs | #![allow(clippy::unwrap_in_result)]
mod utils;
use std::{borrow::Cow, sync::Arc};
use common_utils::{id_type, types::MinorUnit};
use router::{
configs,
core::payments,
db::StorageImpl,
routes, services,
types::{
self,
api::{self, enums as api_enums},
},
};
use time::macros::datetime;
use tokio::sync::oneshot;
use uuid::Uuid;
// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid
// do we'll test refund and payment in same tests and later implement thread_local variables.
// When test-connector feature is enabled, you can pass the connector name in description
#[actix_web::test]
#[ignore]
// verify the API-KEY/merchant id has stripe as first choice
async fn payments_create_stripe() {
Box::pin(utils::setup()).await;
let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "MySecretApiKey");
let request = serde_json::json!({
"payment_id" : payment_id,
"merchant_id" : "jarnura",
"amount" : 1000,
"currency" : "USD",
"amount_to_capture" : 1000,
"confirm" : true,
"customer" : "test_customer",
"customer_email" : "test@gmail.com",
"customer_name" : "Test",
"description" : "stripe",
"return_url" : "https://juspay.in/",
"payment_method_data" : {"card" : {"card_number":"4242424242424242","card_exp_month":"12","card_exp_year":"29","card_holder_name":"JohnDoe","card_cvc":"123"}},
"payment_method" : "card",
"statement_descriptor_name" : "Test Merchant",
"statement_descriptor_suffix" : "US"
});
let refund_req = serde_json::json!({
"amount" : 1000,
"currency" : "USD",
"refund_id" : "refund_123",
"payment_id" : payment_id,
"merchant_id" : "jarnura",
});
let client = awc::Client::default();
let mut create_response = client
.post("http://127.0.0.1:8080/payments/create")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
let create_response_body = create_response.body().await;
println!("{create_response:?} : {create_response_body:?}");
assert_eq!(create_response.status(), awc::http::StatusCode::OK);
let mut retrieve_response = client
.get("http://127.0.0.1:8080/payments/retrieve")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
let retrieve_response_body = retrieve_response.body().await;
println!("{retrieve_response:?} =:= {retrieve_response_body:?}");
assert_eq!(retrieve_response.status(), awc::http::StatusCode::OK);
let mut refund_response = client
.post("http://127.0.0.1:8080/refunds/create")
.insert_header(api_key)
.send_json(&refund_req)
.await
.unwrap();
let refund_response_body = refund_response.body().await;
println!("{refund_response:?} =:= {refund_response_body:?}");
assert_eq!(refund_response.status(), awc::http::StatusCode::OK);
}
#[actix_web::test]
#[ignore]
// verify the API-KEY/merchant id has adyen as first choice
async fn payments_create_adyen() {
Box::pin(utils::setup()).await;
let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "321");
let request = serde_json::json!({
"payment_id" : payment_id,
"merchant_id" : "jarnura",
"amount" : 1000,
"currency" : "USD",
"amount_to_capture" : 1000,
"confirm" : true,
"customer" : "test_customer",
"customer_email" : "test@gmail.com",
"customer_name" : "Test",
"description" : "adyen",
"return_url" : "https://juspay.in/",
"payment_method_data" : {"card" : {"card_number":"5555 3412 4444 1115","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"JohnDoe","card_cvc":"737"}},
"payment_method" : "card",
"statement_descriptor_name" : "Test Merchant",
"statement_descriptor_suffix" : "US"
});
let refund_req = serde_json::json!({
"amount" : 1000,
"currency" : "USD",
"refund_id" : "refund_123",
"payment_id" : payment_id,
"merchant_id" : "jarnura",
});
let client = awc::Client::default();
let mut create_response = client
.post("http://127.0.0.1:8080/payments/create")
.insert_header(api_key) //API Key must have adyen as first choice
.send_json(&request)
.await
.unwrap();
let create_response_body = create_response.body().await;
println!("{create_response:?} : {create_response_body:?}");
assert_eq!(create_response.status(), awc::http::StatusCode::OK);
let mut retrieve_response = client
.get("http://127.0.0.1:8080/payments/retrieve")
.insert_header(api_key)
.send_json(&request)
.await
.unwrap();
let retrieve_response_body = retrieve_response.body().await;
println!("{retrieve_response:?} =:= {retrieve_response_body:?}");
assert_eq!(retrieve_response.status(), awc::http::StatusCode::OK);
let mut refund_response = client
.post("http://127.0.0.1:8080/refunds/create")
.insert_header(api_key)
.send_json(&refund_req)
.await
.unwrap();
let refund_response_body = refund_response.body().await;
println!("{refund_response:?} =:= {refund_response_body:?}");
assert_eq!(refund_response.status(), awc::http::StatusCode::OK);
}
#[actix_web::test]
// verify the API-KEY/merchant id has stripe as first choice
#[ignore]
async fn payments_create_fail() {
Box::pin(utils::setup()).await;
let payment_id = format!("test_{}", Uuid::new_v4());
let api_key = ("API-KEY", "MySecretApiKey");
let invalid_request = serde_json::json!({
"description" : "stripe",
});
let request = serde_json::json!({
"payment_id" : payment_id,
"merchant_id" : "jarnura",
"amount" : 1000,
"currency" : "USD",
"amount_to_capture" : 1000,
"confirm" : true,
"customer" : "test_customer",
"customer_email" : "test@gmail.com",
"customer_name" : "Test",
"description" : "adyen",
"return_url" : "https://juspay.in/",
"payment_method_data" : {"card" : {"card_number":"5555 3412 4444 1115","card_exp_month":"03","card_exp_year":"2030","card_holder_name":"JohnDoe","card_cvc":"737"}},
"payment_method" : "card",
"statement_descriptor_name" : "Test Merchant",
"statement_descriptor_suffix" : "US"
});
let client = awc::Client::default();
let mut invalid_response = client
.post("http://127.0.0.1:8080/payments/create")
.insert_header(api_key)
.send_json(&invalid_request)
.await
.unwrap();
let invalid_response_body = invalid_response.body().await;
println!("{invalid_response:?} : {invalid_response_body:?}");
assert_eq!(
invalid_response.status(),
awc::http::StatusCode::BAD_REQUEST
);
let mut api_key_response = client
.get("http://127.0.0.1:8080/payments/retrieve")
// .insert_header(api_key)
.send_json(&request)
.await
.unwrap();
let api_key_response_body = api_key_response.body().await;
println!("{api_key_response:?} =:= {api_key_response_body:?}");
assert_eq!(
api_key_response.status(),
awc::http::StatusCode::UNAUTHORIZED
);
}
#[actix_web::test]
#[ignore]
async fn payments_todo() {
Box::pin(utils::setup()).await;
let client = awc::Client::default();
let mut response;
let mut response_body;
let _post_endpoints = ["123/update", "123/confirm", "cancel"];
let get_endpoints = vec!["list"];
for endpoint in get_endpoints {
response = client
.get(format!("http://127.0.0.1:8080/payments/{endpoint}"))
.insert_header(("API-KEY", "MySecretApiKey"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
// for endpoint in post_endpoints {
// response = client
// .post(format!("http://127.0.0.1:8080/payments/{}", endpoint))
// .send()
// .await
// .unwrap();
// response_body = response.body().await;
// println!("{} =:= {:?} : {:?}", endpoint, response, response_body);
// assert_eq!(response.status(), awc::http::StatusCode::OK);
// }
}
#[test]
fn connector_list() {
let connector_list = types::ConnectorsList {
connectors: vec![String::from("stripe"), "adyen".to_string()],
};
let json = serde_json::to_string(&connector_list).unwrap();
println!("{}", &json);
let newlist: types::ConnectorsList = serde_json::from_str(&json).unwrap();
println!("{newlist:#?}");
assert_eq!(true, true);
}
#[cfg(feature = "v1")]
#[actix_rt::test]
#[ignore] // AWS
async fn payments_create_core() {
use configs::settings::Settings;
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();
let state = Arc::new(app_state)
.get_session_state(
&id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.unwrap();
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(&merchant_id, &key_store)
.await
.unwrap();
let platform = hyperswitch_domain_models::platform::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
let payment_id =
id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();
let req = api::PaymentsRequest {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(MinorUnit::new(6540)),
capture_on: Some(datetime!(2022-09-10 11:12)),
confirm: Some(true),
customer_id: None,
email: None,
name: None,
description: Some("Its my first payment request".to_string()),
return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OnSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethodDataRequest {
payment_method_data: Some(api::PaymentMethodData::Card(api::Card {
card_number: "4242424242424242".to_string().try_into().unwrap(),
card_exp_month: "10".to_string().into(),
card_exp_year: "35".to_string().into(),
card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
})),
billing: None,
}),
payment_method: Some(api_enums::PaymentMethod::Card),
shipping: Some(api::Address {
address: None,
phone: None,
email: None,
}),
billing: Some(api::Address {
address: None,
phone: None,
email: None,
}),
statement_descriptor_name: Some("Hyperswtich".to_string()),
statement_descriptor_suffix: Some("Hyperswitch".to_string()),
three_ds_data: None,
..Default::default()
};
let expected_response = api::PaymentsResponse {
payment_id,
status: api_enums::IntentStatus::Succeeded,
amount: MinorUnit::new(6540),
amount_capturable: MinorUnit::new(0),
amount_received: None,
client_secret: None,
created: None,
modified_at: None,
currency: "USD".to_string(),
customer_id: None,
description: Some("Its my first payment request".to_string()),
refunds: None,
mandate_id: None,
merchant_id,
net_amount: MinorUnit::new(6540),
connector: None,
customer: None,
disputes: None,
attempts: None,
captures: None,
mandate_data: None,
setup_future_usage: None,
off_session: None,
capture_on: None,
capture_method: None,
payment_method: None,
payment_method_data: None,
payment_token: None,
shipping: None,
billing: None,
order_details: None,
email: None,
name: None,
phone: None,
return_url: None,
authentication_type: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
payment_method_type: None,
connector_label: None,
business_country: None,
business_label: None,
business_sub_label: None,
allowed_payment_method_types: None,
manual_retry_allowed: None,
connector_transaction_id: None,
frm_message: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
profile_id: None,
surcharge_details: None,
attempt_count: 1,
merchant_decision: None,
merchant_connector_id: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
mit_category: None,
tokenization: None,
browser_info: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
merchant_order_reference_id: None,
capture_before: None,
extended_authorization_applied: None,
extended_authorization_last_applied_at: None,
order_tax_amount: None,
connector_mandate_id: None,
shipping_cost: None,
card_discovery: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
issuer_error_code: None,
issuer_error_message: None,
is_iframe_redirection_enabled: None,
whole_connector_response: None,
payment_channel: None,
network_transaction_id: None,
enable_partial_authorization: None,
is_overcapture_enabled: None,
enable_overcapture: None,
network_details: None,
is_stored_credential: None,
request_extended_authorization: None,
billing_descriptor: None,
partner_merchant_identifier_details: None,
payment_method_tokenization_details: None,
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
state.get_req_state(),
platform,
None,
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await
.unwrap();
assert_eq!(expected_response, actual_response);
}
// #[actix_rt::test]
// async fn payments_start_core_stripe_redirect() {
// use configs::settings::Settings;
// let conf = Settings::new().expect("invalid settings");
// let state = routes::AppState {
// flow_name: String::from("default"),
// pg_conn: connection::pg_connection_read(&conf),
// redis_conn: connection::redis_connection(&conf).await,
// };
// let customer_id = format!("cust_{}", Uuid::new_v4());
// let merchant_id = "jarnura".to_string();
// let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string();
// let customer_data = api::CreateCustomerRequest {
// customer_id: customer_id.clone(),
// merchant_id: merchant_id.clone(),
// ..api::CreateCustomerRequest::default()
// };
// let _customer = customer_data.insert(&state.pg_conn).unwrap();
// let merchant_account = services::authenticate(&state, "MySecretApiKey").unwrap();
// let payment_attempt = storage::PaymentAttempt::find_by_payment_id_merchant_id(
// &state.pg_conn,
// &payment_id,
// &merchant_id,
// )
// .unwrap();
// let payment_intent = storage::PaymentIntent::find_by_payment_id_merchant_id(
// &state.pg_conn,
// &payment_id,
// &merchant_id,
// )
// .unwrap();
// let payment_intent_update = storage::PaymentIntentUpdate::ReturnUrlUpdate {
// return_url: "http://example.com/payments".to_string(),
// status: None,
// };
// payment_intent
// .update(&state.pg_conn, payment_intent_update)
// .unwrap();
// let expected_response = services::ApplicationResponse::Form(services::RedirectForm {
// url: "http://example.com/payments".to_string(),
// method: services::Method::Post,
// form_fields: HashMap::from([("payment_id".to_string(), payment_id.clone())]),
// });
// let actual_response = payments_start_core(
// &state,
// merchant_account,
// api::PaymentsStartRequest {
// payment_id,
// merchant_id,
// txn_id: payment_attempt.txn_id.to_owned(),
// },
// )
// .await
// .unwrap();
// assert_eq!(expected_response, actual_response);
// }
#[cfg(feature = "v1")]
#[actix_rt::test]
#[ignore]
async fn payments_create_core_adyen_no_redirect() {
use crate::configs::settings::Settings;
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = Arc::new(app_state)
.get_session_state(
&id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let payment_id =
id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();
let customer_id = format!("cust_{}", Uuid::new_v4());
let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.unwrap();
let merchant_account = state
.store
.find_merchant_account_by_merchant_id(&merchant_id, &key_store)
.await
.unwrap();
let platform = hyperswitch_domain_models::platform::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
let req = api::PaymentsRequest {
payment_id: Some(api::PaymentIdType::PaymentIntentId(payment_id.clone())),
merchant_id: Some(merchant_id.clone()),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
amount_to_capture: Some(MinorUnit::new(6540)),
capture_on: Some(datetime!(2022-09-10 10:11:12)),
confirm: Some(true),
customer_id: Some(id_type::CustomerId::try_from(Cow::from(customer_id)).unwrap()),
description: Some("Its my first payment request".to_string()),
return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OnSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethodDataRequest {
payment_method_data: Some(api::PaymentMethodData::Card(api::Card {
card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(),
card_exp_month: "03".to_string().into(),
card_exp_year: "2030".to_string().into(),
card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "737".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
nick_name: Some(masking::Secret::new("nick_name".into())),
})),
billing: None,
}),
payment_method: Some(api_enums::PaymentMethod::Card),
shipping: Some(api::Address {
address: None,
phone: None,
email: None,
}),
billing: Some(api::Address {
address: None,
phone: None,
email: None,
}),
statement_descriptor_name: Some("Juspay".to_string()),
statement_descriptor_suffix: Some("Router".to_string()),
three_ds_data: None,
..Default::default()
};
let expected_response = services::ApplicationResponse::JsonWithHeaders((
api::PaymentsResponse {
payment_id: payment_id.clone(),
status: api_enums::IntentStatus::Processing,
amount: MinorUnit::new(6540),
amount_capturable: MinorUnit::new(0),
amount_received: None,
client_secret: None,
created: None,
modified_at: None,
currency: "USD".to_string(),
customer_id: None,
description: Some("Its my first payment request".to_string()),
refunds: None,
mandate_id: None,
merchant_id,
net_amount: MinorUnit::new(6540),
connector: None,
customer: None,
disputes: None,
attempts: None,
captures: None,
mandate_data: None,
setup_future_usage: None,
off_session: None,
capture_on: None,
capture_method: None,
payment_method: None,
payment_method_data: None,
payment_token: None,
shipping: None,
billing: None,
order_details: None,
email: None,
name: None,
phone: None,
return_url: None,
authentication_type: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
next_action: None,
cancellation_reason: None,
error_code: None,
error_message: None,
unified_code: None,
unified_message: None,
payment_experience: None,
payment_method_type: None,
connector_label: None,
business_country: None,
business_label: None,
business_sub_label: None,
allowed_payment_method_types: None,
manual_retry_allowed: None,
connector_transaction_id: None,
frm_message: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
reference_id: None,
payment_link: None,
profile_id: None,
surcharge_details: None,
attempt_count: 1,
merchant_decision: None,
merchant_connector_id: None,
incremental_authorization_allowed: None,
authorization_count: None,
incremental_authorizations: None,
external_authentication_details: None,
external_3ds_authentication_attempted: None,
expires_on: None,
fingerprint: None,
browser_info: None,
mit_category: None,
tokenization: None,
payment_method_id: None,
payment_method_status: None,
updated: None,
split_payments: None,
frm_metadata: None,
merchant_order_reference_id: None,
capture_before: None,
extended_authorization_applied: None,
extended_authorization_last_applied_at: None,
order_tax_amount: None,
connector_mandate_id: None,
shipping_cost: None,
card_discovery: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
issuer_error_code: None,
issuer_error_message: None,
is_iframe_redirection_enabled: None,
whole_connector_response: None,
payment_channel: None,
network_transaction_id: None,
enable_partial_authorization: None,
is_overcapture_enabled: None,
enable_overcapture: None,
network_details: None,
is_stored_credential: None,
request_extended_authorization: None,
billing_descriptor: None,
partner_merchant_identifier_details: None,
payment_method_tokenization_details: None,
},
vec![],
));
let actual_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
state.get_req_state(),
platform,
None,
payments::PaymentCreate,
req,
services::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await
.unwrap();
assert_eq!(expected_response, actual_response);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/worldpayvantiv.rs | crates/router/tests/connectors/worldpayvantiv.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 WorldpayvantivTest;
impl ConnectorActions for WorldpayvantivTest {}
impl utils::Connector for WorldpayvantivTest {
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: WorldpayvantivTest = WorldpayvantivTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/bamboraapac.rs | crates/router/tests/connectors/bamboraapac.rs | use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct BamboraapacTest;
impl ConnectorActions for BamboraapacTest {}
impl utils::Connector for BamboraapacTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Adyen;
utils::construct_connector_data_old(
Box::new(Adyen::new()),
types::Connector::Adyen,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.bamboraapac
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"bamboraapac".to_string()
}
}
static CONNECTOR: BamboraapacTest = BamboraapacTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/airwallex.rs | crates/router/tests/connectors/airwallex.rs | use std::str::FromStr;
use hyperswitch_domain_models::address::{Address, AddressDetails};
use masking::{PeekInterface, Secret};
use router::types::{self, domain, storage::enums, AccessToken};
use crate::{
connector_auth,
utils::{self, Connector, ConnectorActions},
};
#[derive(Clone, Copy)]
struct AirwallexTest;
impl ConnectorActions for AirwallexTest {}
static CONNECTOR: AirwallexTest = AirwallexTest {};
impl Connector for AirwallexTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Airwallex;
utils::construct_connector_data_old(
Box::new(Airwallex::new()),
types::Connector::Airwallex,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.airwallex
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"airwallex".to_string()
}
}
fn get_access_token() -> Option<AccessToken> {
match CONNECTOR.get_auth_token() {
types::ConnectorAuthType::BodyKey { api_key, key1 } => Some(AccessToken {
token: api_key,
expires: key1.peek().parse::<i64>().unwrap(),
}),
_ => None,
}
}
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
access_token: get_access_token(),
address: Some(types::PaymentAddress::new(
None,
None,
Some(Address {
address: Some(AddressDetails {
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Doe".to_string())),
..Default::default()
}),
phone: None,
email: None,
}),
None,
)),
..Default::default()
})
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4035501000000008").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
card_cvc: Secret::new("123".to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
co_badged_card_data: None,
}),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
router_return_url: Some("https://google.com".to_string()),
complete_authorize_url: Some("https://google.com".to_string()),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
// #[serial_test::serial]
#[actix_web::test]
#[ignore]
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).
// #[serial_test::serial]
#[actix_web::test]
#[ignore]
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).
// #[serial_test::serial]
#[actix_web::test]
#[ignore]
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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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(),
),
..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).
// #[serial_test::serial]
#[actix_web::test]
#[ignore]
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).
// #[serial_test::serial]
#[actix_web::test]
#[ignore]
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).
// #[serial_test::serial]
#[actix_web::test]
#[ignore]
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).
// #[serial_test::serial]
#[actix_web::test]
#[ignore]
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 card number.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid card number".to_string(),
);
}
// Creates a payment with incorrect CVC.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid card cvc".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid expiry month".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"payment_method.card should not be expired".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[serial_test::serial]
#[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,
"The PaymentIntent status SUCCEEDED is invalid for operation cancel."
);
}
// Captures a payment using invalid connector payment id.
#[serial_test::serial]
#[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(
"The requested endpoint does not exist [/api/v1/pa/payment_intents/123456789/capture]"
)
);
}
// Refunds a payment with refund amount higher than payment amount.
// #[serial_test::serial]
#[actix_web::test]
#[ignore]
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/stripe.rs | crates/router/tests/connectors/stripe.rs | use std::str::FromStr;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
struct Stripe;
impl ConnectorActions for Stripe {}
impl utils::Connector for Stripe {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Stripe;
utils::construct_connector_data_old(
Box::new(Stripe::new()),
types::Connector::Stripe,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.stripe
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"stripe".to_string()
}
}
fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4242424242424242").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = Stripe {}
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
#[actix_web::test]
async fn should_make_payment() {
let response = Stripe {}
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
#[actix_web::test]
async fn should_capture_already_authorized_payment() {
let connector = Stripe {};
let response = connector
.authorize_and_capture_payment(get_payment_authorize_data(), None, None)
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged);
}
#[actix_web::test]
async fn should_partially_capture_already_authorized_payment() {
let connector = Stripe {};
let response = connector
.authorize_and_capture_payment(
get_payment_authorize_data(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged);
}
#[actix_web::test]
async fn should_sync_authorized_payment() {
let connector = Stripe {};
let authorize_response = connector
.authorize_payment(get_payment_authorize_data(), None)
.await
.unwrap();
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()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
#[actix_web::test]
async fn should_sync_payment() {
let connector = Stripe {};
let authorize_response = connector
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = connector
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
#[actix_web::test]
async fn should_void_already_authorized_payment() {
let connector = Stripe {};
let response = connector
.authorize_and_void_payment(
get_payment_authorize_data(),
Some(types::PaymentsCancelData {
connector_transaction_id: "".to_string(), // this connector_transaction_id will be ignored and the transaction_id from payment authorize data will be used for void
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
None,
)
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided);
}
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let response = Stripe {}
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4024007134364842").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(
x.reason.unwrap(),
"Your card was declined. Your request was in test mode, but used a non test (live) card. For a list of valid test cards, visit: https://stripe.com/docs/testing.",
);
}
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = Stripe {}
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("13".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(
x.reason.unwrap(),
"Your card's expiration month is invalid.",
);
}
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_year() {
let response = Stripe {}
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2022".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(x.reason.unwrap(), "Your card's expiration year is invalid.");
}
#[actix_web::test]
async fn should_fail_payment_for_invalid_card_cvc() {
let response = Stripe {}
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(x.reason.unwrap(), "Your card's security code is invalid.");
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let connector = Stripe {};
// Authorize
let authorize_response = connector
.make_payment(get_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
// Void
let void_response = connector
.void_payment(txn_id.unwrap(), None, None)
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().reason.unwrap(),
"You cannot cancel this PaymentIntent because it has a status of succeeded. Only a PaymentIntent with one of the following statuses may be canceled: requires_payment_method, requires_capture, requires_confirmation, requires_action, processing."
);
}
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let connector = Stripe {};
let response = connector
.capture_payment("12345".to_string(), None, None)
.await
.unwrap();
let err = response.response.unwrap_err();
assert_eq!(
err.reason.unwrap(),
"No such payment_intent: '12345'".to_string()
);
assert_eq!(err.code, "resource_missing".to_string());
}
#[actix_web::test]
async fn should_refund_succeeded_payment() {
let connector = Stripe {};
let response = connector
.make_payment_and_refund(get_payment_authorize_data(), None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let connector = Stripe {};
let response = connector
.auth_capture_and_refund(get_payment_authorize_data(), None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let connector = Stripe {};
let refund_response = connector
.make_payment_and_refund(
get_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let connector = Stripe {};
let response = connector
.auth_capture_and_refund(
get_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
let connector = Stripe {};
connector
.make_payment_and_multiple_refund(
get_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await;
}
#[actix_web::test]
async fn should_fail_refund_for_invalid_amount() {
let connector = Stripe {};
let response = connector
.make_payment_and_refund(
get_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"Refund amount ($1.50) is greater than charge amount ($1.00)",
);
}
#[actix_web::test]
async fn should_sync_refund() {
let connector = Stripe {};
let refund_response = connector
.make_payment_and_refund(get_payment_authorize_data(), None, None)
.await
.unwrap();
let response = connector
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let connector = Stripe {};
let refund_response = connector
.auth_capture_and_refund(get_payment_authorize_data(), None, None)
.await
.unwrap();
let response = connector
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/mifinity.rs | crates/router/tests/connectors/mifinity.rs | use masking::Secret;
use router::types::{self, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct MifinityTest;
impl ConnectorActions for MifinityTest {}
impl utils::Connector for MifinityTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Mifinity;
utils::construct_connector_data_old(
Box::new(Mifinity::new()),
types::Connector::Mifinity,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.mifinity
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"mifinity".to_string()
}
}
static CONNECTOR: MifinityTest = MifinityTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/tesouro.rs | crates/router/tests/connectors/tesouro.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 TesouroTest;
impl ConnectorActions for TesouroTest {}
impl utils::Connector for TesouroTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Tesouro;
utils::construct_connector_data_old(
Box::new(Tesouro::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.tesouro
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"tesouro".to_string()
}
}
static CONNECTOR: TesouroTest = TesouroTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/bambora.rs | crates/router/tests/connectors/bambora.rs | use std::str::FromStr;
use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct BamboraTest;
impl ConnectorActions for BamboraTest {}
impl utils::Connector for BamboraTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Bambora;
utils::construct_connector_data_old(
Box::new(Bambora::new()),
types::Connector::Bambora,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.bambora
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"bambora".to_string()
}
}
static CONNECTOR: BamboraTest = BamboraTest {};
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_default_payment_authorize_data(), None)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(get_default_payment_authorize_data(), None, None)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
get_default_payment_authorize_data(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_default_payment_authorize_data(), None)
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
mandate_id: None,
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta: None,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
get_default_payment_authorize_data(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
None,
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(get_default_payment_authorize_data(), None, None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
get_default_payment_authorize_data(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// 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(get_default_payment_authorize_data(), None, None, None)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(get_default_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(get_default_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
mandate_id: None,
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: Some(enums::CaptureMethod::Automatic),
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta: None,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(get_default_payment_authorize_data(), None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
get_default_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// 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(get_default_payment_authorize_data(), None, None)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
card_exp_year: Secret::new("25".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid Card Number".to_string(),
);
}
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().reason,
Some(r#"[{"field":"card:cvd","message":"Invalid card CVD"},{"field":"card:cvd","message":"Invalid card CVD"}]"#.to_string())
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().reason,
Some(r#"[{"field":"card:expiry_month","message":"Invalid expiry date"}]"#.to_string())
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().reason,
Some(r#"[{"field":"card:expiry_year","message":"Invalid expiration year"}]"#.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(get_default_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, None)
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"Transaction cannot be adjusted"
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("Missing or invalid payment information - Please validate all required payment information.")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_succeed_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
get_default_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success
);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/hyperswitch_vault.rs | crates/router/tests/connectors/hyperswitch_vault.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 HyperswitchVaultTest;
impl ConnectorActions for HyperswitchVaultTest {}
impl utils::Connector for HyperswitchVaultTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::HyperswitchVault;
utils::construct_connector_data_old(
Box::new(&HyperswitchVault),
types::Connector::HyperswitchVault,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.hyperswitch_vault
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"hyperswitch_vault".to_string()
}
}
static CONNECTOR: HyperswitchVaultTest = HyperswitchVaultTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/phonepe.rs | crates/router/tests/connectors/phonepe.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 PhonepeTest;
impl ConnectorActions for PhonepeTest {}
impl utils::Connector for PhonepeTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Phonepe;
utils::construct_connector_data_old(
Box::new(Phonepe::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.phonepe
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"phonepe".to_string()
}
}
static CONNECTOR: PhonepeTest = PhonepeTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/coingate.rs | crates/router/tests/connectors/coingate.rs | use masking::Secret;
use router::types::{self, api, storage::enums};
use crate::utils::{self, ConnectorActions};
use test_utils::connector_auth;
#[derive(Clone, Copy)]
struct CoingateTest;
impl ConnectorActions for CoingateTest {}
impl utils::Connector for CoingateTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Coingate;
api::ConnectorData {
connector: Box::new(Coingate::new()),
connector_name: types::Connector::Coingate,
get_token: types::api::GetToken::Connector,
merchant_connector_id: None,
}
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.coingate
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"coingate".to_string()
}
}
static CONNECTOR: CoingateTest = CoingateTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: types::api::PaymentMethodData::Card(api::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: api::PaymentMethodData::Card(api::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: api::PaymentMethodData::Card(api::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/globepay.rs | crates/router/tests/connectors/globepay.rs | use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct GlobepayTest;
impl ConnectorActions for GlobepayTest {}
impl utils::Connector for GlobepayTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Globepay;
utils::construct_connector_data_old(
Box::new(Globepay::new()),
types::Connector::Globepay,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.globepay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"globepay".to_string()
}
}
static CONNECTOR: GlobepayTest = GlobepayTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/bluesnap.rs | crates/router/tests/connectors/bluesnap.rs | use std::str::FromStr;
use common_utils::pii::Email;
use hyperswitch_domain_models::address::{Address, AddressDetails};
use masking::Secret;
use router::types::{self, domain, storage::enums, ConnectorAuthType, PaymentAddress};
use crate::{
connector_auth,
utils::{self, ConnectorActions, PaymentInfo},
};
#[derive(Clone, Copy)]
struct BluesnapTest;
impl ConnectorActions for BluesnapTest {}
static CONNECTOR: BluesnapTest = BluesnapTest {};
impl utils::Connector for BluesnapTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Bluesnap;
utils::construct_connector_data_old(
Box::new(Bluesnap::new()),
types::Connector::Bluesnap,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.bluesnap
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"bluesnap".to_string()
}
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("test@gmail.com").unwrap()),
..utils::PaymentAuthorizeType::default().0
})
}
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
first_name: Some(Secret::new("joseph".to_string())),
last_name: Some(Secret::new("Doe".to_string())),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_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).
#[serial_test::serial]
#[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_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_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()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[serial_test::serial]
#[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_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(payment_method_details(), None, None, get_payment_info())
.await
.unwrap();
let rsync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
rsync_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[serial_test::serial]
#[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_payment_info(),
)
.await
.unwrap();
let rsync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
rsync_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(payment_method_details(), None, None, get_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_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(),
),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_payment_info())
.await
.unwrap();
let rsync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
rsync_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[serial_test::serial]
#[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_payment_info(),
)
.await
.unwrap();
let rsync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
rsync_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let transaction_id = utils::get_connector_transaction_id(authorize_response.response).unwrap();
for _x in 0..2 {
tokio::time::sleep(std::time::Duration::from_secs(5)).await; // to avoid 404 error
let refund_response = CONNECTOR
.refund_payment(
transaction_id.clone(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
let rsync_response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
rsync_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment with incorrect CVC.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("test@gmail.com").unwrap()),
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"VALIDATION_GENERAL_FAILURE".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("test@gmail.com").unwrap()),
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"VALIDATION_GENERAL_FAILURE".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("test@gmail.com").unwrap()),
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"VALIDATION_GENERAL_FAILURE".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_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, None)
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"TRANSACTION_ALREADY_CAPTURED"
);
}
// Captures a payment using invalid connector payment id.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, None)
.await
.unwrap();
capture_response
.response
.unwrap_err()
.message
.contains("is not authorized to view transaction");
}
// Refunds a payment with refund amount higher than payment amount.
#[serial_test::serial]
#[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_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"REFUND_MAX_AMOUNT_FAILURE",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/authipay.rs | crates/router/tests/connectors/authipay.rs | use std::str::FromStr;
use masking::Secret;
use router::{
core::errors,
types::{self, api, storage::enums},
};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct AuthipayTest;
impl ConnectorActions for AuthipayTest {}
impl utils::Connector for AuthipayTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Authipay;
api::ConnectorData {
connector: Box::new(Authipay::new()),
connector_name: types::Connector::Authipay,
get_token: types::api::GetToken::Connector,
merchant_connector_id: None,
}
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.authipay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"authipay".to_string()
}
}
static CONNECTOR: AuthipayTest = AuthipayTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
payment_id: utils::get_payment_id(),
payment_method: enums::PaymentMethod::Card,
payment_method_type: Some(enums::PaymentMethodType::Credit),
amount: 100, // $1.00
currency: enums::Currency::USD,
capture_method: Some(enums::CaptureMethod::Manual),
mandate_id: None,
setup_future_usage: None,
off_session: None,
merchant_connector_id: None,
browser_info: None,
recurring_mandate_payment: None,
router_return_url: None,
connector_meta: None,
allowed_payment_method_types: None,
pm_token: None,
payment_experience: None,
webhook_url: None,
customer_id: None,
surcharge_details: None,
connector_request_reference_id: None,
request_incremental_authorization: None,
metadata: None,
payment_type: None,
session_token: None,
terminal_id: None,
card_network: None,
capture_on: None,
incremental_authorization_allowed: None,
})
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: api::PaymentMethodData::Card(api::Card {
card_number: cards::CardNumber::from_str("4035874000424977").unwrap(), // Visa test card from Authipay specs
card_exp_month: Secret::new("12".to_string()),
card_exp_year: Secret::new("2024".to_string()),
card_cvc: Secret::new("123".to_string()),
card_holder_name: Secret::new("John Doe".to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: Some("Default Card".to_string()),
}),
currency: enums::Currency::USD,
amount: 100, // $1.00
router_return_url: String::from("http://localhost:8080/"),
payment_method_type: Some(enums::PaymentMethodType::Credit),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: types::api::PaymentMethodData::Card(api::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: api::PaymentMethodData::Card(api::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: api::PaymentMethodData::Card(api::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/plaid.rs | crates/router/tests/connectors/plaid.rs | use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, Connector, ConnectorActions};
#[derive(Clone, Copy)]
struct PlaidTest;
impl ConnectorActions for PlaidTest {}
static CONNECTOR: PlaidTest = PlaidTest {};
impl Connector for PlaidTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Plaid;
utils::construct_connector_data_old(
Box::new(Plaid::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.plaid
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"plaid".to_string()
}
}
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid card cvc.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/authorizedotnet.rs | crates/router/tests/connectors/authorizedotnet.rs | use std::str::FromStr;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions, PaymentInfo},
};
#[derive(Clone, Copy)]
struct AuthorizedotnetTest;
impl ConnectorActions for AuthorizedotnetTest {}
impl utils::Connector for AuthorizedotnetTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Authorizedotnet;
utils::construct_connector_data_old(
Box::new(Authorizedotnet::new()),
types::Connector::Authorizedotnet,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.authorizedotnet
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"authorizedotnet".to_string()
}
}
static CONNECTOR: AuthorizedotnetTest = AuthorizedotnetTest {};
fn get_payment_method_data() -> domain::Card {
domain::Card {
card_number: cards::CardNumber::from_str("5424000000000015").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
card_cvc: Secret::new("123".to_string()),
..Default::default()
}
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let authorize_response = CONNECTOR
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 300,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
Some(PaymentInfo::with_default_billing_name()),
)
.await
.expect("Authorize payment response");
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id =
utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(psync_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 authorize_response = CONNECTOR
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 301,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
Some(PaymentInfo::with_default_billing_name()),
)
.await
.expect("Authorize payment response");
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id =
utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(psync_response.status, enums::AttemptStatus::Authorized);
let cap_response = CONNECTOR
.capture_payment(
txn_id.clone(),
Some(types::PaymentsCaptureData {
amount_to_capture: 301,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
assert_eq!(cap_response.status, enums::AttemptStatus::Pending);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 302,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
Some(PaymentInfo::with_default_billing_name()),
)
.await
.expect("Authorize payment response");
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id =
utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(psync_response.status, enums::AttemptStatus::Authorized);
let cap_response = CONNECTOR
.capture_payment(
txn_id.clone(),
Some(types::PaymentsCaptureData {
amount_to_capture: 150,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
assert_eq!(cap_response.status, enums::AttemptStatus::Pending);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
}
// 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(
Some(types::PaymentsAuthorizeData {
amount: 303,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
Some(PaymentInfo::with_default_billing_name()),
)
.await
.expect("Authorize payment response");
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id =
utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default();
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).x
#[actix_web::test]
async fn should_void_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(
Some(types::PaymentsAuthorizeData {
amount: 304,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
Some(PaymentInfo::with_default_billing_name()),
)
.await
.expect("Authorize payment response");
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
let txn_id =
utils::get_connector_transaction_id(authorize_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(psync_response.status, enums::AttemptStatus::Authorized);
let void_response = CONNECTOR
.void_payment(
txn_id,
Some(types::PaymentsCancelData {
amount: Some(304),
..utils::PaymentCancelType::default().0
}),
None,
)
.await
.expect("Void response");
assert_eq!(void_response.status, enums::AttemptStatus::VoidInitiated)
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let cap_response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
amount: 310,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(cap_response.status, enums::AttemptStatus::Pending);
let txn_id = utils::get_connector_transaction_id(cap_response.response).unwrap_or_default();
let psync_response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::CaptureInitiated,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id.clone()),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(
psync_response.status,
enums::AttemptStatus::CaptureInitiated
);
}
// 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(
Some(types::PaymentsAuthorizeData {
amount: 311,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
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::Pending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: None,
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::CaptureInitiated);
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
"60217566768".to_string(),
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment with empty card number.
#[actix_web::test]
async fn should_fail_payment_for_empty_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(
x.message,
"The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardNumber' element is invalid - The value XX is invalid according to its datatype 'String' - The actual length is less than the MinLength value.",
);
}
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardCode' element is invalid - The value XXXXXXX is invalid according to its datatype 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:cardCode' - The actual length is greater than the MaxLength value.".to_string(),
);
}
// todo()
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Credit card expiration date is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The credit card has expired.".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(
Some(types::PaymentsAuthorizeData {
amount: 307,
payment_method_data: domain::PaymentMethodData::Card(get_payment_method_data()),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, None)
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"The 'AnetApi/xml/v1/schema/AnetApiSchema.xsd:amount' element is invalid - The value '' is invalid according to its datatype 'http://www.w3.org/2001/XMLSchema:decimal' - The string '' is not a valid Decimal value."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
"The transaction cannot be found."
);
}
#[actix_web::test]
#[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."]
async fn should_partially_refund_manually_captured_payment() {}
#[actix_web::test]
#[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."]
async fn should_refund_manually_captured_payment() {}
#[actix_web::test]
#[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."]
async fn should_sync_manually_captured_refund() {}
#[actix_web::test]
#[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."]
async fn should_refund_auto_captured_payment() {}
#[actix_web::test]
#[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."]
async fn should_partially_refund_succeeded_payment() {}
#[actix_web::test]
#[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."]
async fn should_refund_succeeded_payment_multiple_times() {}
#[actix_web::test]
#[ignore = "refunds tests are ignored for this connector because it takes one day for a payment to be settled."]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/dwolla.rs | crates/router/tests/connectors/dwolla.rs | use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct DwollaTest;
impl ConnectorActions for DwollaTest {}
impl utils::Connector for DwollaTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Dwolla;
utils::construct_connector_data_old(
Box::new(Dwolla::new()),
types::Connector::DummyConnector1,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.dwolla
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"dwolla".to_string()
}
}
static CONNECTOR: DwollaTest = DwollaTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/gpayments.rs | crates/router/tests/connectors/gpayments.rs | use router::types;
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
#[allow(dead_code)]
struct GpaymentsTest;
impl ConnectorActions for GpaymentsTest {}
impl utils::Connector for GpaymentsTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Gpayments;
utils::construct_connector_data_old(
Box::new(Gpayments::new()),
types::Connector::Threedsecureio,
// Added as Dummy connector as template code is added for future usage
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.gpayments
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"gpayments".to_string()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/amazonpay.rs | crates/router/tests/connectors/amazonpay.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 AmazonpayTest;
impl ConnectorActions for AmazonpayTest {}
impl utils::Connector for AmazonpayTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Amazonpay;
utils::construct_connector_data_old(
Box::new(Amazonpay::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.amazonpay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"amazonpay".to_string()
}
}
static CONNECTOR: AmazonpayTest = AmazonpayTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/vgs.rs | crates/router/tests/connectors/vgs.rs | use masking::Secret;
use router::types::{self, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct VgsTest;
impl ConnectorActions for VgsTest {}
impl utils::Connector for VgsTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Vgs;
utils::construct_connector_data_old(
Box::new(&Vgs),
types::Connector::Vgs,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.vgs
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"vgs".to_string()
}
}
static CONNECTOR: VgsTest = VgsTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/opayo.rs | crates/router/tests/connectors/opayo.rs | use std::str::FromStr;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct OpayoTest;
impl ConnectorActions for OpayoTest {}
impl utils::Connector for OpayoTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Opayo;
utils::construct_connector_data_old(
Box::new(Opayo::new()),
// Remove `dummy_connector` feature gate from module in `main.rs` when updating this to use actual connector variant
types::Connector::DummyConnector1,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.opayo
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"opayo".to_string()
}
}
static CONNECTOR: OpayoTest = OpayoTest {};
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 card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card number is incorrect.".to_string(),
);
}
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/paystack.rs | crates/router/tests/connectors/paystack.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 PaystackTest;
impl ConnectorActions for PaystackTest {}
impl utils::Connector for PaystackTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Paystack;
utils::construct_connector_data_old(
Box::new(Paystack::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.paystack
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"paystack".to_string()
}
}
static CONNECTOR: PaystackTest = PaystackTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/boku.rs | crates/router/tests/connectors/boku.rs | use masking::Secret;
use router::types::{self, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct BokuTest;
impl ConnectorActions for BokuTest {}
impl utils::Connector for BokuTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Boku;
utils::construct_connector_data_old(
Box::new(Boku::new()),
types::Connector::Boku,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.boku
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"boku".to_string()
}
}
static CONNECTOR: BokuTest = BokuTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/jpmorgan.rs | crates/router/tests/connectors/jpmorgan.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 JpmorganTest;
impl JpmorganTest {
#[allow(dead_code)]
fn new() -> Self {
Self
}
}
impl ConnectorActions for JpmorganTest {}
impl utils::Connector for JpmorganTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Jpmorgan;
utils::construct_connector_data_old(
Box::new(Jpmorgan::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.jpmorgan
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"jpmorgan".to_string()
}
}
static CONNECTOR: JpmorganTest = JpmorganTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/santander.rs | crates/router/tests/connectors/santander.rs | use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct SantanderTest;
impl ConnectorActions for SantanderTest {}
impl utils::Connector for SantanderTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Santander;
utils::construct_connector_data_old(
Box::new(Santander::new()),
types::Connector::DummyConnector1,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.santander
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"santander".to_string()
}
}
static CONNECTOR: SantanderTest = SantanderTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/mollie.rs | crates/router/tests/connectors/mollie.rs | use router::types;
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[allow(dead_code)]
#[derive(Clone, Copy)]
struct MollieTest;
impl ConnectorActions for MollieTest {}
impl utils::Connector for MollieTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Mollie;
utils::construct_connector_data_old(
Box::new(Mollie::new()),
types::Connector::Mollie,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.mollie
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"mollie".to_string()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/paypal.rs | crates/router/tests/connectors/paypal.rs | use std::str::FromStr;
use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums, AccessToken, ConnectorAuthType};
use crate::{
connector_auth,
utils::{self, Connector, ConnectorActions},
};
struct PaypalTest;
impl ConnectorActions for PaypalTest {}
impl Connector for PaypalTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Paypal;
utils::construct_connector_data_old(
Box::new(Paypal::new()),
types::Connector::Paypal,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.paypal
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"paypal".to_string()
}
}
static CONNECTOR: PaypalTest = PaypalTest {};
fn get_access_token() -> Option<AccessToken> {
let connector = PaypalTest {};
match connector.get_auth_token() {
ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken {
token: api_key,
expires: 18600,
}),
_ => None,
}
}
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
access_token: get_access_token(),
..Default::default()
})
}
fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4000020000000000").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_data(), 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 authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta,
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
mandate_id: None,
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
encoded_data: None,
capture_method: None,
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
..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 authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.void_payment(
txn_id,
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
connector_meta,
..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]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_refund_manually_captured_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
let refund_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let response = CONNECTOR
.refund_payment(
refund_txn_id,
Some(types::RefundsData {
..utils::PaymentRefundType::default().0
}),
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]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_partially_refund_manually_captured_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
let refund_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let response = CONNECTOR
.refund_payment(
refund_txn_id,
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]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_sync_manually_captured_refund() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
let refund_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let refund_response = CONNECTOR
.refund_payment(
refund_txn_id,
Some(types::RefundsData {
..utils::PaymentRefundType::default().0
}),
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(get_payment_data(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
assert_eq!(
authorize_response.status.clone(),
enums::AttemptStatus::Pending
);
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone());
assert_ne!(txn_id, None, "Empty connector transaction id");
let connector_meta = utils::get_connector_metadata(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
mandate_id: None,
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: Some(enums::CaptureMethod::Automatic),
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
amount: MinorUnit::new(100),
integrity_object: None,
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(get_payment_data(), 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]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_partially_refund_succeeded_payment() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
let refund_response = CONNECTOR
.refund_payment(
txn_id,
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]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_refund_succeeded_payment_multiple_times() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
for _x in 0..2 {
let refund_response = CONNECTOR
.refund_payment(
txn_id.clone(),
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,
);
}
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(get_payment_data(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.clone().unwrap_err().message,
"Request is not well-formed, syntactically incorrect, or violates schema.",
);
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"description - The value of a field does not conform to the expected format., value - 12345, field - security_code;",
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.clone().unwrap_err().message,
"Request is not well-formed, syntactically incorrect, or violates schema.",
);
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"description - The value of a field does not conform to the expected format., value - 2025-20, field - expiry;",
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.clone().unwrap_err().message,
"The requested action could not be performed, semantically incorrect, or failed business validation.",
);
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"description - The card is expired., field - expiry;",
);
}
// 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
.authorize_payment(get_payment_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
let txn_id = utils::get_connector_transaction_id(capture_response.clone().response).unwrap();
let connector_meta = utils::get_connector_metadata(capture_response.response);
let void_response = CONNECTOR
.void_payment(
txn_id,
Some(types::PaymentsCancelData {
cancellation_reason: Some("requested_by_customer".to_string()),
connector_meta,
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(
void_response.response.clone().unwrap_err().message,
"The requested action could not be performed, semantically incorrect, or failed business validation."
);
assert_eq!(
void_response.response.unwrap_err().reason.unwrap(),
"description - Authorization has been previously captured and hence cannot be voided. ; "
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let connector_meta = Some(serde_json::json!({
"authorize_id": "56YH8TZ",
"order_id":"02569315XM5003146",
"psync_flow":"AUTHORIZE",
}));
let capture_response = CONNECTOR
.capture_payment(
"".to_string(),
Some(types::PaymentsCaptureData {
connector_meta,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
capture_response.response.clone().unwrap_err().message,
"The specified resource does not exist.",
);
assert_eq!(
capture_response.response.unwrap_err().reason.unwrap(),
"description - Specified resource ID does not exist. Please check the resource ID and try again. ; ",
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
#[ignore = "Since Payment status is in pending status, cannot refund"]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let authorize_response = CONNECTOR
.make_payment(get_payment_data(), get_default_payment_info())
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
let response = CONNECTOR
.refund_payment(
txn_id,
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(&response.response.clone().unwrap_err().message, "The requested action could not be performed, semantically incorrect, or failed business validation.");
assert_eq!(
response.response.unwrap_err().reason.unwrap(),
"description - The refund amount must be less than or equal to the capture amount that has not yet been refunded. ; ",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/trustpayments.rs | crates/router/tests/connectors/trustpayments.rs | use std::str::FromStr;
use masking::Secret;
use router::types::{self, api, domain, 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::Trustpayments,
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> {
Some(utils::PaymentInfo {
address: Some(types::PaymentAddress::new(
None,
None,
Some(hyperswitch_domain_models::address::Address {
address: Some(hyperswitch_domain_models::address::AddressDetails {
country: Some(common_enums::CountryAlpha2::US),
city: Some("New York".to_string()),
zip: Some(Secret::new("10001".to_string())),
line1: Some(Secret::new("123 Main St".to_string())),
line2: None,
line3: None,
state: Some(Secret::new("NY".to_string())),
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Doe".to_string())),
origin_zip: None,
}),
phone: Some(hyperswitch_domain_models::address::PhoneDetails {
number: Some(Secret::new("1234567890".to_string())),
country_code: Some("+1".to_string()),
}),
email: None,
}),
None,
)),
..Default::default()
})
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("12".to_string()),
card_exp_year: Secret::new("2025".to_string()),
card_cvc: Secret::new("123".to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
nick_name: None,
card_holder_name: Some(Secret::new("John Doe".to_string())),
co_badged_card_data: None,
}),
confirm: true,
amount: 100,
minor_amount: common_utils::types::MinorUnit::new(100),
currency: enums::Currency::USD,
capture_method: Some(enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/hipay.rs | crates/router/tests/connectors/hipay.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 HipayTest;
impl ConnectorActions for HipayTest {}
impl utils::Connector for HipayTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Hipay;
utils::construct_connector_data_old(
Box::new(Hipay::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.hipay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"hipay".to_string()
}
}
static CONNECTOR: HipayTest = HipayTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/juspaythreedsserver.rs | crates/router/tests/connectors/juspaythreedsserver.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 JuspaythreedsserverTest;
impl JuspaythreedsserverTest {
#[allow(dead_code)]
fn new() -> Self {
Self
}
}
impl ConnectorActions for JuspaythreedsserverTest {}
impl utils::Connector for JuspaythreedsserverTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Juspaythreedsserver;
utils::construct_connector_data_old(
Box::new(Juspaythreedsserver::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.juspaythreedsserver
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"juspaythreedsserver".to_string()
}
}
static CONNECTOR: JuspaythreedsserverTest = JuspaythreedsserverTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/flexiti.rs | crates/router/tests/connectors/flexiti.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 FlexitiTest;
impl ConnectorActions for FlexitiTest {}
impl utils::Connector for FlexitiTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Flexiti;
utils::construct_connector_data_old(
Box::new(Flexiti::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.flexiti
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"flexiti".to_string()
}
}
static CONNECTOR: FlexitiTest = FlexitiTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/silverflow.rs | crates/router/tests/connectors/silverflow.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 SilverflowTest;
impl ConnectorActions for SilverflowTest {}
impl utils::Connector for SilverflowTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Silverflow;
utils::construct_connector_data_old(
Box::new(Silverflow::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.silverflow
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"silverflow".to_string()
}
}
static CONNECTOR: SilverflowTest = SilverflowTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/worldpayxml.rs | 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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/itaubank.rs | crates/router/tests/connectors/itaubank.rs | use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct ItaubankTest;
impl ConnectorActions for ItaubankTest {}
impl utils::Connector for ItaubankTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Itaubank;
utils::construct_connector_data_old(
Box::new(Itaubank::new()),
types::Connector::Itaubank,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.itaubank
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"itaubank".to_string()
}
}
static CONNECTOR: ItaubankTest = ItaubankTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/katapult.rs | crates/router/tests/connectors/katapult.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 KatapultTest;
impl ConnectorActions for KatapultTest {}
impl utils::Connector for KatapultTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Katapult;
utils::construct_connector_data_old(
Box::new(Katapult::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.katapult
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"katapult".to_string()
}
}
static CONNECTOR: KatapultTest = KatapultTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/helcim.rs | crates/router/tests/connectors/helcim.rs | use masking::Secret;
use router::types::{self, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct HelcimTest;
impl ConnectorActions for HelcimTest {}
impl utils::Connector for HelcimTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Helcim;
utils::construct_connector_data_old(
Box::new(Helcim::new()),
types::Connector::Helcim,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.helcim
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"helcim".to_string()
}
}
static CONNECTOR: HelcimTest = HelcimTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/nexinets.rs | crates/router/tests/connectors/nexinets.rs | use std::str::FromStr;
use cards::CardNumber;
use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums, PaymentsAuthorizeData};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct NexinetsTest;
impl ConnectorActions for NexinetsTest {}
static CONNECTOR: NexinetsTest = NexinetsTest {};
impl utils::Connector for NexinetsTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Nexinets;
utils::construct_connector_data_old(
Box::new(&Nexinets),
types::Connector::Nexinets,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.nexinets
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"nexinets".to_string()
}
}
fn payment_method_details() -> Option<PaymentsAuthorizeData> {
Some(PaymentsAuthorizeData {
currency: diesel_models::enums::Currency::EUR,
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("374111111111111").unwrap(),
..utils::CCardType::default().0
}),
router_return_url: Some("https://google.com".to_string()),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), None)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id = "".to_string();
let connector_meta = utils::get_connector_metadata(response.response);
let capture_data = types::PaymentsCaptureData {
connector_meta,
currency: diesel_models::enums::Currency::EUR,
..utils::PaymentCaptureType::default().0
};
let capture_response = CONNECTOR
.capture_payment(connector_payment_id, Some(capture_data), None)
.await
.unwrap();
assert_eq!(capture_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_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id = "".to_string();
let connector_meta = utils::get_connector_metadata(response.response);
let capture_data = types::PaymentsCaptureData {
connector_meta,
amount_to_capture: 50,
currency: diesel_models::enums::Currency::EUR,
..utils::PaymentCaptureType::default().0
};
let capture_response = CONNECTOR
.capture_payment(connector_payment_id, Some(capture_data), None)
.await
.unwrap();
assert_eq!(capture_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(), None)
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let connector_meta = utils::get_connector_metadata(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),
encoded_data: None,
capture_method: None,
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta,
mandate_id: None,
payment_method_type: None,
currency: enums::Currency::EUR,
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id = "".to_string();
let connector_meta = utils::get_connector_metadata(response.response);
let response = CONNECTOR
.void_payment(
connector_payment_id,
Some(types::PaymentsCancelData {
connector_meta,
amount: Some(100),
currency: Some(diesel_models::enums::Currency::EUR),
..utils::PaymentCancelType::default().0
}),
None,
)
.await
.unwrap();
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 authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), None)
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id,
Some(types::PaymentsCaptureData {
currency: diesel_models::enums::Currency::EUR,
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
let capture_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let refund_connector_metadata = utils::get_connector_metadata(capture_response.response);
let response = CONNECTOR
.refund_payment(
capture_txn_id.clone(),
Some(types::RefundsData {
connector_transaction_id: capture_txn_id,
currency: diesel_models::enums::Currency::EUR,
connector_metadata: refund_connector_metadata,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), None)
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id.clone(),
Some(types::PaymentsCaptureData {
currency: diesel_models::enums::Currency::EUR,
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
let capture_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let refund_connector_metadata = utils::get_connector_metadata(capture_response.response);
let response = CONNECTOR
.refund_payment(
capture_txn_id.clone(),
Some(types::RefundsData {
refund_amount: 10,
connector_transaction_id: capture_txn_id,
currency: diesel_models::enums::Currency::EUR,
connector_metadata: refund_connector_metadata,
..utils::PaymentRefundType::default().0
}),
None,
)
.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 authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), None)
.await
.expect("Authorize payment response");
let txn_id = "".to_string();
let capture_connector_meta = utils::get_connector_metadata(authorize_response.response);
let capture_response = CONNECTOR
.capture_payment(
txn_id.clone(),
Some(types::PaymentsCaptureData {
currency: diesel_models::enums::Currency::EUR,
connector_meta: capture_connector_meta,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
let capture_txn_id =
utils::get_connector_transaction_id(capture_response.response.clone()).unwrap();
let refund_connector_metadata = utils::get_connector_metadata(capture_response.response);
let refund_response = CONNECTOR
.refund_payment(
capture_txn_id.clone(),
Some(types::RefundsData {
refund_amount: 100,
connector_transaction_id: capture_txn_id.clone(),
currency: diesel_models::enums::Currency::EUR,
connector_metadata: refund_connector_metadata.clone(),
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
let transaction_id = Some(
refund_response
.response
.clone()
.unwrap()
.connector_refund_id,
);
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response
.response
.clone()
.unwrap()
.connector_refund_id,
Some(types::RefundsData {
connector_refund_id: transaction_id,
connector_transaction_id: capture_txn_id,
connector_metadata: refund_connector_metadata,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let cap_response = CONNECTOR
.make_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(cap_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(cap_response.response.clone()).unwrap();
let connector_meta = utils::get_connector_metadata(cap_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(txn_id),
capture_method: Some(enums::CaptureMethod::Automatic),
connector_meta,
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let captured_response = CONNECTOR
.make_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(captured_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(captured_response.response.clone());
let connector_metadata = utils::get_connector_metadata(captured_response.response);
let response = CONNECTOR
.refund_payment(
txn_id.clone().unwrap(),
Some(types::RefundsData {
refund_amount: 100,
currency: diesel_models::enums::Currency::EUR,
connector_transaction_id: txn_id.unwrap(),
connector_metadata,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let captured_response = CONNECTOR
.make_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(captured_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(captured_response.response.clone());
let connector_meta = utils::get_connector_metadata(captured_response.response);
let response = CONNECTOR
.refund_payment(
txn_id.clone().unwrap(),
Some(types::RefundsData {
refund_amount: 50,
currency: diesel_models::enums::Currency::EUR,
connector_transaction_id: txn_id.unwrap(),
connector_metadata: connector_meta,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
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() {
let captured_response = CONNECTOR
.make_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(captured_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(captured_response.response.clone());
let connector_meta = utils::get_connector_metadata(captured_response.response);
for _x in 0..2 {
let refund_response = CONNECTOR
.refund_payment(
txn_id.clone().unwrap(),
Some(types::RefundsData {
connector_metadata: connector_meta.clone(),
connector_transaction_id: txn_id.clone().unwrap(),
refund_amount: 50,
currency: diesel_models::enums::Currency::EUR,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let captured_response = CONNECTOR
.make_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(captured_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(captured_response.response.clone());
let connector_metadata = utils::get_connector_metadata(captured_response.response).clone();
let refund_response = CONNECTOR
.refund_payment(
txn_id.clone().unwrap(),
Some(types::RefundsData {
connector_transaction_id: txn_id.clone().unwrap(),
refund_amount: 100,
currency: diesel_models::enums::Currency::EUR,
connector_metadata: connector_metadata.clone(),
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
let transaction_id = Some(
refund_response
.response
.clone()
.unwrap()
.connector_refund_id,
);
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response
.response
.clone()
.unwrap()
.connector_refund_id,
Some(types::RefundsData {
connector_refund_id: transaction_id,
connector_transaction_id: txn_id.unwrap(),
connector_metadata,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"payment.verification : Bad value for 'payment.verification'. Expected: string of length in range 3 <=> 4 representing a valid creditcard verification number.".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(PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"payment.expiryMonth : Bad value for 'payment.expiryMonth'. Expected: string of length 2 in range '01' <=> '12' representing the month in a valid creditcard expiry date >= current date.".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(PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"payment.expiryYear : Bad value for 'payment.expiryYear'. Expected: string of length 2 in range '01' <=> '99' representing the year in a valid creditcard expiry date >= current date.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let captured_response = CONNECTOR
.make_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(captured_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(captured_response.response.clone()).unwrap();
let connector_meta = utils::get_connector_metadata(captured_response.response);
let void_response = CONNECTOR
.void_payment(
txn_id,
Some(types::PaymentsCancelData {
cancellation_reason: Some("requested_by_customer".to_string()),
amount: Some(100),
currency: Some(diesel_models::enums::Currency::EUR),
connector_meta,
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"transactionId : Operation not allowed!"
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let connector_payment_id = "".to_string();
let capture_response = CONNECTOR
.capture_payment(
connector_payment_id,
Some(types::PaymentsCaptureData {
connector_meta: Some(
serde_json::json!({"transaction_id" : "transaction_usmh41hymb",
"order_id" : "tjil1ymxsz",
"psync_flow" : "PREAUTH"
}),
),
amount_to_capture: 50,
currency: diesel_models::enums::Currency::EUR,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("transactionId : Transaction does not belong to order.")
);
}
// 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 captured_response = CONNECTOR
.make_payment(payment_method_details(), None)
.await
.unwrap();
assert_eq!(captured_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(captured_response.response.clone());
let connector_meta = utils::get_connector_metadata(captured_response.response);
let response = CONNECTOR
.refund_payment(
txn_id.clone().unwrap(),
Some(types::RefundsData {
refund_amount: 150,
currency: diesel_models::enums::Currency::EUR,
connector_transaction_id: txn_id.unwrap(),
connector_metadata: connector_meta,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"initialAmount : Bad value for 'initialAmount'. Expected: Positive integer between 1 and maximum available amount (debit/capture.initialAmount - debit/capture.refundedAmount.",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/datatrans.rs | crates/router/tests/connectors/datatrans.rs | use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct DatatransTest;
impl ConnectorActions for DatatransTest {}
impl utils::Connector for DatatransTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Adyen;
utils::construct_connector_data_old(
Box::new(Adyen::new()),
types::Connector::Adyen,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.datatrans
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"datatrans".to_string()
}
}
static CONNECTOR: DatatransTest = DatatransTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/aci.rs | crates/router/tests/connectors/aci.rs | use std::str::FromStr;
use hyperswitch_domain_models::{
address::{Address, AddressDetails, PhoneDetails},
payment_method_data::{Card, PaymentMethodData},
router_request_types::AuthenticationData,
};
use masking::Secret;
use router::types::{self, storage::enums, PaymentAddress};
use crate::{
connector_auth,
utils::{self, ConnectorActions, PaymentInfo},
};
#[derive(Clone, Copy)]
struct AciTest;
impl ConnectorActions for AciTest {}
impl utils::Connector for AciTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Aci;
utils::construct_connector_data_old(
Box::new(Aci::new()),
types::Connector::Aci,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.aci
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"aci".to_string()
}
}
static CONNECTOR: AciTest = AciTest {};
fn get_default_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Doe".to_string())),
line1: Some(Secret::new("123 Main St".to_string())),
city: Some("New York".to_string()),
state: Some(Secret::new("NY".to_string())),
zip: Some(Secret::new("10001".to_string())),
country: Some(enums::CountryAlpha2::US),
..Default::default()
}),
phone: Some(PhoneDetails {
number: Some(Secret::new("+1234567890".to_string())),
country_code: Some("+1".to_string()),
}),
email: None,
}),
None,
None,
)),
..Default::default()
})
}
fn get_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_month: Secret::new("10".to_string()),
card_exp_year: Secret::new("2025".to_string()),
card_cvc: Secret::new("999".to_string()),
card_holder_name: Some(Secret::new("John Doe".to_string())),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
fn get_threeds_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: PaymentMethodData::Card(Card {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_month: Secret::new("10".to_string()),
card_exp_year: Secret::new("2025".to_string()),
card_cvc: Secret::new("999".to_string()),
card_holder_name: Some(Secret::new("John Doe".to_string())),
..utils::CCardType::default().0
}),
enrolled_for_3ds: true,
authentication_data: Some(AuthenticationData {
eci: Some("05".to_string()),
cavv: Secret::new("jJ81HADVRtXfCBATEp01CJUAAAA".to_string()),
threeds_server_transaction_id: Some("9458d8d4-f19f-4c28-b5c7-421b1dd2e1aa".to_string()),
message_version: Some(common_utils::types::SemanticVersion::new(2, 1, 0)),
ds_trans_id: Some("97267598FAE648F28083B2D2AF7B1234".to_string()),
created_at: common_utils::date_time::now(),
challenge_code: Some("01".to_string()),
challenge_cancel: None,
challenge_code_reason: Some("01".to_string()),
message_extension: None,
acs_trans_id: None,
authentication_type: None,
cb_network_params: None,
exemption_indicator: None,
transaction_status: None,
}),
..utils::PaymentAuthorizeType::default().0
})
}
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
get_payment_authorize_data(),
None,
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
get_payment_authorize_data(),
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);
}
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(get_payment_authorize_data(), 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,);
}
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
get_payment_authorize_data(),
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);
}
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
get_payment_authorize_data(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
get_payment_authorize_data(),
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,
);
}
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
get_payment_authorize_data(),
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,
);
}
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(get_payment_authorize_data(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(get_payment_authorize_data(), 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,);
}
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(
get_payment_authorize_data(),
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
get_payment_authorize_data(),
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,
);
}
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
get_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(
get_payment_authorize_data(),
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,
);
}
#[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!(
response.response.is_err(),
"Payment should fail with incorrect CVC"
);
}
#[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!(
response.response.is_err(),
"Payment should fail with invalid expiry month"
);
}
#[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!(
response.response.is_err(),
"Payment should fail with incorrect expiry year"
);
}
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(get_payment_authorize_data(), 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!(
void_response.response.is_err(),
"Void should fail for already captured payment"
);
}
#[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!(
capture_response.response.is_err(),
"Capture should fail for invalid payment ID"
);
}
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
get_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert!(
response.response.is_err(),
"Refund should fail when amount exceeds payment amount"
);
}
#[actix_web::test]
#[ignore]
async fn should_make_threeds_payment() {
let authorize_response = CONNECTOR
.make_payment(
get_threeds_payment_authorize_data(),
get_default_payment_info(),
)
.await
.unwrap();
assert!(
authorize_response.status == enums::AttemptStatus::AuthenticationPending
|| authorize_response.status == enums::AttemptStatus::Charged,
"3DS payment should result in AuthenticationPending or Charged status, got: {:?}",
authorize_response.status
);
if let Ok(types::PaymentsResponseData::TransactionResponse {
redirection_data, ..
}) = &authorize_response.response
{
if authorize_response.status == enums::AttemptStatus::AuthenticationPending {
assert!(
redirection_data.is_some(),
"3DS flow should include redirection data for authentication"
);
}
}
}
#[actix_web::test]
#[ignore]
async fn should_authorize_threeds_payment() {
let response = CONNECTOR
.authorize_payment(
get_threeds_payment_authorize_data(),
get_default_payment_info(),
)
.await
.expect("Authorize 3DS payment response");
assert!(
response.status == enums::AttemptStatus::AuthenticationPending
|| response.status == enums::AttemptStatus::Authorized,
"3DS authorization should result in AuthenticationPending or Authorized status, got: {:?}",
response.status
);
}
#[actix_web::test]
#[ignore]
async fn should_sync_threeds_payment() {
let authorize_response = CONNECTOR
.authorize_payment(
get_threeds_payment_authorize_data(),
get_default_payment_info(),
)
.await
.expect("Authorize 3DS payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::AuthenticationPending,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync 3DS response");
assert!(
response.status == enums::AttemptStatus::AuthenticationPending
|| response.status == enums::AttemptStatus::Authorized,
"3DS sync should maintain AuthenticationPending or Authorized status"
);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/nomupay.rs | crates/router/tests/connectors/nomupay.rs | use api_models::payments::{Address, AddressDetails};
use masking::Secret;
use router::types::{self, api, storage::enums, PaymentAddress};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions, PaymentInfo};
#[derive(Clone, Copy)]
struct NomupayTest;
impl ConnectorActions for NomupayTest {}
impl utils::Connector for NomupayTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Nomupay;
utils::construct_connector_data_old(
Box::new(Nomupay::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.nomupay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"nomupay".to_string()
}
}
impl NomupayTest {
fn get_payout_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
currency: Some(enums::Currency::GBP),
address: Some(PaymentAddress::new(
None,
Some(
Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::GB),
city: Some("London".to_string()),
zip: Some(Secret::new("10025".to_string())),
line1: Some(Secret::new("50 Branson Ave".to_string())),
..Default::default()
}),
phone: None,
email: None,
}
.into(),
),
None,
None,
)),
payout_method_data: Some(api::PayoutMethodData::Bank(api::payouts::BankPayout::Sepa(
api::SepaBankTransfer {
bank_name: Some("Deutsche Bank".to_string()),
bank_country_code: Some(enums::CountryAlpha2::DE),
bank_city: Some("Munich".to_string()),
iban: Secret::new("DE57331060435647542639".to_string()),
bic: Some(Secret::new("DEUTDE5M551".to_string())),
},
))),
..Default::default()
})
}
}
static CONNECTOR: NomupayTest = NomupayTest {};
/******************** Payouts test cases ********************/
// Creates a recipient at connector's end
#[actix_web::test]
async fn should_create_payout_recipient() {
let payout_type = enums::PayoutType::Bank;
let payment_info = NomupayTest::get_payout_info();
let response = CONNECTOR
.create_payout_recipient(payout_type, payment_info)
.await
.expect("Payout recipient creation response");
assert_eq!(
response.status.unwrap(),
enums::PayoutStatus::RequiresCreation
);
}
// Create SEPA payout
#[actix_web::test]
async fn should_create_bacs_payout() {
let payout_type = enums::PayoutType::Bank;
let payout_info = NomupayTest::get_payout_info();
// Create recipient
let recipient_res = CONNECTOR
.create_payout_recipient(payout_type.to_owned(), payout_info.to_owned())
.await
.expect("Payout recipient response");
assert_eq!(
recipient_res.status.unwrap(),
enums::PayoutStatus::RequiresCreation
);
// Create payout
let create_res: types::PayoutsResponseData = CONNECTOR
.create_payout(recipient_res.connector_payout_id, payout_type, payout_info)
.await
.expect("Payout bank creation response");
assert_eq!(
create_res.status.unwrap(),
enums::PayoutStatus::RequiresFulfillment
);
}
// Create and fulfill SEPA payout
#[actix_web::test]
async fn should_create_and_fulfill_bacs_payout() {
let payout_type = enums::PayoutType::Bank;
let payout_info = NomupayTest::get_payout_info();
// Create recipient
let recipient_res = CONNECTOR
.create_payout_recipient(payout_type.to_owned(), payout_info.to_owned())
.await
.expect("Payout recipient response");
assert_eq!(
recipient_res.status.unwrap(),
enums::PayoutStatus::RequiresCreation
);
let response = CONNECTOR
.create_and_fulfill_payout(recipient_res.connector_payout_id, payout_type, payout_info)
.await
.expect("Payout bank creation and fulfill response");
assert_eq!(response.status.unwrap(), enums::PayoutStatus::Success);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/checkbook.rs | crates/router/tests/connectors/checkbook.rs | use std::str::FromStr;
use hyperswitch_domain_models::address::{Address, AddressDetails};
use masking::Secret;
use router::types::{self, api, storage::enums, Email};
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct CheckbookTest;
impl ConnectorActions for CheckbookTest {}
impl utils::Connector for CheckbookTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Checkbook;
utils::construct_connector_data_old(
Box::new(Checkbook::new()),
types::Connector::Checkbook,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
types::ConnectorAuthType::BodyKey {
key1: Secret::new("dummy_publishable_key".to_string()),
api_key: Secret::new("dummy_secret_key".to_string()),
}
}
fn get_name(&self) -> String {
"checkbook".to_string()
}
}
static CONNECTOR: CheckbookTest = CheckbookTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
address: Some(types::PaymentAddress::new(
None,
None,
Some(Address {
address: Some(AddressDetails {
first_name: Some(Secret::new("John".to_string())),
last_name: Some(Secret::new("Doe".to_string())),
..Default::default()
}),
phone: None,
email: Some(Email::from_str("abc@gmail.com").unwrap()),
}),
None,
)),
..Default::default()
})
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Creates a payment.
#[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::AuthenticationPending);
}
// Synchronizes a payment.
#[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::AuthenticationPending,
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::AuthenticationPending);
}
// Voids a payment.
#[actix_web::test]
async fn should_void_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
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/affirm.rs | crates/router/tests/connectors/affirm.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 AffirmTest;
impl ConnectorActions for AffirmTest {}
impl utils::Connector for AffirmTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Affirm;
utils::construct_connector_data_old(
Box::new(Affirm::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.affirm
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"affirm".to_string()
}
}
static CONNECTOR: AffirmTest = AffirmTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/gigadat.rs | crates/router/tests/connectors/gigadat.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 GigadatTest;
impl ConnectorActions for GigadatTest {}
impl utils::Connector for GigadatTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Gigadat;
utils::construct_connector_data_old(
Box::new(Gigadat::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.gigadat
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"gigadat".to_string()
}
}
static CONNECTOR: GigadatTest = GigadatTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/dlocal.rs | crates/router/tests/connectors/dlocal.rs | use std::str::FromStr;
use hyperswitch_domain_models::address::{Address, AddressDetails};
use masking::Secret;
use router::types::{self, api, domain, storage::enums, PaymentAddress};
use crate::{
connector_auth,
utils::{self, ConnectorActions, PaymentInfo},
};
#[derive(Clone, Copy)]
struct DlocalTest;
impl ConnectorActions for DlocalTest {}
impl utils::Connector for DlocalTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Dlocal;
utils::construct_connector_data_old(
Box::new(Dlocal::new()),
types::Connector::Dlocal,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.dlocal
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"dlocal".to_string()
}
}
static CONNECTOR: DlocalTest = DlocalTest {};
// 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(None, Some(get_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(None, None, Some(get_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(
None,
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
Some(get_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(None, Some(get_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()
}),
Some(get_payment_info()),
)
.await
.expect("PSync response");
println!("{}", response.status);
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(
None,
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
Some(get_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(None, None, None, Some(get_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(
None,
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
Some(get_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(None, None, None, Some(get_payment_info()))
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
Some(get_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(None, Some(get_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(None, Some(get_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(),
),
..Default::default()
}),
Some(get_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(None, None, Some(get_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(
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
Some(get_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(
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
Some(get_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(None, None, Some(get_payment_info()))
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
Some(get_payment_info()),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1891011").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
Some(get_payment_info()),
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(x.message, "Invalid parameter");
assert_eq!(x.reason, Some("card.number".to_string()));
}
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("1ad2345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
Some(get_payment_info()),
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(x.message, "Invalid parameter");
assert_eq!(x.reason, Some("card.cvv".to_string()));
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("201".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
Some(get_payment_info()),
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(x.message, "Invalid parameter");
assert_eq!(x.reason, Some("card.expiration_month".to_string()));
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("20001".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
Some(get_payment_info()),
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(x.message, "Invalid parameter");
assert_eq!(x.reason, Some("card.expiration_year".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(None, Some(get_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, None)
.await
.unwrap();
let x = void_response.response.unwrap_err();
assert_eq!(x.code, "5021");
assert_eq!(x.message, "Acquirer could not process the request");
}
// 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("123456sdf789".to_string(), None, Some(get_payment_info()))
.await
.unwrap();
let x = capture_response.response.unwrap_err();
assert_eq!(x.code, "3003");
}
// 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(
None,
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
Some(get_payment_info()),
)
.await
.unwrap();
let x = response.response.unwrap_err();
println!("response from refund amount higher payment");
println!("{}", x.code);
assert_eq!(x.code, "5007");
assert_eq!(x.message, "Amount exceeded");
}
pub fn get_payment_info() -> PaymentInfo {
PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
phone: None,
address: Some(AddressDetails {
city: None,
country: Some(api_models::enums::CountryAlpha2::PA),
line1: None,
line2: None,
line3: None,
zip: None,
state: None,
first_name: None,
last_name: None,
origin_zip: None,
}),
email: None,
}),
None,
None,
)),
auth_type: None,
access_token: None,
connector_meta_data: None,
..Default::default()
}
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/paysafe.rs | crates/router/tests/connectors/paysafe.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 PaysafeTest;
impl ConnectorActions for PaysafeTest {}
impl utils::Connector for PaysafeTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Paysafe;
utils::construct_connector_data_old(
Box::new(Paysafe::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.paysafe
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"paysafe".to_string()
}
}
static CONNECTOR: PaysafeTest = PaysafeTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/tokenex.rs | crates/router/tests/connectors/tokenex.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 TokenexTest;
impl ConnectorActions for TokenexTest {}
impl utils::Connector for TokenexTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Tokenex;
utils::construct_connector_data_old(
Box::new(&Tokenex),
types::Connector::Tokenex,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.tokenex
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"tokenex".to_string()
}
}
static CONNECTOR: TokenexTest = TokenexTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/shift4.rs | crates/router/tests/connectors/shift4.rs | use std::str::FromStr;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct Shift4Test;
impl ConnectorActions for Shift4Test {}
impl utils::Connector for Shift4Test {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Shift4;
utils::construct_connector_data_old(
Box::new(Shift4::new()),
types::Connector::Shift4,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.shift4
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"shift4".to_string()
}
}
static CONNECTOR: Shift4Test = Shift4Test {};
// 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(None, None).await.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let connector = CONNECTOR;
let response = connector
.authorize_and_capture_payment(None, None, None)
.await;
assert_eq!(response.unwrap().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 connector = CONNECTOR;
let response = connector
.authorize_and_capture_payment(
None,
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let connector = CONNECTOR;
let authorize_response = connector.authorize_payment(None, None).await.unwrap();
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()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
// Authorize
let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let connector = CONNECTOR;
let response = connector
.authorize_and_void_payment(
None,
Some(types::PaymentsCancelData {
connector_transaction_id: "".to_string(),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
None,
)
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Pending); //shift4 doesn't allow voiding a payment
}
// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4024007134364842").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The card's security code failed verification.".to_string(),
);
}
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_succeed_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("asdasd".to_string()), //shift4 accept invalid CVV as it doesn't accept CVV
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The card has expired.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
// Authorize
let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
// Void
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, None)
.await
.unwrap();
assert_eq!(void_response.status, enums::AttemptStatus::Pending); //shift4 doesn't allow voiding a payment
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
// Capture
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("Charge '123456789' does not exist")
);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let connector = CONNECTOR;
let response = connector
.make_payment_and_refund(None, None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let connector = CONNECTOR;
let response = connector
.auth_capture_and_refund(None, None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let connector = CONNECTOR;
let refund_response = connector
.make_payment_and_refund(
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
refund_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 connector = CONNECTOR;
let response = connector
.auth_capture_and_refund(
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
let connector = CONNECTOR;
connector
.make_payment_and_multiple_refund(
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await;
}
// 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 connector = CONNECTOR;
let response = connector
.make_payment_and_refund(
None,
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid Refund data",
);
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let connector = CONNECTOR;
let refund_response = connector
.make_payment_and_refund(None, None, None)
.await
.unwrap();
let response = connector
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.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 connector = CONNECTOR;
let refund_response = connector
.auth_capture_and_refund(None, None, None)
.await
.unwrap();
let response = connector
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/nordea.rs | crates/router/tests/connectors/nordea.rs | use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct NordeaTest;
impl ConnectorActions for NordeaTest {}
impl utils::Connector for NordeaTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Nordea;
utils::construct_connector_data_old(
Box::new(Nordea::new()),
types::Connector::DummyConnector1,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.nordea
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"nordea".to_string()
}
}
static CONNECTOR: NordeaTest = NordeaTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/custombilling.rs | crates/router/tests/connectors/custombilling.rs | use masking::Secret;
use router::{
types::{self, api, storage::enums,
}};
use crate::utils::{self, ConnectorActions};
use test_utils::connector_auth;
#[derive(Clone, Copy)]
struct CustombillingTest;
impl ConnectorActions for CustombillingTest {}
impl utils::Connector for CustombillingTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Custombilling;
api::ConnectorData {
connector: Box::new(Custombilling::new()),
connector_name: types::Connector::Custombilling,
get_token: types::api::GetToken::Connector,
merchant_connector_id: None,
}
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.custombilling
.expect("Missing connector authentication configuration").into(),
)
}
fn get_name(&self) -> String {
"custombilling".to_string()
}
}
static CONNECTOR: CustombillingTest = CustombillingTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(payment_method_details(), None, None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: types::api::PaymentMethodData::Card(api::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: api::PaymentMethodData::Card(api::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: api::PaymentMethodData::Card(api::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR.make_payment(payment_method_details(), get_default_payment_info()).await.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/fiserv.rs | crates/router/tests/connectors/fiserv.rs | use std::str::FromStr;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use serde_json::json;
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct FiservTest;
impl ConnectorActions for FiservTest {}
impl utils::Connector for FiservTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Fiserv;
utils::construct_connector_data_old(
Box::new(Fiserv::new()),
types::Connector::Fiserv,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.fiserv
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"fiserv".to_string()
}
fn get_connector_meta(&self) -> Option<serde_json::Value> {
Some(json!({"terminalId": "10000001"}))
}
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4005550000000019").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
card_cvc: Secret::new("123".to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
co_badged_card_data: None,
}),
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
..utils::PaymentAuthorizeType::default().0
})
}
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
connector_meta_data: Some(json!({"terminalId": "10000001"})),
..utils::PaymentInfo::with_default_billing_name()
})
}
static CONNECTOR: FiservTest = FiservTest {};
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
#[serial_test::serial]
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]
#[serial_test::serial]
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]
#[serial_test::serial]
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]
#[serial_test::serial]
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);
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
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]
#[serial_test::serial]
#[ignore]
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("TIMEOUT".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]
#[serial_test::serial]
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]
#[serial_test::serial]
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]
#[serial_test::serial]
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();
tokio::time::sleep(std::time::Duration::from_secs(7)).await;
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]
#[serial_test::serial]
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]
#[serial_test::serial]
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");
tokio::time::sleep(std::time::Duration::from_secs(7)).await;
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..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]
#[serial_test::serial]
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]
#[serial_test::serial]
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]
#[serial_test::serial]
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]
#[serial_test::serial]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_secs(7)).await;
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 card number.
#[actix_web::test]
#[serial_test::serial]
async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Unable to assign card to brand: Invalid.".to_string(),
);
}
// Creates a payment with incorrect CVC.
#[actix_web::test]
#[serial_test::serial]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid or Missing Field Data".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
#[serial_test::serial]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid or Missing Field Data".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
#[serial_test::serial]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Unable to assign card to brand: Invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
#[serial_test::serial]
#[ignore]
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(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("TIMEOUT".to_string()),
..Default::default()
}),
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]
#[serial_test::serial]
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("Referenced transaction is invalid or not found")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
#[serial_test::serial]
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,
"Unable to Refund: Amount is greater than original transaction",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/checkout.rs | crates/router/tests/connectors/checkout.rs | use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct CheckoutTest;
impl ConnectorActions for CheckoutTest {}
impl utils::Connector for CheckoutTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Checkout;
utils::construct_connector_data_old(
Box::new(Checkout::new()),
types::Connector::Checkout,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.checkout
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"checkout".to_string()
}
}
static CONNECTOR: CheckoutTest = CheckoutTest {};
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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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]
#[ignore = "Connector Error, needs to be looked into and fixed"]
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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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).
#[serial_test::serial]
#[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]
#[ignore = "Connector Error, needs to be looked into and fixed"]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
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.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"cvv_invalid".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"card_expiry_month_invalid".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[serial_test::serial]
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"card_expired".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[serial_test::serial]
#[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().status_code, 403);
}
// Captures a payment using invalid connector payment id.
#[serial_test::serial]
#[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().status_code, 404);
}
// Refunds a payment with refund amount higher than payment amount.
#[serial_test::serial]
#[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_exceeds_balance",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/novalnet.rs | crates/router/tests/connectors/novalnet.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 NovalnetTest;
impl ConnectorActions for NovalnetTest {}
impl utils::Connector for NovalnetTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Novalnet;
utils::construct_connector_data_old(
Box::new(Novalnet::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.novalnet
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"novalnet".to_string()
}
}
static CONNECTOR: NovalnetTest = NovalnetTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/payone.rs | crates/router/tests/connectors/payone.rs | use masking::Secret;
use router::types::{self, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct PayoneTest;
impl ConnectorActions for PayoneTest {}
impl utils::Connector for PayoneTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Payone;
utils::construct_connector_data_old(
Box::new(Payone::new()),
types::Connector::Payone,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.payone
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"payone".to_string()
}
}
static CONNECTOR: PayoneTest = PayoneTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/blackhawknetwork.rs | crates/router/tests/connectors/blackhawknetwork.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 BlackhawknetworkTest;
impl ConnectorActions for BlackhawknetworkTest {}
impl utils::Connector for BlackhawknetworkTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Blackhawknetwork;
utils::construct_connector_data_old(
Box::new(Blackhawknetwork::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.blackhawknetwork
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"blackhawknetwork".to_string()
}
}
static CONNECTOR: BlackhawknetworkTest = BlackhawknetworkTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/tsys.rs | crates/router/tests/connectors/tsys.rs | use std::{str::FromStr, time::Duration};
use cards::CardNumber;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct TsysTest;
impl ConnectorActions for TsysTest {}
impl utils::Connector for TsysTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Tsys;
utils::construct_connector_data_old(
Box::new(Tsys::new()),
types::Connector::Tsys,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.tsys
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"tsys".to_string()
}
}
static CONNECTOR: TsysTest = TsysTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details(amount: i64) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount,
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: CardNumber::from_str("4111111111111111").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(101), 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(100),
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(130),
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(140), 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(150),
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(160),
Some(types::PaymentsCaptureData {
amount_to_capture: 160,
..utils::PaymentCaptureType::default().0
}),
Some(types::RefundsData {
refund_amount: 160,
..utils::PaymentRefundType::default().0
}),
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(170),
Some(types::PaymentsCaptureData {
amount_to_capture: 170,
..utils::PaymentCaptureType::default().0
}),
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(180),
Some(types::PaymentsCaptureData {
amount_to_capture: 180,
..utils::PaymentCaptureType::default().0
}),
Some(types::RefundsData {
refund_amount: 180,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(10)).await;
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(200), 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(210), 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(220),
Some(types::RefundsData {
refund_amount: 220,
..utils::PaymentRefundType::default().0
}),
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(230),
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(250),
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(100),
None,
get_default_payment_info(),
)
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(10)).await;
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The value of element cvv2 is not valid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The value of element 'expirationDate' is not valid., ".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("abcd".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"The value of element 'expirationDate' is not valid., ".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore = "Connector Refunds the payment on Void call for Auto Captured Payment"]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(500), 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("Record(s) Not Found.")
);
}
// 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(100),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Return Not Allowed.",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/taxjar.rs | crates/router/tests/connectors/taxjar.rs | use masking::Secret;
use router::types::{self, api, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct TaxjarTest;
impl ConnectorActions for TaxjarTest {}
impl utils::Connector for TaxjarTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Taxjar;
utils::construct_connector_data_old(
Box::new(Taxjar::new()),
types::Connector::Adyen,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.taxjar
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"taxjar".to_string()
}
}
static CONNECTOR: TaxjarTest = TaxjarTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/worldline.rs | crates/router/tests/connectors/worldline.rs | use std::str::FromStr;
use hyperswitch_domain_models::address::{Address, AddressDetails};
use masking::Secret;
use router::{
connector::Worldline,
core::errors,
types::{self, storage::enums, PaymentAddress},
};
use crate::{
connector_auth::ConnectorAuthentication,
utils::{self, ConnectorActions, PaymentInfo},
};
struct WorldlineTest;
impl ConnectorActions for WorldlineTest {}
impl utils::Connector for WorldlineTest {
fn get_data(&self) -> types::api::ConnectorData {
utils::construct_connector_data_old(
Box::new(&Worldline),
types::Connector::Worldline,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
ConnectorAuthentication::new()
.worldline
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
String::from("worldline")
}
}
impl WorldlineTest {
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
first_name: Some(Secret::new(String::from("John"))),
last_name: Some(Secret::new(String::from("Dough"))),
..Default::default()
}),
phone: None,
email: None,
}),
None,
None,
)),
..Default::default()
})
}
fn get_payment_authorize_data(
card_number: &str,
card_exp_month: &str,
card_exp_year: &str,
card_cvc: &str,
capture_method: enums::CaptureMethod,
) -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 3500,
currency: enums::Currency::USD,
payment_method_data: types::domain::PaymentMethodData::Card(types::domain::Card {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
card_issuing_country_code: None,
bank_code: None,
nick_name: Some(Secret::new("nick_name".into())),
card_holder_name: Some(Secret::new("card holder name".into())),
co_badged_card_data: None,
}),
confirm: true,
setup_future_usage: None,
mandate_id: None,
off_session: None,
setup_mandate_details: None,
capture_method: Some(capture_method),
browser_info: None,
order_details: None,
order_category: None,
email: None,
customer_name: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: None,
customer_id: None,
surcharge_details: None,
request_incremental_authorization: false,
metadata: None,
authentication_data: None,
customer_acceptance: None,
billing_descriptor: None,
..utils::PaymentAuthorizeType::default().0
})
}
}
#[actix_web::test]
async fn should_requires_manual_authorization() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"5424 1802 7979 1732",
"10",
"25",
"123",
enums::CaptureMethod::Manual,
);
let response = WorldlineTest {}
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Authorized);
}
#[actix_web::test]
async fn should_auto_authorize_and_request_capture() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"2025",
"123",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
}
#[actix_web::test]
async fn should_throw_not_implemented_for_unsupported_issuer() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"630495060000000000",
"10",
"25",
"123",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await;
assert_eq!(
*response.unwrap_err().current_context(),
errors::ConnectorError::NotSupported {
message: "Maestro".to_string(),
connector: "worldline",
}
)
}
#[actix_web::test]
async fn should_throw_missing_required_field_for_country() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"2025",
"123",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(
authorize_data,
Some(PaymentInfo {
address: Some(PaymentAddress::new(None, None, None, None)),
..Default::default()
}),
)
.await;
assert_eq!(
*response.unwrap_err().current_context(),
errors::ConnectorError::MissingRequiredField {
field_name: "billing.address.country"
}
)
}
#[actix_web::test]
async fn should_fail_payment_for_invalid_cvc() {
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"25",
"",
enums::CaptureMethod::Automatic,
);
let response = WorldlineTest {}
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"NULL VALUE NOT ALLOWED FOR cardPaymentMethodSpecificInput.card.cvv".to_string(),
);
}
#[actix_web::test]
async fn should_sync_manual_auth_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"2025",
"123",
enums::CaptureMethod::Manual,
);
let response = connector
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let sync_response = connector
.sync_payment(
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
connector_payment_id,
),
capture_method: Some(enums::CaptureMethod::Manual),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
#[actix_web::test]
async fn should_sync_auto_auth_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"25",
"123",
enums::CaptureMethod::Automatic,
);
let response = connector
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let sync_response = connector
.sync_payment(
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
connector_payment_id,
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Pending);
}
#[actix_web::test]
async fn should_capture_authorized_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"2025",
"123",
enums::CaptureMethod::Manual,
);
let response = connector
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let capture_response = WorldlineTest {}
.capture_payment(connector_payment_id, None, None)
.await
.unwrap();
assert_eq!(
capture_response.status,
enums::AttemptStatus::CaptureInitiated
);
}
#[actix_web::test]
async fn should_fail_capture_payment() {
let capture_response = WorldlineTest {}
.capture_payment("123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
"UNKNOWN_PAYMENT_ID".to_string()
);
}
#[actix_web::test]
async fn should_cancel_unauthorized_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"25",
"123",
enums::CaptureMethod::Manual,
);
let response = connector
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let cancel_response = connector
.void_payment(connector_payment_id, None, None)
.await
.unwrap();
assert_eq!(cancel_response.status, enums::AttemptStatus::Voided);
}
#[actix_web::test]
async fn should_cancel_uncaptured_payment() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012000033330026",
"10",
"2025",
"123",
enums::CaptureMethod::Automatic,
);
let response = connector
.make_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Pending);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let cancel_response = connector
.void_payment(connector_payment_id, None, None)
.await
.unwrap();
assert_eq!(cancel_response.status, enums::AttemptStatus::Voided);
}
#[actix_web::test]
async fn should_fail_cancel_with_invalid_payment_id() {
let response = WorldlineTest {}
.void_payment("123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"UNKNOWN_PAYMENT_ID".to_string(),
);
}
#[actix_web::test]
async fn should_fail_refund_with_invalid_payment_status() {
let connector = WorldlineTest {};
let authorize_data = WorldlineTest::get_payment_authorize_data(
"4012 0000 3333 0026",
"10",
"25",
"123",
enums::CaptureMethod::Manual,
);
let response = connector
.authorize_payment(authorize_data, WorldlineTest::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
let connector_payment_id =
utils::get_connector_transaction_id(response.response).unwrap_or_default();
let refund_response = connector
.refund_payment(connector_payment_id, None, None)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap_err().message,
"ORDER WITHOUT REFUNDABLE PAYMENTS".to_string(),
);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/payu.rs | crates/router/tests/connectors/payu.rs | use common_enums::GooglePayCardFundingSource;
use masking::PeekInterface;
use router::types::{self, domain, storage::enums, AccessToken, ConnectorAuthType};
use crate::{
connector_auth,
utils::{self, Connector, ConnectorActions, PaymentAuthorizeType},
};
struct Payu;
impl ConnectorActions for Payu {}
impl Connector for Payu {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Payu;
utils::construct_connector_data_old(
Box::new(Payu::new()),
types::Connector::Payu,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.payu
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"payu".to_string()
}
}
fn get_access_token() -> Option<AccessToken> {
let connector = Payu {};
match connector.get_auth_token() {
ConnectorAuthType::BodyKey { api_key, key1 } => Some(AccessToken {
token: api_key,
expires: key1.peek().parse::<i64>().unwrap(),
}),
_ => None,
}
}
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
Some(utils::PaymentInfo {
access_token: get_access_token(),
..Default::default()
})
}
#[actix_web::test]
#[ignore]
async fn should_authorize_card_payment() {
//Authorize Card Payment in PLN currency
let authorize_response = Payu {}
.authorize_payment(
Some(types::PaymentsAuthorizeData {
currency: enums::Currency::PLN,
..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
// in Payu need Psync to get status therefore set to pending
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response.response) {
let sync_response = Payu {}
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
// Assert the sync response, it will be authorized in case of manual capture, for automatic it will be Completed Success
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
}
#[actix_web::test]
async fn should_authorize_gpay_payment() {
let authorize_response = Payu {}
.authorize_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Wallet(
domain::WalletData::GooglePay(domain::GooglePayWalletData {
pm_type: "CARD".to_string(),
description: "Visa1234567890".to_string(),
info: domain::GooglePayPaymentMethodInfo {
card_network: "VISA".to_string(),
card_details: "1234".to_string(),
assurance_details: None,
card_funding_source: Some(GooglePayCardFundingSource::Unknown),
},
tokenization_data: common_types::payments::GpayTokenizationData::Encrypted(
common_types::payments::GpayEcryptedTokenizationData {
token_type: "worldpay".to_string(),
token: "someToken".to_string(),
},
),
}),
),
currency: enums::Currency::PLN,
..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response.response) {
let sync_response = Payu {}
.sync_payment(
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
}
}
#[actix_web::test]
#[ignore]
async fn should_capture_already_authorized_payment() {
let connector = Payu {};
let authorize_response = connector
.authorize_payment(
Some(types::PaymentsAuthorizeData {
currency: enums::Currency::PLN,
..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response.response) {
let sync_response = connector
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
let capture_response = connector
.capture_payment(transaction_id.clone(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(capture_response.status, enums::AttemptStatus::Pending);
let response = connector
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id,
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
}
#[actix_web::test]
#[ignore]
async fn should_sync_payment() {
let connector = Payu {};
// Authorize the payment for manual capture
let authorize_response = connector
.authorize_payment(
Some(types::PaymentsAuthorizeData {
currency: enums::Currency::PLN,
..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response.response) {
// Sync the Payment Data
let response = connector
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id,
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
}
#[actix_web::test]
#[ignore]
async fn should_void_already_authorized_payment() {
let connector = Payu {};
//make a successful payment
let authorize_response = connector
.make_payment(
Some(types::PaymentsAuthorizeData {
currency: enums::Currency::PLN,
..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
//try CANCEL for previous payment
if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response.response) {
let void_response = connector
.void_payment(transaction_id.clone(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(void_response.status, enums::AttemptStatus::Pending);
let sync_response = connector
.psync_retry_till_status_matches(
enums::AttemptStatus::Voided,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id,
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Voided,);
}
}
#[actix_web::test]
#[ignore]
async fn should_refund_succeeded_payment() {
let connector = Payu {};
let authorize_response = connector
.authorize_payment(
Some(types::PaymentsAuthorizeData {
currency: enums::Currency::PLN,
..PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Pending);
if let Some(transaction_id) = utils::get_connector_transaction_id(authorize_response.response) {
let sync_response = connector
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Authorized);
//Capture the payment in case of Manual Capture
let capture_response = connector
.capture_payment(transaction_id.clone(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(capture_response.status, enums::AttemptStatus::Pending);
let sync_response = connector
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
transaction_id.clone(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(sync_response.status, enums::AttemptStatus::Charged);
//Refund the payment
let refund_response = connector
.refund_payment(transaction_id.clone(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().connector_refund_id.len(),
10
);
}
}
#[actix_web::test]
async fn should_sync_succeeded_refund_payment() {
let connector = Payu {};
//Currently hardcoding the order_id because RSync is not instant, change it accordingly
let sync_refund_response = connector
.sync_refund(
"6DHQQN3T57230110GUEST000P01".to_string(),
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
sync_refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success
);
}
#[actix_web::test]
async fn should_fail_already_refunded_payment() {
let connector = Payu {};
//Currently hardcoding the order_id, change it accordingly
let response = connector
.refund_payment(
"5H1SVX6P7W230112GUEST000P01".to_string(),
None,
get_default_payment_info(),
)
.await
.unwrap();
let x = response.response.unwrap_err();
assert_eq!(x.reason.unwrap(), "PAID".to_string());
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/unified_authentication_service.rs | crates/router/tests/connectors/unified_authentication_service.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 UnifiedAuthenticationServiceTest;
impl ConnectorActions for UnifiedAuthenticationServiceTest {}
impl utils::Connector for UnifiedAuthenticationServiceTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::UnifiedAuthenticationService;
utils::construct_connector_data_old(
Box::new(UnifiedAuthenticationService::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.unified_authentication_service
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"unified_authentication_service".to_string()
}
}
static CONNECTOR: UnifiedAuthenticationServiceTest = UnifiedAuthenticationServiceTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/volt.rs | crates/router/tests/connectors/volt.rs | use masking::Secret;
use router::types::{self, domain, storage::enums};
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
struct VoltTest;
impl ConnectorActions for VoltTest {}
impl utils::Connector for VoltTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Volt;
utils::construct_connector_data_old(
Box::new(Volt::new()),
types::Connector::Volt,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.volt
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"volt".to_string()
}
}
static CONNECTOR: VoltTest = VoltTest {};
fn get_default_payment_info() -> Option<utils::PaymentInfo> {
None
}
fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
None
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
payment_method_details(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
get_default_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(payment_method_details(), get_default_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
payment_method_details(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
get_default_payment_info(),
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(
payment_method_details(),
None,
None,
get_default_payment_info(),
)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
capture_method: Some(enums::CaptureMethod::Automatic),
..Default::default()
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let refund_response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await;
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect CVC.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's security code is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration month is invalid.".to_string(),
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Your card's expiration year is invalid.".to_string(),
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(payment_method_details(), get_default_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123456789".to_string(), None, get_default_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("No such payment_intent: '123456789'")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
payment_method_details(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
get_default_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Refund amount (₹1.50) is greater than charge amount (₹1.00)",
);
}
// Connector dependent test cases goes here
// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/loonio.rs | crates/router/tests/connectors/loonio.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 LoonioTest;
impl ConnectorActions for LoonioTest {}
impl utils::Connector for LoonioTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Loonio;
utils::construct_connector_data_old(
Box::new(Loonio::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.loonio
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"loonio".to_string()
}
}
static CONNECTOR: LoonioTest = LoonioTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/facilitapay.rs | crates/router/tests/connectors/facilitapay.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 FacilitapayTest;
impl ConnectorActions for FacilitapayTest {}
impl utils::Connector for FacilitapayTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Facilitapay;
utils::construct_connector_data_old(
Box::new(Facilitapay::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.facilitapay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"facilitapay".to_string()
}
}
static CONNECTOR: FacilitapayTest = FacilitapayTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/tests/connectors/mpgs.rs | crates/router/tests/connectors/mpgs.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 MpgsTest;
impl ConnectorActions for MpgsTest {}
impl utils::Connector for MpgsTest {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Mpgs;
utils::construct_connector_data_old(
Box::new(Mpgs::new()),
types::Connector::Plaid,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.mpgs
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"mpgs".to_string()
}
}
static CONNECTOR: MpgsTest = MpgsTest {};
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
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.