id stringlengths 20 153 | type stringclasses 1
value | granularity stringclasses 14
values | content stringlengths 16 84.3k | metadata dict |
|---|---|---|---|---|
connector-service_mini_domain_types_4311916100995806462_8 | clm | mini_chunk | // connector-service/backend/domain_types/src/errors.rs
// AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
// }
// Self::IncorrectConnectorNameGiven => {
// AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
// }
// Self::AddressNotFound => {
// AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
// },
// Self::DisputeNotFound { .. } => {
// AER::NotFound(ApiError::new("HE", 4, "Dispute does not exist in our records", None))
// },
// Self::FileNotFound => {
// AER::NotFound(ApiError::new("HE", 4, "File does not exist in our records", None))
// }
// Self::FileNotAvailable => {
// AER::NotFound(ApiError::new("HE", 4, "File not available", None))
// }
// Self::MissingTenantId => {
// AER::InternalServerError(ApiError::new("HE", 5, "Missing Tenant ID in the request".to_string(), None))
// }
// Self::InvalidTenant { tenant_id } => {
// AER::InternalServerError(ApiError::new("HE", 5, format!("Invalid Tenant {tenant_id}"), None))
// }
// Self::AmountConversionFailed { amount_type } => {
// AER::InternalServerError(ApiError::new("HE", 6, format!("Failed to convert amount to {amount_type} type"), None))
// }
// Self::NotImplemented { message } => {
// AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
// }
// Self::Unauthorized => AER::Unauthorized(ApiError::new(
// "IR",
// 1,
// "API key not provided or invalid API key used", None
// )),
// Self::InvalidRequestUrl => {
// AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
// }
// Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
// "IR",
// 3,
// "The HTTP method is not applicable for this API", None
// )),
// Self::MissingRequiredField { field_name } => AER::BadRequest(
// ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
// ),
// Self::InvalidDataFormat {
// field_name,
// expected_format,
// } => AER::Unprocessable(ApiError::new(
// "IR",
// 5,
// format!(
// "{field_name} contains invalid data. Expected format is {expected_format}"
// ), None
// )),
// Self::InvalidRequestData { message } => {
// AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
// }
// Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
// "IR",
// 7,
// format!("Invalid value provided: {field_name}"), None
// )),
// Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
// "IR",
// 8,
// "client_secret was not provided", None
// )),
// Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
// "IR",
// 8,
// "The provided client_secret has expired", None
// )),
// Self::ClientSecretInvalid => {
// AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
// }
// Self::MandateActive => {
// AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
// }
// Self::CustomerRedacted => {
// AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
// }
| {
"chunk": 8,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_4311916100995806462_9 | clm | mini_chunk | // connector-service/backend/domain_types/src/errors.rs
// Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
// Self::RefundAmountExceedsPaymentAmount => {
// AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None))
// }
// Self::PaymentUnexpectedState {
// current_flow,
// field_name,
// current_value,
// states,
// } => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
// Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
// Self::PreconditionFailed { message } => {
// AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
// }
// Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
// Self::GenericUnauthorized { message } => {
// AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
// },
// Self::NotSupported { message } => {
// AER::BadRequest(ApiError::new("IR", 19, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
// },
// Self::FlowNotSupported { flow, connector } => {
// AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
// }
// Self::MissingRequiredFields { field_names } => AER::BadRequest(
// ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
// ),
// Self::AccessForbidden {resource} => {
// AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None))
// },
// Self::FileProviderNotSupported { message } => {
// AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
// },
// Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new(
// "IR",
// 24,
// format!("Invalid {wallet_name} wallet token"), None
// )),
// Self::PaymentMethodDeleteFailed => {
// AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
// }
// Self::InvalidCookie => {
// AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None))
// }
// Self::ExtendedCardInfoNotFound => {
// AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None))
// }
// Self::CurrencyNotSupported { message } => {
// AER::BadRequest(ApiError::new("IR", 28, message, None))
// }
// Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 29, message.to_string(), None)),
// Self::InvalidConnectorConfiguration {config} => {
// AER::BadRequest(ApiError::new("IR", 30, format!("Merchant connector account is configured with invalid {config}"), None))
// }
// Self::InvalidCardIin => AER::BadRequest(ApiError::new("IR", 31, "The provided card IIN does not exist", None)),
// Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("IR", 32, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
// Self::MissingFile => {
// AER::BadRequest(ApiError::new("IR", 33, "File not found in the request", None))
// }
// Self::MissingDisputeId => {
| {
"chunk": 9,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_4311916100995806462_10 | clm | mini_chunk | // connector-service/backend/domain_types/src/errors.rs
// AER::BadRequest(ApiError::new("IR", 34, "Dispute id not found in the request", None))
// }
// Self::MissingFilePurpose => {
// AER::BadRequest(ApiError::new("IR", 35, "File purpose not found in the request or is invalid", None))
// }
// Self::MissingFileContentType => {
// AER::BadRequest(ApiError::new("IR", 36, "File content type not found", None))
// }
// Self::GenericNotFoundError { message } => {
// AER::NotFound(ApiError::new("IR", 37, message, None))
// },
// Self::GenericDuplicateError { message } => {
// AER::BadRequest(ApiError::new("IR", 38, message, None))
// }
// Self::IncorrectPaymentMethodConfiguration => {
// AER::BadRequest(ApiError::new("IR", 39, "No eligible connector was found for the current payment method configuration", None))
// }
// Self::LinkConfigurationError { message } => {
// AER::BadRequest(ApiError::new("IR", 40, message, None))
// },
// Self::PayoutFailed { data } => {
// AER::BadRequest(ApiError::new("IR", 41, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()})))
// },
// Self::CookieNotFound => {
// AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None))
// },
// Self::ExternalVaultFailed => {
// AER::BadRequest(ApiError::new("IR", 45, "External Vault failed while processing with connector.", None))
// },
// Self::WebhookAuthenticationFailed => {
// AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
// }
// Self::WebhookBadRequest => {
// AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
// }
// Self::WebhookProcessingFailure => {
// AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
// },
// Self::WebhookResourceNotFound => {
// AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
// }
// Self::WebhookUnprocessableEntity => {
// AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
// },
// Self::WebhookInvalidMerchantSecret => {
// AER::BadRequest(ApiError::new("WE", 6, "Merchant Secret set for webhook source verification is invalid", None))
// }
// Self::IntegrityCheckFailed {
// reason,
// field_names,
// connector_transaction_id
// } => AER::InternalServerError(ApiError::new(
// "IE",
// 0,
// format!("{} as data mismatched for {}", reason, field_names),
// Some(Extra {
// connector_transaction_id: connector_transaction_id.to_owned(),
// ..Default::default()
// })
// )),
// Self::PlatformAccountAuthNotSupported => {
// AER::BadRequest(ApiError::new("IR", 43, "API does not support platform operation", None))
// }
// Self::InvalidPlatformOperation => {
// AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None))
// }
// }
// }
// }
// impl actix_web::ResponseError for ApiErrorResponse {
// fn status_code(&self) -> StatusCode {
// ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).status_code()
// }
// fn error_response(&self) -> actix_web::HttpResponse {
// ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).error_response()
// }
// }
impl From<ApiErrorResponse> for crate::router_data::ErrorResponse {
fn from(error: ApiErrorResponse) -> Self {
Self {
| {
"chunk": 10,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_4311916100995806462_11 | clm | mini_chunk | // connector-service/backend/domain_types/src/errors.rs
code: error.error_code(),
message: error.error_message(),
reason: None,
status_code: match error {
ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code,
_ => 500,
},
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}
}
}
/// Connector Errors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Error while obtaining URL for the integration")]
FailedToObtainIntegrationUrl,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Request encoding failed : {0}")]
RequestEncodingFailedWithReason(String),
#[error("Parsing failed")]
ParsingFailed,
#[error("Integrity check failed: {field_names}")]
IntegrityCheckFailed {
field_names: String,
connector_transaction_id: Option<String>,
},
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("The connector returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to parse custom routing rules from merchant account")]
RoutingRulesParsingError,
#[error("Failed to obtain preferred connector from merchant account")]
FailedToObtainPreferredConnector,
#[error("An invalid connector name was provided")]
InvalidConnectorName,
#[error("An invalid Wallet was used")]
InvalidWallet,
#[error("Failed to handle connector response")]
ResponseHandlingFailed,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Missing required fields: {field_names:?}")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Failed to obtain certificate")]
FailedToObtainCertificate,
#[error("Connector meta data not found")]
NoConnectorMetaData,
#[error("Connector wallet details not found")]
NoConnectorWalletDetails,
#[error("Failed to obtain certificate key")]
FailedToObtainCertificateKey,
#[error("Failed to verify source of the response")]
SourceVerificationFailed,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
#[error("{message} is not supported by {connector}")]
NotSupported {
message: String,
connector: &'static str,
},
#[error("{flow} flow not supported by {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error("Capture method not supported")]
CaptureMethodNotSupported,
#[error("Missing connector mandate ID")]
MissingConnectorMandateID,
#[error("Missing connector mandate metadata")]
MissingConnectorMandateMetadata,
#[error("Missing connector transaction ID")]
MissingConnectorTransactionID,
#[error("Missing connector refund ID")]
MissingConnectorRefundID,
#[error("Missing apple pay tokenization data")]
MissingApplePayTokenData,
#[error("Webhooks not implemented for this connector")]
WebhooksNotImplemented,
#[error("Failed to decode webhook event body")]
WebhookBodyDecodingFailed,
#[error("Signature not found for incoming webhook")]
WebhookSignatureNotFound,
#[error("Failed to verify webhook source")]
WebhookSourceVerificationFailed,
#[error("Could not find merchant secret in DB for incoming webhook source verification")]
WebhookVerificationSecretNotFound,
#[error("Merchant secret found for incoming webhook source verification is invalid")]
WebhookVerificationSecretInvalid,
#[error("Incoming webhook object reference ID not found")]
WebhookReferenceIdNotFound,
#[error("Incoming webhook event type not found")]
WebhookEventTypeNotFound,
#[error("Incoming webhook event resource object not found")]
WebhookResourceObjectNotFound,
| {
"chunk": 11,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_4311916100995806462_12 | clm | mini_chunk | // connector-service/backend/domain_types/src/errors.rs
#[error("Could not respond to the incoming webhook event")]
WebhookResponseEncodingFailed,
#[error("Invalid Date/time format")]
InvalidDateFormat,
#[error("Date Formatting Failed")]
DateFormattingFailed,
#[error("Invalid Data format")]
InvalidDataFormat { field_name: &'static str },
#[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
MismatchedPaymentData,
#[error("Failed to parse {wallet_name} wallet token")]
InvalidWalletToken { wallet_name: String },
#[error("Missing Connector Related Transaction ID")]
MissingConnectorRelatedTransactionID { id: String },
#[error("File Validation failed")]
FileValidationFailed { reason: String },
#[error("Missing 3DS redirection payload: {field_name}")]
MissingConnectorRedirectionPayload { field_name: &'static str },
#[error("Failed at connector's end with code '{code}'")]
FailedAtConnector { message: String, code: String },
#[error("Payment Method Type not found")]
MissingPaymentMethodType,
#[error("Balance in the payment method is low")]
InSufficientBalanceInPaymentMethod,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("The given currency method is not configured with the given connector")]
CurrencyNotSupported {
message: String,
connector: &'static str,
},
#[error("Invalid Configuration")]
InvalidConnectorConfig { config: &'static str },
#[error("Failed to convert amount to required type")]
AmountConversionFailed,
#[error("Generic Error")]
GenericError {
error_message: String,
error_object: serde_json::Value,
},
#[error("Field {fields} doesn't match with the ones used during mandate creation")]
MandatePaymentDataMismatch { fields: String },
}
impl ConnectorError {
/// fn is_connector_timeout
pub fn is_connector_timeout(&self) -> bool {
self == &Self::RequestTimeoutReceived
}
}
impl ErrorSwitch<ConnectorError> for common_utils::errors::ParsingError {
fn switch(&self) -> ConnectorError {
ConnectorError::ParsingFailed
}
}
impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
fn switch(&self) -> ApiErrorResponse {
match self {
Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed,
Self::WebhookSignatureNotFound
| Self::WebhookReferenceIdNotFound
| Self::WebhookResourceObjectNotFound
| Self::WebhookBodyDecodingFailed
| Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest,
Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity,
Self::WebhookVerificationSecretInvalid => {
ApiErrorResponse::WebhookInvalidMerchantSecret
}
_ => ApiErrorResponse::InternalServerError,
}
}
}
// http client errors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, Clone, thiserror::Error, PartialEq)]
pub enum HttpClientError {
#[error("Header map construction failed")]
HeaderMapConstructionFailed,
#[error("Invalid proxy configuration")]
InvalidProxyConfiguration,
#[error("Client construction failed")]
ClientConstructionFailed,
#[error("Certificate decode failed")]
CertificateDecodeFailed,
#[error("Request body serialization failed")]
BodySerializationFailed,
#[error("Unexpected state reached/Invariants conflicted")]
UnexpectedState,
#[error("Failed to parse URL")]
UrlParsingFailed,
#[error("URL encoding of request payload failed")]
UrlEncodingFailed,
#[error("Failed to send request to connector {0}")]
RequestNotSent(String),
#[error("Failed to decode response")]
ResponseDecodingFailed,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("connection closed before a message could complete")]
ConnectionClosedIncompleteMessage,
#[error("Server responded with Internal Server Error")]
InternalServerErrorReceived,
#[error("Server responded with Bad Gateway")]
BadGatewayReceived,
#[error("Server responded with Service Unavailable")]
ServiceUnavailableReceived,
| {
"chunk": 12,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_4311916100995806462_13 | clm | mini_chunk | // connector-service/backend/domain_types/src/errors.rs
#[error("Server responded with Gateway Timeout")]
GatewayTimeoutReceived,
#[error("Server responded with unexpected response")]
UnexpectedServerResponse,
}
impl ErrorSwitch<ApiClientError> for HttpClientError {
fn switch(&self) -> ApiClientError {
match self {
Self::HeaderMapConstructionFailed => ApiClientError::HeaderMapConstructionFailed,
Self::InvalidProxyConfiguration => ApiClientError::InvalidProxyConfiguration,
Self::ClientConstructionFailed => ApiClientError::ClientConstructionFailed,
Self::CertificateDecodeFailed => ApiClientError::CertificateDecodeFailed,
Self::BodySerializationFailed => ApiClientError::BodySerializationFailed,
Self::UnexpectedState => ApiClientError::UnexpectedState,
Self::UrlParsingFailed => ApiClientError::UrlParsingFailed,
Self::UrlEncodingFailed => ApiClientError::UrlEncodingFailed,
Self::RequestNotSent(reason) => ApiClientError::RequestNotSent(reason.clone()),
Self::ResponseDecodingFailed => ApiClientError::ResponseDecodingFailed,
Self::RequestTimeoutReceived => ApiClientError::RequestTimeoutReceived,
Self::ConnectionClosedIncompleteMessage => {
ApiClientError::ConnectionClosedIncompleteMessage
}
Self::InternalServerErrorReceived => ApiClientError::InternalServerErrorReceived,
Self::BadGatewayReceived => ApiClientError::BadGatewayReceived,
Self::ServiceUnavailableReceived => ApiClientError::ServiceUnavailableReceived,
Self::GatewayTimeoutReceived => ApiClientError::GatewayTimeoutReceived,
Self::UnexpectedServerResponse => ApiClientError::UnexpectedServerResponse,
}
}
}
| {
"chunk": 13,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_6123773352099696515_0 | clm | mini_chunk | // connector-service/backend/domain_types/src/router_response_types.rs
use std::collections::HashMap;
use common_utils::Method;
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub enum RedirectForm {
Form {
endpoint: String,
method: Method,
form_fields: HashMap<String, String>,
},
Html {
html_data: String,
},
BlueSnap {
payment_fields_token: String, // payment-field-token
},
CybersourceAuthSetup {
access_token: String,
ddc_url: String,
reference_id: String,
},
CybersourceConsumerAuth {
access_token: String,
step_up_url: String,
},
DeutschebankThreeDSChallengeFlow {
acs_url: String,
creq: String,
},
Payme,
Braintree {
client_token: String,
card_token: String,
bin: String,
acs_url: String,
},
Nmi {
amount: String,
currency: common_enums::Currency,
public_key: hyperswitch_masking::Secret<String>,
customer_vault_id: String,
order_id: String,
},
Mifinity {
initialization_token: String,
},
WorldpayDDCForm {
endpoint: url::Url,
method: Method,
form_fields: HashMap<String, String>,
collection_id: Option<String>,
},
Uri {
uri: String,
},
}
impl From<(url::Url, Method)> for RedirectForm {
fn from((mut redirect_url, method): (url::Url, Method)) -> Self {
let form_fields = HashMap::from_iter(
redirect_url
.query_pairs()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
// Do not include query params in the endpoint
redirect_url.set_query(None);
Self::Form {
endpoint: redirect_url.to_string(),
method,
form_fields,
}
}
}
#[derive(Clone, Debug)]
pub struct Response {
/// headers
pub headers: Option<http::HeaderMap>,
/// response
pub response: bytes::Bytes,
/// status code
pub status_code: u16,
}
| {
"chunk": 0,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_0 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
use std::fmt::Debug;
use base64::Engine;
use common_enums::{CardNetwork, CountryAlpha2, RegulatedName, SamsungPayCardBrand};
use common_utils::{
ext_traits::OptionExt, new_types::MaskedBankAccount, pii::UpiVpaMaskingStrategy, Email,
ValidationError,
};
use error_stack::{self, ResultExt};
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use time::Date;
use utoipa::ToSchema;
use crate::{
errors,
router_data::NetworkTokenNumber,
utils::{get_card_issuer, missing_field_err, CardIssuer, Error},
};
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct Card<T: PaymentMethodDataTypes> {
pub card_number: RawCardNumber<T>,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_cvc: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub co_badged_card_data: Option<CoBadgedCardData>,
}
pub trait PaymentMethodDataTypes: Clone {
type Inner: Default + Debug + Send + Eq + PartialEq + Serialize + DeserializeOwned + Clone;
}
/// PCI holder implementation for handling raw PCI data
#[derive(Default, Debug, Eq, PartialEq, Serialize, Deserialize, Clone)]
pub struct DefaultPCIHolder;
/// Vault token holder implementation for handling vault token data
#[derive(Default, Debug, Eq, PartialEq, Serialize, Deserialize, Clone)]
pub struct VaultTokenHolder;
/// Generic CardNumber struct that uses PaymentMethodDataTypes trait
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct RawCardNumber<T: PaymentMethodDataTypes>(pub T::Inner);
impl RawCardNumber<DefaultPCIHolder> {
pub fn peek(&self) -> &str {
self.0.peek()
}
}
impl RawCardNumber<VaultTokenHolder> {
pub fn peek(&self) -> &str {
&self.0
}
}
impl PaymentMethodDataTypes for DefaultPCIHolder {
type Inner = cards::CardNumber;
}
impl PaymentMethodDataTypes for VaultTokenHolder {
type Inner = String; //Token
}
// Generic implementation for all Card<T> types
impl<T: PaymentMethodDataTypes> Card<T> {
pub fn get_card_expiry_year_2_digit(
&self,
) -> Result<Secret<String>, crate::errors::ConnectorError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(crate::errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
pub fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, crate::errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
)))
}
pub fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.card_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
pub fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.card_exp_month
.peek()
.clone()
.parse::<i8>()
.change_context(crate::errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
}
impl Card<DefaultPCIHolder> {
pub fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
pub fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.card_exp_month.peek()
))
}
pub fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
))
}
| {
"chunk": 0,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_1 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
pub fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, crate::errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
pub fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.card_exp_year
.peek()
.clone()
.parse::<i32>()
.change_context(crate::errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum PaymentMethodData<T: PaymentMethodDataTypes> {
Card(Card<T>),
CardDetailsForNetworkTransactionId(CardDetailsForNetworkTransactionId),
CardRedirect(CardRedirectData),
Wallet(WalletData),
PayLater(PayLaterData),
BankRedirect(BankRedirectData),
BankDebit(BankDebitData),
BankTransfer(Box<BankTransferData>),
Crypto(CryptoData),
MandatePayment,
Reward,
RealTimePayment(Box<RealTimePaymentData>),
Upi(UpiData),
Voucher(VoucherData),
GiftCard(Box<GiftCardData>),
CardToken(CardToken),
OpenBanking(OpenBankingData),
NetworkToken(NetworkTokenData),
MobilePayment(MobilePaymentData),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenBankingData {
OpenBankingPIS {},
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MobilePaymentData {
DirectCarrierBilling {
/// The phone number of the user
msisdn: String,
/// Unique user identifier
client_uid: Option<String>,
},
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct NetworkTokenData {
pub network_token: cards::NetworkToken,
pub network_token_exp_month: Secret<String>,
pub network_token_exp_year: Secret<String>,
pub cryptogram: Option<Secret<String>>,
pub card_issuer: Option<String>, //since network token is tied to card, so its issuer will be same as card issuer
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<CardType>,
pub card_issuing_country: Option<common_enums::CountryAlpha2>,
pub bank_code: Option<String>,
pub card_holder_name: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub eci: Option<String>,
}
impl NetworkTokenData {
pub fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.network_token.peek())
}
pub fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.network_token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
pub fn get_network_token(&self) -> NetworkTokenNumber {
self.network_token.clone()
}
pub fn get_network_token_expiry_month(&self) -> Secret<String> {
self.network_token_exp_month.clone()
}
pub fn get_network_token_expiry_year(&self) -> Secret<String> {
self.network_token_exp_year.clone()
}
pub fn get_cryptogram(&self) -> Option<Secret<String>> {
self.cryptogram.clone()
}
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum GiftCardData {
Givex(GiftCardDetails),
PaySafeCard {},
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct GiftCardDetails {
/// The gift card number
pub number: Secret<String>,
/// The card verification code.
pub cvc: Secret<String>,
}
#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)]
#[serde(rename_all = "snake_case")]
pub struct CardToken {
/// The card holder's name
pub card_holder_name: Option<Secret<String>>,
/// The CVC number for the card
pub card_cvc: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct BoletoVoucherData {
/// The shopper's social security number
pub social_security_number: Option<Secret<String>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
| {
"chunk": 1,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_2 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
pub struct AlfamartVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct IndomaretVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct JCSVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VoucherData {
Boleto(Box<BoletoVoucherData>),
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart(Box<AlfamartVoucherData>),
Indomaret(Box<IndomaretVoucherData>),
Oxxo,
SevenEleven(Box<JCSVoucherData>),
Lawson(Box<JCSVoucherData>),
MiniStop(Box<JCSVoucherData>),
FamilyMart(Box<JCSVoucherData>),
Seicomart(Box<JCSVoucherData>),
PayEasy(Box<JCSVoucherData>),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpiData {
/// UPI Collect - Customer approves a collect request sent to their UPI app
UpiCollect(UpiCollectData),
/// UPI Intent - Customer is redirected to their UPI app with a pre-filled payment request
UpiIntent(UpiIntentData),
/// UPI QR - Unique QR generated per txn
UpiQr(UpiQrData),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct UpiCollectData {
pub vpa_id: Option<Secret<String, UpiVpaMaskingStrategy>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct UpiIntentData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct UpiQrData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum RealTimePaymentData {
DuitNow {},
Fps {},
PromptPay {},
VietQr {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct CryptoData {
pub pay_currency: Option<String>,
pub network: Option<String>,
}
impl CryptoData {
pub fn get_pay_currency(&self) -> Result<String, Error> {
self.pay_currency
.clone()
.ok_or_else(missing_field_err("crypto_data.pay_currency"))
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BankTransferData {
AchBankTransfer {},
SepaBankTransfer {},
BacsBankTransfer {},
MultibancoBankTransfer {},
PermataBankTransfer {},
BcaBankTransfer {},
BniVaBankTransfer {},
BriVaBankTransfer {},
CimbVaBankTransfer {},
DanamonVaBankTransfer {},
MandiriVaBankTransfer {},
Pix {
/// Unique key for pix transfer
pix_key: Option<Secret<String>>,
/// CPF is a Brazilian tax identification number
cpf: Option<Secret<String>>,
/// CNPJ is a Brazilian company tax identification number
cnpj: Option<Secret<String>>,
/// Source bank account UUID
source_bank_account_id: Option<MaskedBankAccount>,
/// Destination bank account UUID.
destination_bank_account_id: Option<MaskedBankAccount>,
},
Pse {},
LocalBankTransfer {
bank_code: Option<String>,
},
InstantBankTransfer {},
InstantBankTransferFinland {},
InstantBankTransferPoland {},
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum BankDebitData {
AchBankDebit {
account_number: Secret<String>,
routing_number: Secret<String>,
card_holder_name: Option<Secret<String>>,
bank_account_holder_name: Option<Secret<String>>,
bank_name: Option<common_enums::BankNames>,
bank_type: Option<common_enums::BankType>,
bank_holder_type: Option<common_enums::BankHolderType>,
},
SepaBankDebit {
iban: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
BecsBankDebit {
account_number: Secret<String>,
bsb_number: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
BacsBankDebit {
account_number: Secret<String>,
sort_code: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum BankRedirectData {
BancontactCard {
| {
"chunk": 2,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_3 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
card_number: Option<cards::CardNumber>,
card_exp_month: Option<Secret<String>>,
card_exp_year: Option<Secret<String>>,
card_holder_name: Option<Secret<String>>,
},
Bizum {},
Blik {
blik_code: Option<String>,
},
Eps {
bank_name: Option<common_enums::BankNames>,
country: Option<CountryAlpha2>,
},
Giropay {
bank_account_bic: Option<Secret<String>>,
bank_account_iban: Option<Secret<String>>,
country: Option<CountryAlpha2>,
},
Ideal {
bank_name: Option<common_enums::BankNames>,
},
Interac {
country: Option<CountryAlpha2>,
email: Option<Email>,
},
OnlineBankingCzechRepublic {
issuer: common_enums::BankNames,
},
OnlineBankingFinland {
email: Option<Email>,
},
OnlineBankingPoland {
issuer: common_enums::BankNames,
},
OnlineBankingSlovakia {
issuer: common_enums::BankNames,
},
OpenBankingUk {
issuer: Option<common_enums::BankNames>,
country: Option<CountryAlpha2>,
},
Przelewy24 {
bank_name: Option<common_enums::BankNames>,
},
Sofort {
country: Option<CountryAlpha2>,
preferred_language: Option<String>,
},
Trustly {
country: Option<CountryAlpha2>,
},
OnlineBankingFpx {
issuer: common_enums::BankNames,
},
OnlineBankingThailand {
issuer: common_enums::BankNames,
},
LocalBankRedirect {},
Eft {
provider: String,
},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum PayLaterData {
KlarnaRedirect {},
KlarnaSdk { token: String },
AffirmRedirect {},
AfterpayClearpayRedirect {},
PayBrightRedirect {},
WalleyRedirect {},
AlmaRedirect {},
AtomeRedirect {},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum WalletData {
AliPayQr(Box<AliPayQr>),
AliPayRedirect(AliPayRedirection),
AliPayHkRedirect(AliPayHkRedirection),
BluecodeRedirect {},
AmazonPayRedirect(Box<AmazonPayRedirectData>),
MomoRedirect(MomoRedirection),
KakaoPayRedirect(KakaoPayRedirection),
GoPayRedirect(GoPayRedirection),
GcashRedirect(GcashRedirection),
ApplePay(ApplePayWalletData),
ApplePayRedirect(Box<ApplePayRedirectData>),
ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>),
DanaRedirect {},
GooglePay(GooglePayWalletData),
GooglePayRedirect(Box<GooglePayRedirectData>),
GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>),
MbWayRedirect(Box<MbWayRedirection>),
MobilePayRedirect(Box<MobilePayRedirection>),
PaypalRedirect(PaypalRedirection),
PaypalSdk(PayPalWalletData),
Paze(PazeWalletData),
SamsungPay(Box<SamsungPayWalletData>),
TwintRedirect {},
VippsRedirect {},
TouchNGoRedirect(Box<TouchNGoRedirection>),
WeChatPayRedirect(Box<WeChatPayRedirection>),
WeChatPayQr(Box<WeChatPayQr>),
CashappQr(Box<CashappQr>),
SwishQr(SwishQrData),
Mifinity(MifinityData),
RevolutPay(RevolutPayData),
}
impl WalletData {
pub fn get_wallet_token(&self) -> Result<Secret<String>, Error> {
match self {
Self::GooglePay(data) => Ok(data.get_googlepay_encrypted_payment_data()?),
Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?),
Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())),
_ => Err(crate::errors::ConnectorError::InvalidWallet.into()),
}
}
pub fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_str::<T>(self.get_wallet_token()?.peek())
.change_context(crate::errors::ConnectorError::InvalidWalletToken { wallet_name })
}
pub fn get_encoded_wallet_token(&self) -> Result<String, Error> {
match self {
Self::GooglePay(_) => {
let json_token: serde_json::Value =
self.get_wallet_token_as_json("Google Pay".to_owned())?;
let token_as_vec = serde_json::to_vec(&json_token).change_context(
crate::errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
},
)?;
| {
"chunk": 3,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_4 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
let encoded_token = base64::engine::general_purpose::STANDARD.encode(token_as_vec);
Ok(encoded_token)
}
_ => Err(crate::errors::ConnectorError::NotImplemented(
"SELECTED PAYMENT METHOD".to_owned(),
)
.into()),
}
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct RevolutPayData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct MifinityData {
#[schema(value_type = Date)]
pub date_of_birth: Secret<Date>,
pub language_preference: Option<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct SwishQrData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct CashappQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct WeChatPayQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct WeChatPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct TouchNGoRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletCredentials {
pub method: Option<String>,
pub recurring_payment: Option<bool>,
pub card_brand: common_enums::SamsungPayCardBrand,
pub dpan_last_four_digits: Option<String>,
#[serde(rename = "card_last4digits")]
pub card_last_four_digits: String,
#[serde(rename = "3_d_s")]
pub token_data: SamsungPayTokenData,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayTokenData {
#[serde(rename = "type")]
pub three_ds_type: Option<String>,
pub version: String,
pub data: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletData {
pub payment_credential: SamsungPayWalletCredentials,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct PazeWalletData {
#[schema(value_type = String)]
pub complete_response: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PayPalWalletData {
/// Token generated for the Apple pay
pub token: String,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaypalRedirection {
/// paypal's email address
#[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
pub email: Option<Email>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GooglePayThirdPartySdkData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct GooglePayWalletData {
/// The type of payment method
#[serde(rename = "type")]
pub pm_type: String,
/// User-facing message to describe the payment method that funds this transaction.
pub description: String,
/// The information of the payment method
pub info: GooglePayPaymentMethodInfo,
/// The tokenization data of Google pay
pub tokenization_data: GpayTokenizationData,
}
impl GooglePayWalletData {
fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error> {
let encrypted_data = self
.tokenization_data
.get_encrypted_google_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
})?;
Ok(Secret::new(encrypted_data.token.clone()))
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
/// This enum is used to represent the Gpay payment data, which can either be encrypted or decrypted.
pub enum GpayTokenizationData {
| {
"chunk": 4,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_5 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
/// This variant contains the decrypted Gpay payment data as a structured object.
Decrypted(GPayPredecryptData),
/// This variant contains the encrypted Gpay payment data as a string.
Encrypted(GpayEcryptedTokenizationData),
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
/// This struct represents the decrypted Google Pay payment data
pub struct GPayPredecryptData {
/// The card's expiry month
pub card_exp_month: Secret<String>,
/// The card's expiry year
pub card_exp_year: Secret<String>,
/// The Primary Account Number (PAN) of the card
pub application_primary_account_number: cards::CardNumber,
/// Cryptogram generated by the Network
pub cryptogram: Option<Secret<String>>,
/// Electronic Commerce Indicator
pub eci_indicator: Option<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
/// This struct represents the encrypted Gpay payment data
pub struct GpayEcryptedTokenizationData {
/// The type of the token
#[serde(rename = "type")]
pub token_type: String,
/// Token generated for the wallet
pub token: String,
}
impl GpayTokenizationData {
/// Get the encrypted Google Pay payment data, returning an error if it does not exist
pub fn get_encrypted_google_pay_payment_data_mandatory(
&self,
) -> error_stack::Result<&GpayEcryptedTokenizationData, ValidationError> {
match self {
Self::Encrypted(encrypted_data) => Ok(encrypted_data),
Self::Decrypted(_) => Err(ValidationError::InvalidValue {
message: "Encrypted Google Pay payment data is mandatory".to_string(),
}
.into()),
}
}
/// Get the token from Google Pay tokenization data
/// Returns the token string if encrypted data exists, otherwise returns an error
pub fn get_encrypted_google_pay_token(&self) -> error_stack::Result<String, ValidationError> {
Ok(self
.get_encrypted_google_pay_payment_data_mandatory()?
.token
.clone())
}
/// Get the token type from Google Pay tokenization data
/// Returns the token_type string if encrypted data exists, otherwise returns an error
pub fn get_encrypted_token_type(&self) -> error_stack::Result<String, ValidationError> {
Ok(self
.get_encrypted_google_pay_payment_data_mandatory()?
.token_type
.clone())
}
}
impl GPayPredecryptData {
/// Get the four-digit expiration year from the Google Pay pre-decrypt data
pub fn get_four_digit_expiry_year(
&self,
) -> error_stack::Result<Secret<String>, ValidationError> {
let mut year = self.card_exp_year.peek().clone();
// If it's a 2-digit year, convert to 4-digit
if year.len() == 2 {
year = format!("20{year}");
} else if year.len() != 4 {
return Err(ValidationError::InvalidValue {
message: format!(
"Invalid expiry year length: {}. Must be 2 or 4 digits",
year.len()
),
}
.into());
}
Ok(Secret::new(year))
}
/// Get the 2-digit expiration year from the Google Pay pre-decrypt data
pub fn get_two_digit_expiry_year(
&self,
) -> error_stack::Result<Secret<String>, ValidationError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
})?
.to_string(),
))
}
/// Get the expiry date in MMYY format from the Google Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> error_stack::Result<Secret<String>, ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.get_expiry_month()?.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
/// Get the expiration month from the Google Pay pre-decrypt data
pub fn get_expiry_month(&self) -> error_stack::Result<Secret<String>, ValidationError> {
| {
"chunk": 5,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_6 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
let month_str = self.card_exp_month.peek();
let month = month_str
.parse::<u8>()
.map_err(|_| ValidationError::InvalidValue {
message: format!("Failed to parse expiry month: {month_str}"),
})?;
if !(1..=12).contains(&month) {
return Err(ValidationError::InvalidValue {
message: format!("Invalid expiry month: {month}. Must be between 1 and 12"),
}
.into());
}
Ok(self.card_exp_month.clone())
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayPaymentMethodInfo {
/// The name of the card network
pub card_network: String,
/// The details of the card
pub card_details: String,
//assurance_details of the card
pub assurance_details: Option<GooglePayAssuranceDetails>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct GooglePayAssuranceDetails {
///indicates that Cardholder possession validation has been performed
pub card_holder_authenticated: bool,
/// indicates that identification and verifications (ID&V) was performed
pub account_verified: bool,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct GooglePayRedirectData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ApplePayThirdPartySdkData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ApplePayRedirectData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ApplepayPaymentMethod {
/// The name to be displayed on Apple Pay button
pub display_name: String,
/// The network of the Apple pay payment method
pub network: String,
/// The type of the payment method
#[serde(rename = "type")]
pub pm_type: String,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
/// This struct represents the decrypted Apple Pay payment data
pub struct ApplePayPredecryptData {
/// The primary account number
pub application_primary_account_number: cards::CardNumber,
/// The application expiration date (PAN expiry month)
pub application_expiration_month: Secret<String>,
/// The application expiration date (PAN expiry year)
pub application_expiration_year: Secret<String>,
/// The payment data, which contains the cryptogram and ECI indicator
pub payment_data: ApplePayCryptogramData,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
/// This struct represents the cryptogram data for Apple Pay transactions
pub struct ApplePayCryptogramData {
/// The online payment cryptogram
pub online_payment_cryptogram: Secret<String>,
/// The ECI (Electronic Commerce Indicator) value
pub eci_indicator: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
#[serde(untagged)]
/// This enum is used to represent the Apple Pay payment data, which can either be encrypted or decrypted.
pub enum ApplePayPaymentData {
/// This variant contains the decrypted Apple Pay payment data as a structured object.
Decrypted(ApplePayPredecryptData),
/// This variant contains the encrypted Apple Pay payment data as a string.
Encrypted(String),
}
impl ApplePayPaymentData {
/// Get the encrypted Apple Pay payment data if it exists
pub fn get_encrypted_apple_pay_payment_data_optional(&self) -> Option<&String> {
match self {
Self::Encrypted(encrypted_data) => Some(encrypted_data),
Self::Decrypted(_) => None,
}
}
/// Get the decrypted Apple Pay payment data if it exists
pub fn get_decrypted_apple_pay_payment_data_optional(&self) -> Option<&ApplePayPredecryptData> {
match self {
Self::Encrypted(_) => None,
Self::Decrypted(decrypted_data) => Some(decrypted_data),
}
}
/// Get the encrypted Apple Pay payment data, returning an error if it does not exist
| {
"chunk": 6,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_7 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
pub fn get_encrypted_apple_pay_payment_data_mandatory(
&self,
) -> error_stack::Result<&String, ValidationError> {
self.get_encrypted_apple_pay_payment_data_optional()
.get_required_value("Encrypted Apple Pay payment data")
.attach_printable("Encrypted Apple Pay payment data is mandatory")
}
/// Get the decrypted Apple Pay payment data, returning an error if it does not exist
pub fn get_decrypted_apple_pay_payment_data_mandatory(
&self,
) -> error_stack::Result<&ApplePayPredecryptData, ValidationError> {
self.get_decrypted_apple_pay_payment_data_optional()
.get_required_value("Decrypted Apple Pay payment data")
.attach_printable("Decrypted Apple Pay payment data is mandatory")
}
}
impl ApplePayPredecryptData {
/// Get the four-digit expiration year from the Apple Pay pre-decrypt data
pub fn get_two_digit_expiry_year(
&self,
) -> error_stack::Result<Secret<String>, ValidationError> {
let binding = self.application_expiration_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(ValidationError::InvalidValue {
message: "Invalid two-digit year".to_string(),
})?
.to_string(),
))
}
/// Get the four-digit expiration year from the Apple Pay pre-decrypt data
pub fn get_four_digit_expiry_year(&self) -> Secret<String> {
let mut year = self.application_expiration_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
/// Get the expiration month from the Apple Pay pre-decrypt data
pub fn get_expiry_month(&self) -> Secret<String> {
self.application_expiration_month.clone()
}
/// Get the expiry date in MMYY format from the Apple Pay pre-decrypt data
pub fn get_expiry_date_as_mmyy(&self) -> error_stack::Result<Secret<String>, ValidationError> {
let year = self.get_two_digit_expiry_year()?.expose();
let month = self.application_expiration_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ApplePayWalletData {
/// The payment data of Apple pay
pub payment_data: ApplePayPaymentData,
/// The payment method of Apple pay
pub payment_method: ApplepayPaymentMethod,
/// The unique identifier for the transaction
pub transaction_identifier: String,
}
impl ApplePayWalletData {
pub fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> {
let apple_pay_encrypted_data = self
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(crate::errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let token = Secret::new(
String::from_utf8(
base64::engine::general_purpose::STANDARD
.decode(apple_pay_encrypted_data)
.change_context(crate::errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
)
.change_context(crate::errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
);
Ok(token)
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GoPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GcashRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MobilePayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MbWayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct KakaoPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MomoRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
| {
"chunk": 7,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_8 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
pub struct AliPayHkRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayQr {}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum CardRedirectData {
Knet {},
Benefit {},
MomoAtm {},
CardRedirect {},
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct CardDetailsForNetworkTransactionId {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
}
impl CardDetailsForNetworkTransactionId {
pub fn get_card_expiry_year_2_digit(
&self,
) -> Result<Secret<String>, crate::errors::ConnectorError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(crate::errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
pub fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
pub fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, crate::errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
)))
}
pub fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.card_exp_month.peek()
))
}
pub fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
))
}
pub fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.card_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
pub fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, crate::errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
pub fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.card_exp_month
.peek()
.clone()
.parse::<i8>()
.change_context(crate::errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
pub fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.card_exp_year
.peek()
.clone()
.parse::<i32>()
.change_context(crate::errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWebWalletData {
/// Specifies authentication method used
pub method: Option<String>,
/// Value if credential is enabled for recurring payment
pub recurring_payment: Option<bool>,
/// Brand of the payment card
pub card_brand: SamsungPayCardBrand,
/// Last 4 digits of the card number
#[serde(rename = "card_last4digits")]
pub card_last_four_digits: String,
/// Samsung Pay token data
#[serde(rename = "3_d_s")]
pub token_data: SamsungPayTokenData,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct AmazonPayRedirectData {}
| {
"chunk": 8,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4017303140956931129_9 | clm | mini_chunk | // connector-service/backend/domain_types/src/payment_method_data.rs
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CoBadgedCardData {
pub co_badged_card_networks: Vec<CardNetwork>,
pub issuer_country_code: CountryAlpha2,
pub is_regulated: bool,
pub regulated_name: Option<RegulatedName>,
}
#[derive(
Debug,
serde::Deserialize,
serde::Serialize,
Clone,
ToSchema,
strum::EnumString,
strum::Display,
Eq,
PartialEq,
)]
#[serde(rename_all = "snake_case")]
pub enum CardType {
Credit,
Debit,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct BankTransferNextStepsData {
/// The instructions for performing a bank transfer
#[serde(flatten)]
pub bank_transfer_instructions: BankTransferInstructions,
/// The details received by the receiver
pub receiver: Option<ReceiverDetails>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BankTransferInstructions {
/// The credit transfer for ACH transactions
AchCreditTransfer(Box<AchTransfer>),
/// The instructions for Multibanco bank transactions
Multibanco(Box<MultibancoTransferInstructions>),
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AchTransfer {
pub account_number: Secret<String>,
pub bank_name: String,
pub routing_number: Secret<String>,
pub swift_code: Secret<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MultibancoTransferInstructions {
pub reference: Secret<String>,
pub entity: String,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ReceiverDetails {
/// The amount received by receiver
amount_received: i64,
/// The amount charged by ACH
amount_charged: Option<i64>,
/// The amount remaining to be sent via ACH
amount_remaining: Option<i64>,
}
| {
"chunk": 9,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-9203487555415585328_0 | clm | mini_chunk | // connector-service/backend/domain_types/src/mandates.rs
use common_enums::Currency;
use common_utils::{date_time, pii::IpAddress, SecretSerdeValue};
use error_stack::ResultExt;
use hyperswitch_masking::Secret;
use time::PrimitiveDateTime;
use crate::utils::{missing_field_err, Error};
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct CustomerAcceptance {
/// Type of acceptance provided by the
pub acceptance_type: AcceptanceType,
/// Specifying when the customer acceptance was provided
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub accepted_at: Option<PrimitiveDateTime>,
/// Information required for online mandate generation
pub online: Option<OnlineMandate>,
}
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct OnlineMandate {
/// Ip address of the customer machine from which the mandate was created
#[serde(skip_deserializing)]
pub ip_address: Option<Secret<String, IpAddress>>,
/// The user-agent of the customer's browser
pub user_agent: String,
}
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Serialize)]
pub struct MandateData {
/// A way to update the mandate's payment method details
pub update_mandate_id: Option<String>,
/// A consent from the customer to store the payment method
pub customer_acceptance: Option<CustomerAcceptance>,
/// A way to select the type of mandate used
pub mandate_type: Option<MandateDataType>,
}
#[derive(Default, Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AcceptanceType {
Online,
#[default]
Offline,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MandateDataType {
SingleUse(MandateAmountData),
MultiUse(Option<MandateAmountData>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: common_utils::types::MinorUnit,
pub currency: Currency,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<SecretSerdeValue>,
}
impl MandateAmountData {
pub fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error> {
let date = self.end_date.ok_or_else(missing_field_err(
"mandate_data.mandate_type.{multi_use|single_use}.end_date",
))?;
date_time::format_date(date, format)
.change_context(crate::errors::ConnectorError::DateFormattingFailed)
}
pub fn get_metadata(&self) -> Result<SecretSerdeValue, Error> {
self.metadata.clone().ok_or_else(missing_field_err(
"mandate_data.mandate_type.{multi_use|single_use}.metadata",
))
}
}
| {
"chunk": 0,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-8256841136792189831_0 | clm | mini_chunk | // connector-service/backend/domain_types/src/api.rs
use std::collections::HashSet;
use crate::{
payment_method_data::{DefaultPCIHolder, PaymentMethodData},
router_response_types::RedirectForm,
};
#[derive(Debug, Eq, PartialEq)]
pub struct RedirectionFormData {
pub redirect_form: RedirectForm,
pub payment_method_data: Option<PaymentMethodData<DefaultPCIHolder>>,
pub amount: String,
pub currency: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PaymentLinkAction {
PaymentLinkFormData(PaymentLinkFormData),
PaymentLinkStatus(PaymentLinkStatusData),
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkFormData {
pub js_script: String,
pub css_script: String,
pub sdk_url: url::Url,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkStatusData {
pub js_script: String,
pub css_script: String,
}
#[derive(Debug, Eq, PartialEq)]
pub struct GenericLinks {
pub allowed_domains: HashSet<String>,
pub data: GenericLinksData,
pub locale: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum GenericLinksData {
ExpiredLink(GenericExpiredLinkData),
PaymentMethodCollect(GenericLinkFormData),
PayoutLink(GenericLinkFormData),
PayoutLinkStatus(GenericLinkStatusData),
PaymentMethodCollectStatus(GenericLinkStatusData),
SecurePaymentLink(PaymentLinkFormData),
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericExpiredLinkData {
pub title: String,
pub message: String,
pub theme: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkFormData {
pub js_data: String,
pub css_data: String,
pub sdk_url: url::Url,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkStatusData {
pub js_data: String,
pub css_data: String,
}
| {
"chunk": 0,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_-4703749612792602811_0 | clm | mini_chunk | // connector-service/backend/domain_types/src/connector_flow.rs
#[derive(Debug, Clone)]
pub struct CreateOrder;
#[derive(Debug, Clone)]
pub struct Authorize;
#[derive(Debug, Clone)]
pub struct PSync;
#[derive(Debug, Clone)]
pub struct Void;
#[derive(Debug, Clone)]
pub struct RSync;
#[derive(Debug, Clone)]
pub struct Refund;
#[derive(Debug, Clone)]
pub struct Capture;
#[derive(Debug, Clone)]
pub struct SetupMandate;
#[derive(Debug, Clone)]
pub struct RepeatPayment;
#[derive(Debug, Clone)]
pub struct Accept;
#[derive(Debug, Clone)]
pub struct SubmitEvidence;
#[derive(Debug, Clone)]
pub struct DefendDispute;
#[derive(Debug, Clone)]
pub struct CreateSessionToken;
#[derive(Debug, Clone)]
pub struct CreateAccessToken;
#[derive(Debug, Clone)]
pub struct CreateConnectorCustomer;
#[derive(Debug, Clone)]
pub struct PaymentMethodToken;
#[derive(Debug, Clone)]
pub struct PreAuthenticate;
#[derive(Debug, Clone)]
pub struct Authenticate;
#[derive(Debug, Clone)]
pub struct PostAuthenticate;
#[derive(Debug, Clone)]
pub struct VoidPC;
#[derive(strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum FlowName {
Authorize,
Refund,
Rsync,
Psync,
Void,
VoidPc,
SetupMandate,
RepeatPayment,
Capture,
AcceptDispute,
SubmitEvidence,
DefendDispute,
CreateOrder,
IncomingWebhook,
Dsync,
CreateSessionToken,
CreateAccessToken,
CreateConnectorCustomer,
PaymentMethodToken,
PreAuthenticate,
Authenticate,
PostAuthenticate,
}
| {
"chunk": 0,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_1919096225770533635_0 | clm | mini_chunk | // connector-service/backend/domain_types/src/utils.rs
use std::{
collections::{HashMap, HashSet},
sync::LazyLock,
};
use base64::Engine;
use common_enums::{CurrencyUnit, PaymentMethodType};
use common_utils::{consts, metadata::MaskedMetadata, AmountConvertor, CustomResult, MinorUnit};
use error_stack::{report, Result, ResultExt};
use hyperswitch_masking::ExposeInterface;
use regex::Regex;
use serde::Serialize;
use serde_json::Value;
use time::PrimitiveDateTime;
use crate::{
errors::{self, ApiError, ApplicationErrorResponse, ParsingError},
payment_method_data::{Card, PaymentMethodData, PaymentMethodDataTypes},
router_data::ErrorResponse,
router_response_types::Response,
types::PaymentMethodDataType,
};
pub type Error = error_stack::Report<errors::ConnectorError>;
/// Trait for converting from one foreign type to another
pub trait ForeignTryFrom<F>: Sized {
/// Custom error for conversion failure
type Error;
/// Convert from a foreign type to the current type and return an error if the conversion fails
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
pub trait ForeignFrom<F>: Sized {
/// Convert from a foreign type to the current type and return an error if the conversion fails
fn foreign_from(from: F) -> Self;
}
pub trait ValueExt {
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_value<T>(self, type_name: &'static str) -> Result<T, ParsingError>
where
T: serde::de::DeserializeOwned;
}
impl ValueExt for serde_json::Value {
fn parse_value<T>(self, type_name: &'static str) -> Result<T, ParsingError>
where
T: serde::de::DeserializeOwned,
{
let debug = format!(
"Unable to parse {type_name} from serde_json::Value: {:?}",
&self
);
serde_json::from_value::<T>(self)
.change_context(ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| debug)
}
}
pub trait Encode<'e>
where
Self: 'e + std::fmt::Debug,
{
fn encode_to_value(&'e self) -> Result<serde_json::Value, ParsingError>
where
Self: Serialize;
}
impl<'e, A> Encode<'e> for A
where
Self: 'e + std::fmt::Debug,
{
fn encode_to_value(&'e self) -> Result<serde_json::Value, ParsingError>
where
Self: Serialize,
{
serde_json::to_value(self)
.change_context(ParsingError::EncodeError("json-value"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
}
pub fn handle_json_response_deserialization_failure(
res: Response,
_: &'static str,
) -> CustomResult<ErrorResponse, crate::errors::ConnectorError> {
let response_data = String::from_utf8(res.response.to_vec())
.change_context(crate::errors::ConnectorError::ResponseDeserializationFailed)?;
// check for whether the response is in json format
match serde_json::from_str::<Value>(&response_data) {
// in case of unexpected response but in json format
Ok(_) => Err(crate::errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(_) => Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: Some(response_data.clone()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
}
}
pub fn generate_random_bytes(length: usize) -> Vec<u8> {
// returns random bytes of length n
let mut rng = rand::thread_rng();
(0..length).map(|_| rand::Rng::gen(&mut rng)).collect()
}
pub fn missing_field_err(
message: &'static str,
) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> {
Box::new(move || {
errors::ConnectorError::MissingRequiredField {
field_name: message,
}
.into()
})
}
pub fn construct_not_supported_error_report(
capture_method: common_enums::CaptureMethod,
connector_name: &'static str,
) -> error_stack::Report<errors::ConnectorError> {
errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
| {
"chunk": 0,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_1919096225770533635_1 | clm | mini_chunk | // connector-service/backend/domain_types/src/utils.rs
connector: connector_name,
}
.into()
}
pub fn to_currency_base_unit_with_zero_decimal_check(
amount: i64,
currency: common_enums::Currency,
) -> core::result::Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_with_zero_decimal_check(amount)
.change_context(errors::ConnectorError::RequestEncodingFailed)
}
pub fn get_timestamp_in_milliseconds(datetime: &PrimitiveDateTime) -> i64 {
let utc_datetime = datetime.assume_utc();
utc_datetime.unix_timestamp() * 1000
}
pub fn get_amount_as_string(
currency_unit: &CurrencyUnit,
amount: i64,
currency: common_enums::Currency,
) -> core::result::Result<String, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
CurrencyUnit::Minor => amount.to_string(),
CurrencyUnit::Base => to_currency_base_unit(amount, currency)?,
};
Ok(amount)
}
pub fn base64_decode(
data: String,
) -> core::result::Result<Vec<u8>, error_stack::Report<errors::ConnectorError>> {
base64::engine::general_purpose::STANDARD
.decode(data)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
}
pub fn to_currency_base_unit(
amount: i64,
currency: common_enums::Currency,
) -> core::result::Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit(amount)
.change_context(errors::ConnectorError::ParsingFailed)
}
pub const SELECTED_PAYMENT_METHOD: &str = "Selected payment method";
pub fn get_unimplemented_payment_method_error_message(connector: &str) -> String {
format!("{SELECTED_PAYMENT_METHOD} through {connector}")
}
pub fn get_header_key_value<'a>(
key: &str,
headers: &'a actix_web::http::header::HeaderMap,
) -> CustomResult<&'a str, errors::ConnectorError> {
get_header_field(headers.get(key))
}
pub fn get_http_header<'a>(
key: &str,
headers: &'a http::HeaderMap,
) -> CustomResult<&'a str, errors::ConnectorError> {
get_header_field(headers.get(key))
}
fn get_header_field(
field: Option<&http::HeaderValue>,
) -> CustomResult<&str, errors::ConnectorError> {
field
.map(|header_value| {
header_value
.to_str()
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
})
.ok_or(report!(
errors::ConnectorError::WebhookSourceVerificationFailed
))?
}
pub fn is_payment_failure(status: common_enums::AttemptStatus) -> bool {
match status {
common_enums::AttemptStatus::AuthenticationFailed
| common_enums::AttemptStatus::AuthorizationFailed
| common_enums::AttemptStatus::CaptureFailed
| common_enums::AttemptStatus::VoidFailed
| common_enums::AttemptStatus::Failure => true,
common_enums::AttemptStatus::Started
| common_enums::AttemptStatus::RouterDeclined
| common_enums::AttemptStatus::AuthenticationPending
| common_enums::AttemptStatus::AuthenticationSuccessful
| common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::Charged
| common_enums::AttemptStatus::Authorizing
| common_enums::AttemptStatus::CodInitiated
| common_enums::AttemptStatus::Voided
| common_enums::AttemptStatus::VoidedPostCapture
| common_enums::AttemptStatus::VoidInitiated
| common_enums::AttemptStatus::VoidPostCaptureInitiated
| common_enums::AttemptStatus::CaptureInitiated
| common_enums::AttemptStatus::AutoRefunded
| common_enums::AttemptStatus::PartialCharged
| common_enums::AttemptStatus::PartialChargedAndChargeable
| common_enums::AttemptStatus::Unresolved
| common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::PaymentMethodAwaited
| common_enums::AttemptStatus::ConfirmationAwaited
| common_enums::AttemptStatus::DeviceDataCollectionPending
| common_enums::AttemptStatus::IntegrityFailure
| common_enums::AttemptStatus::Unknown => false,
}
}
pub fn get_card_details<T>(
payment_method_data: PaymentMethodData<T>,
connector_name: &'static str,
) -> Result<Card<T>, errors::ConnectorError>
where
T: PaymentMethodDataTypes,
{
match payment_method_data {
| {
"chunk": 1,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_1919096225770533635_2 | clm | mini_chunk | // connector-service/backend/domain_types/src/utils.rs
PaymentMethodData::Card(details) => Ok(details),
_ => Err(errors::ConnectorError::NotSupported {
message: SELECTED_PAYMENT_METHOD.to_string(),
connector: connector_name,
})?,
}
}
pub fn is_mandate_supported<T>(
selected_pmd: PaymentMethodData<T>,
payment_method_type: Option<PaymentMethodType>,
mandate_implemented_pmds: HashSet<PaymentMethodDataType>,
connector: &'static str,
) -> core::result::Result<(), Error>
where
T: PaymentMethodDataTypes,
{
if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) {
Ok(())
} else {
match payment_method_type {
Some(pm_type) => Err(errors::ConnectorError::NotSupported {
message: format!("{pm_type} mandate payment"),
connector,
}
.into()),
None => Err(errors::ConnectorError::NotSupported {
message: " mandate payment".to_string(),
connector,
}
.into()),
}
}
}
pub fn convert_amount<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: MinorUnit,
currency: common_enums::Currency,
) -> core::result::Result<T, Error> {
amount_convertor
.convert(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
pub fn convert_back_amount_to_minor_units<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: common_enums::Currency,
) -> core::result::Result<MinorUnit, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert_back(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
#[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)]
pub enum CardIssuer {
AmericanExpress,
Master,
Maestro,
Visa,
Discover,
DinersClub,
JCB,
CarteBlanche,
CartesBancaires,
}
// Helper function for extracting connector request reference ID
pub(crate) fn extract_connector_request_reference_id(
identifier: &Option<grpc_api_types::payments::Identifier>,
) -> String {
identifier
.as_ref()
.and_then(|id| id.id_type.as_ref())
.and_then(|id_type| match id_type {
grpc_api_types::payments::identifier::IdType::Id(id) => Some(id.clone()),
_ => None,
})
.unwrap_or_default()
}
// Helper function for extracting connector request reference ID
pub(crate) fn extract_optional_connector_request_reference_id(
identifier: &Option<grpc_api_types::payments::Identifier>,
) -> Option<String> {
identifier
.as_ref()
.and_then(|id| id.id_type.as_ref())
.and_then(|id_type| match id_type {
grpc_api_types::payments::identifier::IdType::Id(id) => Some(id.clone()),
_ => None,
})
}
#[track_caller]
pub fn get_card_issuer(card_number: &str) -> core::result::Result<CardIssuer, Error> {
for (k, v) in CARD_REGEX.iter() {
let regex: Regex = v
.clone()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if regex.is_match(card_number) {
return Ok(*k);
}
}
Err(error_stack::Report::new(
errors::ConnectorError::NotImplemented("Card Type".into()),
))
}
static CARD_REGEX: LazyLock<HashMap<CardIssuer, core::result::Result<Regex, regex::Error>>> =
LazyLock::new(|| {
let mut map = HashMap::new();
// Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841
// [#379]: Determine card issuer from card BIN number
map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$"));
map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$"));
map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$"));
map.insert(CardIssuer::Discover, Regex::new(r"^65[4-9][0-9]{13}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$"));
map.insert(
CardIssuer::Maestro,
Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"),
);
map.insert(
CardIssuer::DinersClub,
Regex::new(r"^3(?:0[0-5]|[68][0-9])[0-9]{11}$"),
);
| {
"chunk": 2,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_domain_types_1919096225770533635_3 | clm | mini_chunk | // connector-service/backend/domain_types/src/utils.rs
map.insert(
CardIssuer::JCB,
Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"),
);
map.insert(CardIssuer::CarteBlanche, Regex::new(r"^389[0-9]{11}$"));
map
});
/// Helper function for extracting merchant ID from metadata
pub fn extract_merchant_id_from_metadata(
metadata: &MaskedMetadata,
) -> Result<common_utils::id_type::MerchantId, ApplicationErrorResponse> {
let merchant_id_secret = metadata
.get(common_utils::consts::X_MERCHANT_ID)
.ok_or_else(|| {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_MERCHANT_ID".to_owned(),
error_identifier: 400,
error_message: "Missing merchant ID in request metadata".to_owned(),
error_object: None,
})
})?;
let merchant_id_str = merchant_id_secret.expose();
Ok(merchant_id_str
.parse::<common_utils::id_type::MerchantId>()
.map_err(|e| {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_MERCHANT_ID".to_owned(),
error_identifier: 400,
error_message: format!("Failed to parse merchant ID from header: {e}"),
error_object: None,
})
})?)
}
/// Convert US state names to their 2-letter abbreviations
pub fn convert_us_state_to_code(state: &str) -> String {
// If already 2 characters, assume it's already an abbreviation
if state.len() == 2 {
return state.to_uppercase();
}
// Convert full state names to abbreviations (case-insensitive)
match state.to_lowercase().trim() {
"alabama" => "AL".to_string(),
"alaska" => "AK".to_string(),
"american samoa" => "AS".to_string(),
"arizona" => "AZ".to_string(),
"arkansas" => "AR".to_string(),
"california" => "CA".to_string(),
"colorado" => "CO".to_string(),
"connecticut" => "CT".to_string(),
"delaware" => "DE".to_string(),
"district of columbia" | "columbia" => "DC".to_string(),
"federated states of micronesia" | "micronesia" => "FM".to_string(),
"florida" => "FL".to_string(),
"georgia" => "GA".to_string(),
"guam" => "GU".to_string(),
"hawaii" => "HI".to_string(),
"idaho" => "ID".to_string(),
"illinois" => "IL".to_string(),
"indiana" => "IN".to_string(),
"iowa" => "IA".to_string(),
"kansas" => "KS".to_string(),
"kentucky" => "KY".to_string(),
"louisiana" => "LA".to_string(),
"maine" => "ME".to_string(),
"marshall islands" => "MH".to_string(),
"maryland" => "MD".to_string(),
"massachusetts" => "MA".to_string(),
"michigan" => "MI".to_string(),
"minnesota" => "MN".to_string(),
"mississippi" => "MS".to_string(),
"missouri" => "MO".to_string(),
"montana" => "MT".to_string(),
"nebraska" => "NE".to_string(),
"nevada" => "NV".to_string(),
"new hampshire" => "NH".to_string(),
"new jersey" => "NJ".to_string(),
"new mexico" => "NM".to_string(),
"new york" => "NY".to_string(),
"north carolina" => "NC".to_string(),
"north dakota" => "ND".to_string(),
"northern mariana islands" => "MP".to_string(),
"ohio" => "OH".to_string(),
"oklahoma" => "OK".to_string(),
"oregon" => "OR".to_string(),
"palau" => "PW".to_string(),
"pennsylvania" => "PA".to_string(),
"puerto rico" => "PR".to_string(),
"rhode island" => "RI".to_string(),
"south carolina" => "SC".to_string(),
"south dakota" => "SD".to_string(),
"tennessee" => "TN".to_string(),
"texas" => "TX".to_string(),
"utah" => "UT".to_string(),
"vermont" => "VT".to_string(),
"virgin islands" => "VI".to_string(),
"virginia" => "VA".to_string(),
"washington" => "WA".to_string(),
"west virginia" => "WV".to_string(),
"wisconsin" => "WI".to_string(),
"wyoming" => "WY".to_string(),
// If no match found, return original (might be international or invalid)
_ => state.to_string(),
}
}
| {
"chunk": 3,
"crate": "domain_types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-api-types_-3244079078714223733_0 | clm | mini_chunk | // connector-service/backend/grpc-api-types/build.rs
use std::{env, path::PathBuf};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let out_dir = PathBuf::from(env::var("OUT_DIR")?);
// Create the bridge generator with string enums
let bridge_generator = g2h::BridgeGenerator::with_tonic_build()
.with_string_enums()
.file_descriptor_set_path(out_dir.join("connector_service_descriptor.bin"));
// Create a basic prost config and add your extern_path configuration
let mut config = prost_build::Config::new();
config.extern_path(".ucs.v2.CardNumberType", "::cards::CardNumber");
config.extern_path(
".ucs.v2.SecretString",
"::hyperswitch_masking::Secret<String>",
);
// Use compile_protos_with_config which handles everything internally
// including string enum support, serde derives, and descriptor set writing
bridge_generator.compile_protos_with_config(
config,
&[
"proto/services.proto",
"proto/health_check.proto",
"proto/payment.proto",
"proto/payment_methods.proto",
],
&["proto"],
)?;
// prost_build::Config::new()
// .service_generator(Box::new(web_generator))
// .file_descriptor_set_path(out_dir.join("connector_service_descriptor.bin"))
// .type_attribute(".", "#[derive(serde::Serialize, serde::Deserialize)]")
// .type_attribute(".", "#[allow(clippy::large_enum_variant)]")
// .compile_protos(
// &[
// "proto/services.proto",
// "proto/health_check.proto",
// "proto/payment.proto",
// "proto/payment_methods.proto",
// ],
// &["proto"],
// )?;
Ok(())
}
| {
"chunk": 0,
"crate": "grpc-api-types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-api-types_3661992858984206027_0 | clm | mini_chunk | // connector-service/backend/grpc-api-types/src/lib.rs
#![allow(clippy::large_enum_variant)]
#![allow(clippy::uninlined_format_args)]
pub const FILE_DESCRIPTOR_SET: &[u8] =
tonic::include_file_descriptor_set!("connector_service_descriptor");
pub mod payments {
tonic::include_proto!("ucs.v2");
}
pub mod health_check {
tonic::include_proto!("grpc.health.v1");
}
| {
"chunk": 0,
"crate": "grpc-api-types",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-4343738646407124784_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/novalnet_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, Address, AuthenticationType, CaptureMethod,
CardDetails, CardPaymentMethodType, Currency, Identifier, PaymentAddress, PaymentMethod,
PaymentServiceAuthorizeRequest, PaymentStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
use uuid::Uuid;
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to generate a unique ID using UUID
fn generate_unique_id(prefix: &str) -> String {
format!("{}_{}", prefix, Uuid::new_v4())
}
// Constants for Novalnet connector
const CONNECTOR_NAME: &str = "novalnet";
const AUTH_TYPE: &str = "signature-key";
const MERCHANT_ID: &str = "merchant_1234";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4111111111111111"; // Valid test card for Novalnet
const TEST_CARD_EXP_MONTH: &str = "12";
const TEST_CARD_EXP_YEAR: &str = "2025";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
fn add_novalnet_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load novalnet credentials");
let (api_key, key1, api_secret) = match auth {
domain_types::router_data::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => (api_key.expose(), key1.expose(), api_secret.expose()),
_ => panic!("Expected SignatureKey auth type for novalnet"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-api-secret",
api_secret.parse().expect("Failed to parse x-api-secret"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
let address = PaymentAddress {
billing_address: Some(Address {
first_name: Some("John".to_string().into()),
last_name: Some("Doe".to_string().into()),
email: Some("test@test.com".to_string().into()),
..Default::default()
}),
shipping_address: None,
};
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-4343738646407124784_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/novalnet_payment_flows_test.rs
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some("https://hyperswitch.io/".to_string()),
webhook_url: Some("https://hyperswitch.io/".to_string()),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(address),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("novalnet_test"))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_novalnet_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AuthenticationPending state"
);
});
}
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7564384104945033011_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/stripe_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
use hyperswitch_masking::{ExposeInterface, Secret};
mod common;
mod utils;
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundResponse, RefundServiceGetRequest,
RefundStatus,
},
};
use tonic::{transport::Channel, Request};
use uuid::Uuid;
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to generate a unique ID using UUID
fn generate_unique_id(prefix: &str) -> String {
format!("{}_{}", prefix, Uuid::new_v4())
}
// Constants for Stripe connector
const CONNECTOR_NAME: &str = "stripe";
const AUTH_TYPE: &str = "header-key";
const MERCHANT_ID: &str = "merchant_1234";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4111111111111111"; // Valid test card for Stripe
const TEST_CARD_EXP_MONTH: &str = "12";
const TEST_CARD_EXP_YEAR: &str = "2025";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
fn add_stripe_metadata<T>(request: &mut Request<T>) {
// Get API credentials using the common credential loading utility
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load Stripe credentials");
let api_key = match auth {
domain_types::router_data::ConnectorAuthType::HeaderKey { api_key } => api_key.expose(),
_ => panic!("Expected HeaderKey auth type for Stripe"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-connector-request-reference-id",
format!("conn_ref_{}", get_timestamp())
.parse()
.expect("Failed to parse x-connector-request-reference-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to extract connector Refund ID from response
fn extract_refund_id(response: &RefundResponse) -> &String {
&response.refund_id
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7564384104945033011_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/stripe_payment_flows_test.rs
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
webhook_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress::default()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("stripe_test"))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
connector_customer_id: Some("cus_TE8065JzRWlLQf".to_string()),
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("stripe_sync"))),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
request_ref_id: None,
..Default::default()
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("stripe_void"))),
}),
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", generate_unique_id("test")),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
webhook_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
..Default::default()
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7564384104945033011_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/stripe_payment_flows_test.rs
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
request_ref_id: None,
..Default::default()
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_stripe_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_stripe_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in Authorized state"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request - make sure they include the terminal_id
let mut capture_grpc_request = Request::new(capture_request);
add_stripe_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
});
}
// Test payment sync with auto capture
#[tokio::test]
async fn test_payment_sync_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_stripe_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_stripe_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7564384104945033011_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/stripe_payment_flows_test.rs
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
assert!(
sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
});
}
// Test payment void
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture to void
let auth_request = create_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_stripe_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state before voiding"
);
// Create void request with a unique reference ID
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_stripe_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC void_payment call failed")
.into_inner();
// Verify the void response
assert!(
void_response.transaction_id.is_some(),
"Transaction ID should be present in void response"
);
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
// Verify the payment status with a sync operation
let sync_request = create_payment_sync_request(&transaction_id);
let mut sync_grpc_request = Request::new(sync_request);
add_stripe_metadata(&mut sync_grpc_request);
// Send the sync request to verify void status
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the payment is properly voided
assert!(
sync_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void sync"
);
});
}
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_stripe_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_stripe_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in RefundSuccess state"
);
});
}
#[tokio::test]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7564384104945033011_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/stripe_payment_flows_test.rs
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_stripe_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_stripe_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in RefundSuccess state"
);
let refund_id = extract_refund_id(&refund_response);
// Create refund sync request
let refund_sync_request = create_refund_sync_request(&transaction_id, refund_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_stripe_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request
let refund_sync_response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund sync call failed")
.into_inner();
// Verify the refund sync response
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund Sync should be in RefundSuccess state"
);
});
});
}
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-9211585717375662373_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/test_amount_conversion.rs
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use common_enums::Currency;
use common_utils::{
types::{MinorUnit, StringMajorUnitForConnector},
AmountConvertor,
};
#[test]
fn test_amount_conversion_with_currency_validation() {
let converter = StringMajorUnitForConnector;
let amount = MinorUnit::new(12345);
// Test zero decimal currency (JPY)
let result = converter.convert(amount, Currency::JPY);
assert!(result.is_ok(), "JPY conversion should succeed");
let converted = result.unwrap();
assert_eq!(converted.get_amount_as_string(), "12345");
// Test two decimal currency (USD)
let result = converter.convert(amount, Currency::USD);
assert!(result.is_ok(), "USD conversion should succeed");
let converted = result.unwrap();
assert_eq!(converted.get_amount_as_string(), "123.45");
// Test three decimal currency (BHD)
let result = converter.convert(amount, Currency::BHD);
assert!(result.is_ok(), "BHD conversion should succeed");
let converted = result.unwrap();
assert_eq!(converted.get_amount_as_string(), "12.345");
// Test four decimal currency (CLF)
let result = converter.convert(amount, Currency::CLF);
assert!(result.is_ok(), "CLF conversion should succeed");
let converted = result.unwrap();
assert_eq!(converted.get_amount_as_string(), "1.2345");
}
#[test]
fn test_currency_validation_errors_propagate() {
// This test verifies that if we had an unsupported currency,
// the error would propagate through the amount conversion system.
// Since all current currencies are supported, we'll test by verifying
// that the currency validation is being called.
let converter = StringMajorUnitForConnector;
let amount = MinorUnit::new(1000);
// Test that various currencies work
let currencies = vec![
Currency::USD,
Currency::EUR,
Currency::GBP,
Currency::JPY,
Currency::BHD,
Currency::CLF,
Currency::KRW,
Currency::VND,
];
let mut failed_currencies = Vec::new();
for currency in currencies {
let result = converter.convert(amount, currency);
if result.is_err() {
failed_currencies.push(currency);
}
}
assert!(
failed_currencies.is_empty(),
"The following currencies failed conversion: {failed_currencies:?}"
);
}
#[test]
fn test_amount_conversion_precision() {
let converter = StringMajorUnitForConnector;
// Test with different amounts to verify precision
let test_cases = vec![
(MinorUnit::new(1), Currency::USD, "0.01"),
(MinorUnit::new(100), Currency::USD, "1.00"),
(MinorUnit::new(12345), Currency::USD, "123.45"),
(MinorUnit::new(1), Currency::JPY, "1"),
(MinorUnit::new(1000), Currency::JPY, "1000"),
(MinorUnit::new(1234), Currency::BHD, "1.234"),
(MinorUnit::new(12345), Currency::BHD, "12.345"),
(MinorUnit::new(1234), Currency::CLF, "0.1234"),
(MinorUnit::new(12345), Currency::CLF, "1.2345"),
];
let mut failed_test_cases = Vec::new();
for (amount, currency, expected) in test_cases {
let result = converter.convert(amount, currency);
match result {
Ok(converted) => {
let actual = converted.get_amount_as_string();
if actual != expected {
failed_test_cases.push((amount, currency, expected, actual));
}
}
Err(_) => {
failed_test_cases.push((amount, currency, expected, "ERROR".to_string()));
}
}
}
assert!(
failed_test_cases.is_empty(),
"The following test cases failed: {failed_test_cases:?}"
);
}
}
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-6689475451466318163_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/xendit_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentStatus, RefundResponse, RefundServiceGetRequest, RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Constants for Xendit connector - Updated to match provided JSON payload
const CONNECTOR_NAME: &str = "xendit";
const MERCHANT_ID: &str = "merchant_1753672298";
const CONNECTOR_CUSTOMER_ID: &str = "abc123";
// Test card data - Updated to match new JSON payload
const TEST_AMOUNT: i64 = 10000000000; // 10 trillion from new payload
const TEST_MINOR_AMOUNT: i64 = 10000000000; // Minor amount from new payload
const TEST_CARD_NUMBER: &str = "4111111111111111"; // Valid test card for Xendit
const TEST_CARD_EXP_MONTH: &str = "10";
const TEST_CARD_EXP_YEAR: &str = "2027"; // Full year format
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "joseph Doe";
const TEST_EMAIL: &str = "test@t.com";
const TEST_REQUEST_REF_ID: &str = "12345678_123";
fn add_xendit_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load xendit credentials");
let api_key = match auth {
domain_types::router_data::ConnectorAuthType::HeaderKey { api_key } => api_key.expose(),
_ => panic!("Expected HeaderKey auth type for xendit"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"header-key".parse().expect("Failed to parse x-auth"),
);
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to extract connector Refund ID from response
fn extract_refund_id(response: &RefundResponse) -> &String {
&response.refund_id
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-6689475451466318163_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/xendit_payment_flows_test.rs
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_MINOR_AMOUNT,
currency: i32::from(Currency::Idr),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some(
"http://localhost:8080/payments/pay_h6dmtWPxiJ4jgtFpk8JK/merchant_1753672298/redirect/response/novalnet".to_string(),
),
webhook_url: Some(
"http://localhost:8080/webhooks/merchant_1753672298/mca_8rIwEeXmFvrIA59fMH75".to_string(),
),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress::default()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(TEST_REQUEST_REF_ID.to_string())),
}),
enrolled_for_3ds: true,
request_incremental_authorization: false,
customer_id: Some(CONNECTOR_CUSTOMER_ID.to_string()),
// browser_info: TODO - BrowserInfo type not available in grpc_api_types
capture_method: Some(i32::from(capture_method)),
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("xendit_sync_{}", get_timestamp()))),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Idr),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Idr),
multiple_capture_data: None,
request_ref_id: None,
..Default::default()
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Idr),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
webhook_url: None,
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
..Default::default()
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
request_ref_id: None,
browser_info: None,
refund_metadata: std::collections::HashMap::new(),
state: None,
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-6689475451466318163_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/xendit_payment_flows_test.rs
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_xendit_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending)
|| response.status == i32::from(PaymentStatus::Pending)
|| response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AuthenticationPending, Pending, or Charged state. Got status: {}",
response.status
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_xendit_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::AuthenticationPending)
|| auth_response.status == i32::from(PaymentStatus::Pending)
|| auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AuthenticationPending, Pending, or Authorized state. Got status: {}",
auth_response.status
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Add delay of 15 seconds
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request - make sure they include the terminal_id
let mut capture_grpc_request = Request::new(capture_request);
add_xendit_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
});
}
// Test payment sync with auto capture
#[tokio::test]
async fn test_payment_sync_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_xendit_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
// Add delay of 10 seconds
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_xendit_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-6689475451466318163_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/xendit_payment_flows_test.rs
assert!(
sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
});
}
// Test refund flow - handles both success and error cases
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_xendit_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending)
|| response.status == i32::from(PaymentStatus::Pending)
|| response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AuthenticationPending or Pending state"
);
// Wait a bit longer to ensure the payment is fully processed
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_xendit_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in RefundSuccess state"
);
});
}
// Test refund sync flow - runs as a separate test since refund + sync is complex
#[tokio::test]
#[ignore] // Service not implemented on server side - Status code: Unimplemented
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_xendit_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending)
|| response.status == i32::from(PaymentStatus::Pending)
|| response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AuthenticationPending or Pending state"
);
// Wait a bit longer to ensure the payment is fully processed
tokio::time::sleep(tokio::time::Duration::from_secs(15)).await;
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_xendit_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in RefundSuccess state"
);
let refund_id = extract_refund_id(&refund_response);
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-6689475451466318163_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/xendit_payment_flows_test.rs
// Wait a bit longer to ensure the refund is fully processed
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// Create refund sync request
let refund_sync_request = create_refund_sync_request(&transaction_id, refund_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_xendit_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request
let refund_sync_response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund sync call failed")
.into_inner();
// Verify the refund sync response
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund Sync should be in RefundSuccess state"
);
});
});
}
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-7945249832950166259_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/mifinity_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
use hyperswitch_masking::{ExposeInterface, Secret};
mod common;
mod utils;
use std::time::{SystemTime, UNIX_EPOCH};
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
identifier::IdType, payment_method, payment_service_client::PaymentServiceClient,
wallet_payment_method_type, AuthenticationType, CaptureMethod, Currency, Identifier,
MifinityWallet, PaymentMethod, PaymentServiceAuthorizeRequest,
PaymentServiceAuthorizeResponse, PaymentServiceGetRequest, PaymentStatus,
WalletPaymentMethodType,
},
};
use tonic::{transport::Channel, Request};
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Constants for Mifinity connector
const CONNECTOR_NAME: &str = "mifinity";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_DESTINATION_ACCOUNT_NUMBER: &str = "5001000001223369"; // Valid test destination account number for Mifinity
const TEST_BRAND_ID: &str = "001";
const TEST_DATE_OF_BIRTH: &str = "2001-10-16";
const TEST_EMAIL: &str = "customer@example.com";
fn add_mifinity_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load mifinity credentials");
let api_key = match auth {
domain_types::router_data::ConnectorAuthType::HeaderKey { api_key } => api_key.expose(),
_ => panic!("Expected HeaderKey auth type for mifinity"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"header-key".parse().expect("Failed to parse x-auth"),
);
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
// Add merchant ID which is required by the server
request.metadata_mut().append(
"x-merchant-id",
"12abc123-f8a3-99b8-9ef8-b31180358hh4"
.parse()
.expect("Failed to parse x-merchant-id"),
);
// Add tenant ID which is required by the server
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
// Add request ID which is required by the server
request.metadata_mut().append(
"x-request-id",
format!("mifinity_req_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
let wallet_details = wallet_payment_method_type::WalletType::Mifinity(MifinityWallet {
date_of_birth: Some(Secret::new(TEST_DATE_OF_BIRTH.to_string())),
language_preference: Some("en-US".to_string()),
});
// Create connector metadata JSON string
let connector_meta_data = format!(
"{{\"brand_id\":\"{TEST_BRAND_ID}\",\"destination_account_number\":\"{TEST_DESTINATION_ACCOUNT_NUMBER}\"}}"
);
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Wallet(
WalletPaymentMethodType {
wallet_type: Some(wallet_details),
},
)),
}),
return_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
email: Some(TEST_EMAIL.to_string().into()),
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-7945249832950166259_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/mifinity_payment_flows_test.rs
address: Some(grpc_api_types::payments::PaymentAddress {
shipping_address: Some(grpc_api_types::payments::Address::default()),
billing_address: Some(grpc_api_types::payments::Address {
first_name: Some("joseph".to_string().into()),
last_name: Some("Doe".to_string().into()),
phone_number: Some("8056594427".to_string().into()),
phone_country_code: Some("+91".to_string()),
email: Some("swangi@gmail.com".to_string().into()),
line1: Some("1467".to_string().into()),
line2: Some("Harrison Street".to_string().into()),
line3: Some("Harrison Street".to_string().into()),
city: Some("San Fransico".to_string().into()),
state: Some("California".to_string().into()),
zip_code: Some("94122".to_string().into()),
country_alpha2_code: Some(grpc_api_types::payments::CountryAlpha2::De.into()),
}),
}),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("mifinity_test_{}", get_timestamp()))),
}),
customer_id: Some("Test_customer".to_string()),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
metadata: {
let mut metadata = std::collections::HashMap::new();
metadata.insert("connector_meta_data".to_string(), connector_meta_data);
metadata
},
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
state: None,
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_mifinity_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending)
|| response.status == i32::from(PaymentStatus::Pending),
"Payment should be in AuthenticationPending or Pending state"
);
});
}
// Test payment sync with auto capture
#[tokio::test]
async fn test_payment_sync_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 2 seconds
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_mifinity_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-7945249832950166259_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/mifinity_payment_flows_test.rs
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_mifinity_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
assert!(
sync_response.status == i32::from(PaymentStatus::AuthenticationPending)
|| sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AuthenticationPending or Charged state"
);
});
}
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8438814131594319128_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/fiuu_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundResponse, RefundServiceGetRequest,
RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
use uuid::Uuid;
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to generate a unique ID using UUID
fn generate_unique_id(prefix: &str) -> String {
format!("{}_{}", prefix, Uuid::new_v4())
}
// Constants for Fiuu connector
const CONNECTOR_NAME: &str = "fiuu";
const AUTH_TYPE: &str = "signature-key";
const MERCHANT_ID: &str = "merchant_1234";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4111111111111111"; // Valid test card for Fiuu
const TEST_CARD_EXP_MONTH: &str = "12";
const TEST_CARD_EXP_YEAR: &str = "2025";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
fn add_fiuu_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load fiuu credentials");
let (api_key, key1, api_secret) = match auth {
domain_types::router_data::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => (api_key.expose(), key1.expose(), api_secret.expose()),
_ => panic!("Expected SignatureKey auth type for fiuu"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-api-secret",
api_secret.parse().expect("Failed to parse x-api-secret"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to extract connector Refund ID from response
fn extract_refund_id(response: &RefundResponse) -> &String {
&response.refund_id
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8438814131594319128_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/fiuu_payment_flows_test.rs
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Myr),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
webhook_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress::default()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("fiuu_test"))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("fiuu_sync"))),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Myr),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Myr),
multiple_capture_data: None,
request_ref_id: None,
..Default::default()
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("fiuu_void"))),
}),
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", generate_unique_id("test")),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Myr),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
webhook_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
..Default::default()
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
request_ref_id: None,
browser_info: None,
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8438814131594319128_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/fiuu_payment_flows_test.rs
refund_metadata: std::collections::HashMap::new(),
state: None,
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_fiuu_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_fiuu_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in Authorized state"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Add delay of 15 seconds
tokio::time::sleep(std::time::Duration::from_secs(15)).await;
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request - make sure they include the terminal_id
let mut capture_grpc_request = Request::new(capture_request);
add_fiuu_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
});
}
// Test payment sync with auto capture
#[tokio::test]
async fn test_payment_sync_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_fiuu_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
// Add delay of 10 seconds
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_fiuu_metadata(&mut sync_grpc_request);
// Send the sync request
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8438814131594319128_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/fiuu_payment_flows_test.rs
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
assert!(
sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
});
}
// Test refund flow - handles both success and error cases
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_fiuu_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
// Wait a bit longer to ensure the payment is fully processed
tokio::time::sleep(tokio::time::Duration::from_secs(12)).await;
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_fiuu_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in RefundPending state"
);
});
}
// Test refund sync flow - runs as a separate test since refund + sync is complex
#[tokio::test]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_fiuu_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_fiuu_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in RefundPending state"
);
let refund_id = extract_refund_id(&refund_response);
// Wait a bit longer to ensure the refund is fully processed
std::thread::sleep(std::time::Duration::from_secs(30));
// Create refund sync request
let refund_sync_request = create_refund_sync_request(&transaction_id, refund_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8438814131594319128_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/fiuu_payment_flows_test.rs
add_fiuu_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request
let refund_sync_response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund sync call failed")
.into_inner();
let is_valid_status = refund_sync_response.status
== i32::from(RefundStatus::RefundPending)
|| refund_sync_response.status == i32::from(RefundStatus::RefundSuccess);
assert!(
is_valid_status,
"Refund Sync should be in RefundPending or RefundSuccess state, got: {:?}",
refund_sync_response.status
);
});
});
}
// Test payment void
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture to void
let auth_request = create_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_fiuu_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state before voiding"
);
// Wait a bit longer to ensure the payment is fully processed
std::thread::sleep(std::time::Duration::from_secs(12));
// Create void request with a unique reference ID
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_fiuu_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC void_payment call failed")
.into_inner();
// Verify the void response
assert!(
void_response.transaction_id.is_some(),
"Transaction ID should be present in void response"
);
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
// Verify the payment status with a sync operation
let sync_request = create_payment_sync_request(&transaction_id);
let mut sync_grpc_request = Request::new(sync_request);
add_fiuu_metadata(&mut sync_grpc_request);
// Send the sync request to verify void status
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the payment is properly voided
assert!(
sync_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void sync"
);
});
}
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_996943186016164794_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/helcim_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
use hyperswitch_masking::{ExposeInterface, Secret};
mod common;
mod utils;
use std::{
collections::HashMap,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, Address, AuthenticationType,
BrowserInformation, CaptureMethod, CardDetails, CardPaymentMethodType, CountryAlpha2,
Currency, Identifier, PaymentAddress, PaymentMethod, PaymentServiceAuthorizeRequest,
PaymentServiceAuthorizeResponse, PaymentServiceCaptureRequest, PaymentServiceGetRequest,
PaymentServiceVoidRequest, PaymentStatus,
},
};
use tonic::{transport::Channel, Request};
// Constants for Helcim connector
const CONNECTOR_NAME: &str = "helcim";
const AUTH_TYPE: &str = "header-key";
// Test card data
const TEST_CARD_NUMBER: &str = "5413330089099130"; // Valid test card for Helcim
const TEST_CARD_EXP_MONTH: &str = "01";
const TEST_CARD_EXP_YEAR: &str = "2027";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "joseph Doe";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to generate unique test amounts to avoid duplicate transaction detection
fn get_unique_amount() -> i64 {
// Use timestamp to create unique amounts between 1000-9999 cents ($10-$99.99)
let timestamp = get_timestamp();
1000 + i64::try_from(timestamp % 9000).unwrap_or(0)
}
// Helper function to get current timestamp with microseconds for uniqueness
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_micros()
.try_into()
.unwrap_or(0)
}
// Helper function to add Helcim metadata headers to a request
fn add_helcim_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load helcim credentials");
let api_key = match auth {
domain_types::router_data::ConnectorAuthType::HeaderKey { api_key } => api_key.expose(),
_ => panic!("Expected HeaderKey auth type for helcim"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
// Add merchant ID which is required by the server
request.metadata_mut().append(
"x-merchant-id",
"12abc123-f8a3-99b8-9ef8-b31180358hh4"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
// Add request ID which is required by the server
request.metadata_mut().append(
"x-request-id",
format!("helcim_req_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to extract connector transaction ID from authorize response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match &id.id_type {
Some(IdType::Id(id)) => id.clone(),
Some(IdType::EncodedData(id)) => id.clone(),
Some(IdType::NoResponseIdMarker(_)) => {
// For manual capture, extract the transaction ID from connector metadata
if let Some(preauth_id) = response.connector_metadata.get("preauth_transaction_id")
{
return preauth_id.clone();
}
panic!(
"NoResponseIdMarker found but no preauth_transaction_id in connector metadata"
)
}
None => panic!("ID type is None in transaction_id"),
},
None => panic!("Transaction ID is None"),
}
}
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_996943186016164794_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/helcim_payment_flows_test.rs
// Helper function to extract connector transaction ID from void response
fn extract_void_transaction_id(
response: &grpc_api_types::payments::PaymentServiceVoidResponse,
) -> String {
match &response.transaction_id {
Some(id) => match &id.id_type {
Some(IdType::Id(id)) => id.clone(),
Some(IdType::EncodedData(id)) => id.clone(),
Some(_) => panic!("Unexpected ID type in transaction_id"),
None => panic!("ID type is None in transaction_id"),
},
None => panic!("Transaction ID is None"),
}
}
// Helper function to extract connector request ref ID from response
fn extract_request_ref_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.response_ref_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector response_ref_id"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to create browser info with IP address (required for Helcim)
fn create_test_browser_info() -> BrowserInformation {
BrowserInformation {
ip_address: Some("192.168.1.1".to_string()),
user_agent: Some(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36".to_string(),
),
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(),
),
language: Some("en-US".to_string()),
color_depth: Some(24),
screen_height: Some(1080),
screen_width: Some(1920),
time_zone_offset_minutes: Some(-300), // EST timezone offset
java_enabled: Some(false),
java_script_enabled: Some(true),
referer: Some("https://example.com".to_string()),
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
}
}
// Helper function to create a proper billing address with unique data
fn create_test_billing_address() -> PaymentAddress {
let timestamp = get_timestamp();
let unique_suffix = timestamp % 10000;
PaymentAddress {
shipping_address: Some(Address::default()),
billing_address: Some(Address {
first_name: Some("John".to_string().into()),
last_name: Some("Doe".to_string().into()),
phone_number: Some(format!("123456{unique_suffix:04}").into()),
phone_country_code: Some("+1".to_string()),
email: Some(format!("customer{unique_suffix}@example.com").into()),
line1: Some(format!("{} Main St", 100 + unique_suffix).into()),
line2: Some("Apt 4B".to_string().into()),
line3: None,
city: Some("New York".to_string().into()),
state: Some("NY".to_string().into()),
zip_code: Some(format!("{:05}", 10001 + (unique_suffix % 1000)).into()),
country_alpha2_code: Some(CountryAlpha2::Us.into()),
}),
}
}
// Helper function to create a payment authorize request
fn create_payment_authorize_request(
capture_method: CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
create_payment_authorize_request_with_amount(capture_method, get_unique_amount())
}
// Helper function to create a payment authorize request with custom amount
fn create_payment_authorize_request_with_amount(
capture_method: CaptureMethod,
amount: i64,
) -> PaymentServiceAuthorizeRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_network: Some(1),
card_issuer: None,
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
let mut metadata = HashMap::new();
metadata.insert(
"description".to_string(),
"Its my first payment request".to_string(),
);
PaymentServiceAuthorizeRequest {
amount,
minor_amount: amount,
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_996943186016164794_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/helcim_payment_flows_test.rs
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some("https://duck.com".to_string()),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(create_test_billing_address()),
browser_info: Some(create_test_browser_info()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("helcim_test_{}", get_timestamp()))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
order_category: Some("PAY".to_string()),
metadata,
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(
transaction_id: &str,
request_ref_id: &str,
amount: i64,
) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(request_ref_id.to_string())),
}),
capture_method: None,
handle_response: None,
amount,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(
transaction_id: &str,
amount: i64,
) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: amount,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("capture_ref_{}", get_timestamp()))),
}),
browser_info: Some(create_test_browser_info()),
..Default::default()
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("void_ref_{}", get_timestamp()))),
}),
all_keys_required: None,
browser_info: Some(create_test_browser_info()),
amount: None,
currency: None,
..Default::default()
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_helcim_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Verify the response
assert!(
response.transaction_id.is_some(),
"Resource ID should be present"
);
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state. Got status: {}, error_code: {:?}, error_message: {:?}",
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_996943186016164794_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/helcim_payment_flows_test.rs
response.status, response.error_code, response.error_message
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let unique_amount = get_unique_amount();
let auth_request =
create_payment_authorize_request_with_amount(CaptureMethod::Manual, unique_amount);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_helcim_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized
if auth_response.status == i32::from(PaymentStatus::Authorized) {
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id, unique_amount);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_helcim_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
}
});
}
// Test payment void
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture to void
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request.clone());
add_helcim_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Extract the request ref ID
let request_ref_id = extract_request_ref_id(&auth_response);
// After authentication, sync the payment to get updated status
let sync_request =
create_payment_sync_request(&transaction_id, &request_ref_id, auth_request.amount);
let mut sync_grpc_request = Request::new(sync_request);
add_helcim_metadata(&mut sync_grpc_request);
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_helcim_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC void_payment call failed")
.into_inner();
// Verify the void response
assert!(
void_response.transaction_id.is_some(),
"Transaction ID should be present in void response"
);
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
// Extract the void transaction ID from the void response
let void_transaction_id = extract_void_transaction_id(&void_response);
// Verify the payment status with a sync operation using the void transaction ID
let sync_request =
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_996943186016164794_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/helcim_payment_flows_test.rs
create_payment_sync_request(&void_transaction_id, &request_ref_id, auth_request.amount);
let mut sync_grpc_request = Request::new(sync_request);
add_helcim_metadata(&mut sync_grpc_request);
// Send the sync request to verify void status
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the payment is properly voided
assert!(
sync_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void sync"
);
});
}
// Test payment sync
#[tokio::test]
async fn test_payment_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to sync
let auth_request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request.clone());
add_helcim_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Extract the request ref ID
let request_ref_id = extract_request_ref_id(&auth_response);
// Wait longer for the transaction to be processed - some async processing may happen
std::thread::sleep(std::time::Duration::from_secs(2));
// Create sync request with the specific transaction ID
let sync_request =
create_payment_sync_request(&transaction_id, &request_ref_id, auth_request.amount);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_helcim_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("Payment sync request failed")
.into_inner();
// Verify the sync response - could be charged, authorized, or pending for automatic capture
assert!(
sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state"
);
});
}
// NOTE: Refund tests are disabled for Helcim connector
// During testing, Helcim API returned the error message: "Card Transaction cannot be refunded"
// This indicates that refunds might not supported in the Helcim test/sandbox environment
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-7542628931815647432_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/test_health.rs
#![allow(clippy::expect_used)]
use grpc_server::{app, configs};
mod common;
use grpc_api_types::health_check::{health_client::HealthClient, HealthCheckRequest};
use tonic::{transport::Channel, Request};
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3949670969701485582_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/cashtocode_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::time::{SystemTime, UNIX_EPOCH};
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
identifier::IdType, payment_method, payment_service_client::PaymentServiceClient,
AuthenticationType, CaptureMethod, Currency, Identifier, PaymentMethod,
PaymentServiceAuthorizeRequest, PaymentStatus, RewardPaymentMethodType, RewardType,
},
};
use tonic::{transport::Channel, Request};
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Constants for Cashtocode connector
const CONNECTOR_NAME: &str = "cashtocode";
const AUTH_TYPE: &str = "currency-auth-key";
const MERCHANT_ID: &str = "merchant_1234";
const TEST_EMAIL: &str = "customer@example.com";
// Test data
const TEST_AMOUNT: i64 = 1000;
fn add_cashtocode_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load cashtocode credentials");
let auth_key_map = match auth {
domain_types::router_data::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
auth_key_map
}
_ => panic!("Expected CurrencyAuthKey auth type for cashtocode"),
};
// Serialize the auth_key_map to JSON for metadata
let auth_key_map_json =
serde_json::to_string(&auth_key_map).expect("Failed to serialize auth_key_map");
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-auth-key-map",
auth_key_map_json
.parse()
.expect("Failed to parse x-auth-key-map"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Reward(
RewardPaymentMethodType {
reward_type: i32::from(RewardType::Classicreward),
},
)),
}),
customer_id: Some("cust_1233".to_string()),
return_url: Some("https://hyperswitch.io/connector-service".to_string()),
webhook_url: Some("https://hyperswitch.io/connector-service".to_string()),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress::default()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("cashtocode_test_{}", get_timestamp()))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
..Default::default()
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization() {
grpc_test!(client, PaymentServiceClient<Channel>, {
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3949670969701485582_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/cashtocode_payment_flows_test.rs
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_cashtocode_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AuthenticationPending state"
);
});
}
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_2331089652036790915_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/braintree_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use cards::CardNumber;
use grpc_server::{app, configs};
mod common;
mod utils;
use std::{
collections::HashMap,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundResponse, RefundServiceGetRequest,
RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
// Constants for Braintree connector
const CONNECTOR_NAME: &str = "braintree";
const AUTH_TYPE: &str = "signature-key";
const MERCHANT_ID: &str = "merchant_17555143863";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4242424242424242"; // Valid test card for Braintree
const TEST_CARD_EXP_MONTH: &str = "10";
const TEST_CARD_EXP_YEAR: &str = "25";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add Braintree metadata headers to a request
fn add_braintree_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load braintree credentials");
let (api_key, key1, api_secret) = match auth {
domain_types::router_data::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => (api_key.expose(), key1.expose(), api_secret.expose()),
_ => panic!("Expected SignatureKey auth type for braintree"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-api-secret",
api_secret.parse().expect("Failed to parse x-api-secret"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-connector-request-reference-id",
format!("conn_ref_{}", get_timestamp())
.parse()
.expect("Failed to parse x-connector-request-reference-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to extract connector Refund ID from response
fn extract_refund_id(response: &RefundResponse) -> &String {
&response.refund_id
}
// Helper function to create a payment authorize request
fn create_payment_authorize_request(
capture_method: CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_2331089652036790915_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/braintree_payment_flows_test.rs
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_network: Some(1),
card_issuer: None,
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
let mut metadata = HashMap::new();
metadata.insert("merchant_account_id".to_string(), "Anand".to_string());
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some("https://duck.com".to_string()),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress::default()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("braintree_test_{}", get_timestamp()))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
metadata,
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: None,
// all_keys_required: None,
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
request_ref_id: None,
..Default::default()
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("void_ref_{}", get_timestamp()))),
}),
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
webhook_url: None,
browser_info: None,
merchant_account_id: Some("Anand".to_string()),
capture_method: None,
request_ref_id: None,
..Default::default()
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
let mut refund_metadata = HashMap::new();
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_2331089652036790915_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/braintree_payment_flows_test.rs
refund_metadata.insert("merchant_account_id".to_string(), "Anand".to_string());
refund_metadata.insert("merchant_config_currency".to_string(), "USD".to_string());
refund_metadata.insert("currency".to_string(), "USD".to_string());
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("rsync_ref_{}", get_timestamp()))),
}),
browser_info: None,
refund_metadata,
state: None,
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_braintree_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending)
|| response.status == i32::from(PaymentStatus::Pending)
|| response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AuthenticationPending or Pending or Charged state"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 4 seconds
tokio::time::sleep(std::time::Duration::from_secs(4)).await;
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_braintree_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::AuthenticationPending)
|| auth_response.status == i32::from(PaymentStatus::Pending)
|| auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AuthenticationPending or Pending state"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request - make sure they include the terminal_id
let mut capture_grpc_request = Request::new(capture_request);
add_braintree_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
});
}
// Test payment sync with auto capture
#[tokio::test]
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_2331089652036790915_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/braintree_payment_flows_test.rs
async fn test_payment_sync_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 8 seconds
tokio::time::sleep(std::time::Duration::from_secs(8)).await;
// Create the payment authorization request
let request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_braintree_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_braintree_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
assert!(
sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
});
}
// Test payment void
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 12 seconds
tokio::time::sleep(std::time::Duration::from_secs(12)).await;
// First create a payment with manual capture to void
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_braintree_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state before voiding"
);
// Create void request with a unique reference ID
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_braintree_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC void_payment call failed")
.into_inner();
// Verify the void response
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
// Verify the payment status with a sync operation
let sync_request = create_payment_sync_request(&transaction_id);
let mut sync_grpc_request = Request::new(sync_request);
add_braintree_metadata(&mut sync_grpc_request);
// Send the sync request to verify void status
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the payment is properly voided
assert!(
sync_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void sync"
);
});
}
// Test refund flow - handles both success and error cases
// Ignored as refund status in Settling or Settled state may take time in Braintree sandbox.
#[tokio::test]
#[ignore]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 16 seconds
tokio::time::sleep(std::time::Duration::from_secs(16)).await;
// Create the payment authorization request
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_2331089652036790915_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/braintree_payment_flows_test.rs
let request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_braintree_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_braintree_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in RefundSuccess state"
);
});
}
// Test refund sync flow - runs as a separate test since refund + sync is complex
// Ignored as refund status in Settling or Settled state may take time in Braintree sandbox.
#[tokio::test]
#[ignore]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// Add delay of 20 seconds
tokio::time::sleep(std::time::Duration::from_secs(20)).await;
// Create the payment authorization request
let request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_braintree_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
assert!(
response.status == i32::from(PaymentStatus::Charged),
"Payment should be in Charged state"
);
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_braintree_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in RefundSuccess state"
);
let refund_id = extract_refund_id(&refund_response);
// Create refund sync request
let refund_sync_request = create_refund_sync_request(&transaction_id, refund_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_braintree_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request
let refund_sync_response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund sync call failed")
.into_inner();
// Verify the refund sync response
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund Sync should be in RefundSuccess state"
);
});
});
}
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5183309079052678393_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/payload_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
use hyperswitch_masking::Secret;
mod common;
mod utils;
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, AcceptanceType, Address, AuthenticationType,
CaptureMethod, CardDetails, CardPaymentMethodType, CountryAlpha2, Currency,
CustomerAcceptance, FutureUsage, Identifier, MandateReference, PaymentAddress,
PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceRegisterRequest, PaymentServiceRepeatEverythingRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundStatus,
},
};
use rand::Rng;
use std::collections::HashMap;
use tonic::{transport::Channel, Request};
use uuid::Uuid;
const CONNECTOR_NAME: &str = "payload";
const AUTH_TYPE: &str = "currency-auth-key";
const MERCHANT_ID: &str = "merchant_payload_test";
// Test card data
const TEST_CARD_NUMBER: &str = "4111111111111111";
const TEST_CARD_EXP_MONTH: &str = "12";
const TEST_CARD_EXP_YEAR: &str = "2025";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
fn generate_unique_id(prefix: &str) -> String {
format!("{}_{}", prefix, Uuid::new_v4())
}
fn add_payload_metadata<T>(request: &mut Request<T>) {
// Get API credentials using the common credential loading utility
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load Payload credentials");
let auth_key_map_json = match auth {
domain_types::router_data::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
// Convert the auth_key_map to JSON string format expected by the metadata
serde_json::to_string(&auth_key_map).expect("Failed to serialize auth_key_map")
}
_ => panic!("Expected CurrencyAuthKey auth type for Payload"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-auth-key-map",
auth_key_map_json
.parse()
.expect("Failed to parse x-auth-key-map"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
// Generate random billing address to avoid duplicates
let mut rng = rand::thread_rng();
let random_street_num = rng.gen_range(100..9999);
let random_zip_suffix = rng.gen_range(1000..9999);
let address = PaymentAddress {
billing_address: Some(Address {
first_name: Some("John".to_string().into()),
last_name: Some("Doe".to_string().into()),
email: Some(TEST_EMAIL.to_string().into()),
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5183309079052678393_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/payload_payment_flows_test.rs
line1: Some(format!("{} Main St", random_street_num).into()),
city: Some("San Francisco".to_string().into()),
state: Some("CA".to_string().into()),
zip_code: Some(format!("{}", random_zip_suffix).into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
..Default::default()
}),
shipping_address: None,
};
// Use random amount to avoid duplicates
let mut rng = rand::thread_rng();
let unique_amount = rng.gen_range(1000..10000); // Amount between $10.00 and $100.00
PaymentServiceAuthorizeRequest {
amount: unique_amount,
minor_amount: unique_amount,
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some("https://example.com/return".to_string()),
webhook_url: Some("https://example.com/webhook".to_string()),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(address),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("payload_test"))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
..Default::default()
}
}
fn create_payment_sync_request(transaction_id: &str, amount: i64) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("payload_sync"))),
}),
capture_method: None,
handle_response: None,
amount,
currency: i32::from(Currency::Usd),
state: None,
}
}
fn create_payment_capture_request(
transaction_id: &str,
amount: i64,
) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: amount,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
request_ref_id: None,
..Default::default()
}
}
fn create_payment_void_request(transaction_id: &str, amount: i64) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("payload_void"))),
}),
all_keys_required: None,
browser_info: None,
amount: Some(amount),
currency: Some(i32::from(Currency::Usd)),
..Default::default()
}
}
fn create_refund_request(transaction_id: &str, amount: i64) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("refund"))),
}),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: amount,
refund_amount: amount,
minor_payment_amount: amount,
minor_refund_amount: amount,
..Default::default()
}
}
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
response
.transaction_id
.as_ref()
.and_then(|id| id.id_type.as_ref())
.and_then(|id_type| match id_type {
IdType::Id(connector_txn_id) => Some(connector_txn_id.clone()),
_ => None,
})
.expect("Failed to extract connector transaction ID from response")
}
#[allow(clippy::field_reassign_with_default)]
fn create_repeat_payment_request(mandate_id: &str) -> PaymentServiceRepeatEverythingRequest {
// Use random amount to avoid duplicates
let mut rng = rand::thread_rng();
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5183309079052678393_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/payload_payment_flows_test.rs
let unique_amount = rng.gen_range(1000..10000); // Amount between $10.00 and $100.00
let mandate_reference = MandateReference {
mandate_id: Some(mandate_id.to_string()),
payment_method_id: None,
};
let mut metadata = HashMap::new();
metadata.insert("order_type".to_string(), "recurring".to_string());
metadata.insert(
"customer_note".to_string(),
"Recurring payment using saved payment method".to_string(),
);
PaymentServiceRepeatEverythingRequest {
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("repeat"))),
}),
mandate_reference: Some(mandate_reference),
amount: unique_amount,
currency: i32::from(Currency::Usd),
minor_amount: unique_amount,
merchant_order_reference_id: Some(generate_unique_id("repeat_order")),
metadata,
webhook_url: None,
capture_method: None,
email: Some(Secret::new(TEST_EMAIL.to_string())),
browser_info: None,
test_mode: None,
payment_method_type: None,
merchant_account_metadata: HashMap::new(),
state: None,
..Default::default()
}
}
fn create_register_request() -> PaymentServiceRegisterRequest {
create_register_request_with_prefix("payload_mandate")
}
fn create_register_request_with_prefix(prefix: &str) -> PaymentServiceRegisterRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
// Use random values to create unique data to avoid duplicate detection
let mut rng = rand::thread_rng();
let random_street_num = rng.gen_range(1000..9999);
let unique_zip = format!("{}", rng.gen_range(10000..99999));
let random_id = rng.gen_range(1000..9999);
let unique_email = format!("customer{}@example.com", random_id);
let unique_first_name = format!("John{}", random_id);
PaymentServiceRegisterRequest {
minor_amount: Some(0), // Setup mandate with 0 amount
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
customer_name: Some(format!("{} Doe", unique_first_name)),
email: Some(unique_email.clone().into()),
customer_acceptance: Some(CustomerAcceptance {
acceptance_type: i32::from(AcceptanceType::Offline),
accepted_at: 0,
online_mandate_details: None,
}),
address: Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some(unique_first_name.into()),
last_name: Some("Doe".to_string().into()),
line1: Some(format!("{} Market St", random_street_num).into()),
line2: None,
line3: None,
city: Some("San Francisco".to_string().into()),
state: Some("CA".to_string().into()),
zip_code: Some(unique_zip.into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
phone_number: None,
phone_country_code: None,
email: Some(unique_email.into()),
}),
shipping_address: None,
}),
auth_type: i32::from(AuthenticationType::NoThreeDs),
setup_future_usage: Some(i32::from(FutureUsage::OffSession)),
enrolled_for_3ds: false,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id(prefix))),
}),
metadata: HashMap::new(),
..Default::default()
}
}
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5183309079052678393_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/payload_payment_flows_test.rs
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving,
"Health check should return Serving status"
);
});
}
#[tokio::test]
async fn test_authorize_psync_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Wait 30 seconds before making API call to avoid parallel test conflicts
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
// Step 1: Authorize with manual capture
let request = create_authorize_request(CaptureMethod::Manual);
let amount = request.minor_amount; // Capture amount from request
let mut grpc_request = Request::new(request);
add_payload_metadata(&mut grpc_request);
let auth_response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
let transaction_id = extract_transaction_id(&auth_response);
assert_eq!(
auth_response.status,
i32::from(PaymentStatus::Authorized),
"Payment should be in Authorized state"
);
// Step 2: PSync
let sync_request = create_payment_sync_request(&transaction_id, amount);
let mut sync_grpc_request = Request::new(sync_request);
add_payload_metadata(&mut sync_grpc_request);
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC sync call failed")
.into_inner();
assert!(
sync_response.transaction_id.is_some(),
"Sync response should contain transaction ID"
);
// Step 3: Void
let void_request = create_payment_void_request(&transaction_id, amount);
let mut void_grpc_request = Request::new(void_request);
add_payload_metadata(&mut void_grpc_request);
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC void call failed")
.into_inner();
assert_eq!(
void_response.status,
i32::from(PaymentStatus::Voided),
"Payment should be in Voided state after void"
);
});
}
#[tokio::test]
async fn test_authorize_capture_refund_rsync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Wait 30 seconds before making API call to avoid parallel test conflicts
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
// Step 1: Authorize with manual capture
let request = create_authorize_request(CaptureMethod::Manual);
let amount = request.minor_amount; // Capture amount from request
let mut grpc_request = Request::new(request);
add_payload_metadata(&mut grpc_request);
let auth_response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
let transaction_id = extract_transaction_id(&auth_response);
assert_eq!(
auth_response.status,
i32::from(PaymentStatus::Authorized),
"Payment should be in Authorized state"
);
// Step 2: Capture
let capture_request = create_payment_capture_request(&transaction_id, amount);
let mut capture_grpc_request = Request::new(capture_request);
add_payload_metadata(&mut capture_grpc_request);
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC capture call failed")
.into_inner();
assert_eq!(
capture_response.status,
i32::from(PaymentStatus::Charged),
"Payment should be in Charged state after capture"
);
// Step 3: Refund
let refund_request = create_refund_request(&transaction_id, amount);
let mut refund_grpc_request = Request::new(refund_request);
add_payload_metadata(&mut refund_grpc_request);
let refund_response = client
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5183309079052678393_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/payload_payment_flows_test.rs
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
let refund_id = refund_response.refund_id.clone();
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in RefundSuccess or RefundPending state"
);
// Step 4: RSync (Refund Sync)
let rsync_request = PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(refund_id)),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("payload_rsync"))),
}),
capture_method: None,
handle_response: None,
amount,
currency: i32::from(Currency::Usd),
state: None,
};
let mut rsync_grpc_request = Request::new(rsync_request);
add_payload_metadata(&mut rsync_grpc_request);
let rsync_response = client
.get(rsync_grpc_request)
.await
.expect("gRPC refund sync call failed")
.into_inner();
assert!(
rsync_response.transaction_id.is_some(),
"Refund sync response should contain transaction ID"
);
});
}
#[tokio::test]
async fn test_setup_mandate() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Wait 30 seconds before making API call to avoid parallel test conflicts
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
// Create setup mandate request (zero amount payment to save card)
let request = create_register_request();
let mut grpc_request = Request::new(request);
add_payload_metadata(&mut grpc_request);
let response = client
.register(grpc_request)
.await
.expect("gRPC register call failed")
.into_inner();
// Verify we got a mandate reference
assert!(
response.mandate_reference.is_some(),
"Mandate reference should be present"
);
if let Some(mandate_ref) = &response.mandate_reference {
assert!(
mandate_ref.mandate_id.is_some() || mandate_ref.payment_method_id.is_some(),
"Mandate ID or payment method ID should be present"
);
if let Some(mandate_id) = &mandate_ref.mandate_id {
assert!(!mandate_id.is_empty(), "Mandate ID should not be empty");
}
if let Some(pm_id) = &mandate_ref.payment_method_id {
assert!(!pm_id.is_empty(), "Payment method ID should not be empty");
}
}
// Verify status is success
assert_eq!(
response.status,
i32::from(PaymentStatus::Charged),
"Setup mandate should be in Charged/Success state"
);
});
}
#[tokio::test]
//Ignored as getting "duplicate transaction" error when run in CI pipeline
#[ignore]
async fn test_repeat_payment() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// NOTE: This test may fail with "duplicate transaction" error if run too soon
// after other tests that use the same test card. Payload has duplicate detection.
tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
let register_request = create_register_request_with_prefix("payload_repeat_test");
let mut register_grpc_request = Request::new(register_request);
add_payload_metadata(&mut register_grpc_request);
let register_response = client
.register(register_grpc_request)
.await
.expect("gRPC register call failed")
.into_inner();
if register_response.mandate_reference.is_none() {
panic!(
"Mandate reference should be present. Status: {}, Error: {:?}",
register_response.status, register_response.error_message
);
}
let mandate_ref = register_response
.mandate_reference
.as_ref()
.expect("Mandate reference should be present");
let mandate_id = mandate_ref
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5183309079052678393_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/payload_payment_flows_test.rs
.mandate_id
.as_ref()
.expect("mandate_id should be present");
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
let repeat_request = create_repeat_payment_request(mandate_id);
let mut repeat_grpc_request = Request::new(repeat_request);
add_payload_metadata(&mut repeat_grpc_request);
let repeat_response = client
.repeat_everything(repeat_grpc_request)
.await
.expect("gRPC repeat_everything call failed")
.into_inner();
assert!(
repeat_response.transaction_id.is_some(),
"Transaction ID should be present in repeat payment response"
);
assert_eq!(
repeat_response.status,
i32::from(PaymentStatus::Charged),
"Repeat payment should be in Charged state with automatic capture"
);
});
}
| {
"chunk": 5,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
#![allow(unused_imports)]
#![allow(dead_code)]
use grpc_server::{app, configs};
use hyperswitch_masking::{ExposeInterface, Secret};
mod common;
mod utils;
use std::{
any::Any,
collections::HashMap,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, AcceptanceType, Address, AuthenticationType,
BrowserInformation, CaptureMethod, CardDetails, CardPaymentMethodType, CountryAlpha2,
Currency, CustomerAcceptance, FutureUsage, Identifier, MandateReference, PaymentAddress,
PaymentMethod, PaymentMethodType, PaymentServiceAuthorizeRequest,
PaymentServiceAuthorizeResponse, PaymentServiceCaptureRequest, PaymentServiceGetRequest,
PaymentServiceRefundRequest, PaymentServiceRegisterRequest,
PaymentServiceRepeatEverythingRequest, PaymentServiceRepeatEverythingResponse,
PaymentServiceVoidRequest, PaymentStatus, RefundServiceGetRequest, RefundStatus,
},
};
use rand::{distributions::Alphanumeric, Rng};
use tonic::{transport::Channel, Request};
use uuid::Uuid;
// Function to generate random name
fn random_name() -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(8)
.map(char::from)
.collect()
}
// Constants for AuthorizeDotNet connector
const CONNECTOR_NAME: &str = "authorizedotnet";
// Test card data matching working grpcurl payload
const TEST_AMOUNT: i64 = 102; // Amount from working grpcurl
const TEST_CARD_NUMBER: &str = "5123456789012346"; // Mastercard from working grpcurl
const TEST_CARD_EXP_MONTH: &str = "12";
const TEST_CARD_EXP_YEAR: &str = "2025";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "TestCustomer0011uyty4";
const TEST_EMAIL_BASE: &str = "testcustomer001@gmail.com";
// Test data for repeat payment
const REPEAT_AMOUNT: i64 = 1000; // Amount for repeat payments
// Metadata for Authorize.Net
// Note: BASE64_METADATA is the base64 encoded version of this JSON:
// {"userFields":{"MerchantDefinedFieldName1":"MerchantDefinedFieldValue1","favorite_color":"blue"}}
const BASE64_METADATA: &str =
"eyJ1c2VyRmllbGRzIjp7Ik1lcmNoYW50RGVmaW5lZEZpZWxkTmFtZTEiOiJNZXJjaGFudERlZmluZWRGaWVsZFZhbHVlMSIsImZhdm9yaXRlX2NvbG9yIjoiYmx1ZSJ9fQ==";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to generate unique email
fn generate_unique_email() -> String {
format!("testcustomer{}@gmail.com", get_timestamp())
}
// Helper function to generate unique request reference ID
fn generate_unique_request_ref_id(prefix: &str) -> String {
format!("{}_{}", prefix, &Uuid::new_v4().simple().to_string()[..8])
}
// Helper function to add AuthorizeDotNet metadata headers to a request
fn add_authorizenet_metadata<T>(request: &mut Request<T>) {
// Get API credentials using the common credential loading utility
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load Authorize.Net credentials");
let (api_key, key1) = match auth {
domain_types::router_data::ConnectorAuthType::BodyKey { api_key, key1 } => {
(api_key.expose(), key1.expose())
}
_ => panic!("Expected BodyKey auth type for Authorize.Net"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"body-key".parse().expect("Failed to parse x-auth"),
);
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
// Add merchant ID which is required by the server
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
// Add tenant ID which is required by the server
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
// Add request ID which is required by the server
request.metadata_mut().append(
"x-request-id",
generate_unique_request_ref_id("req")
.parse()
.expect("Failed to parse x-request-id"),
);
// Add connector request reference ID which is required for our error handling
request.metadata_mut().append(
"x-connector-request-reference-id",
generate_unique_request_ref_id("conn_ref")
.parse()
.expect("Failed to parse x-connector-request-reference-id"),
);
}
// Helper function to extract transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
// First try to get the transaction ID from transaction_id field
match &response.transaction_id {
Some(id) => match &id.id_type {
Some(id_type) => match id_type {
IdType::Id(id) => id.clone(),
IdType::EncodedData(id) => id.clone(),
_ => format!("unknown_id_type_{}", get_timestamp()),
},
None => format!("no_id_type_{}", get_timestamp()),
},
None => {
// Fallback to response_ref_id if transaction_id is not available
if let Some(ref_id) = &response.response_ref_id {
match &ref_id.id_type {
Some(id_type) => match id_type {
IdType::Id(id) => id.clone(),
IdType::EncodedData(id) => id.clone(),
_ => format!("unknown_ref_id_{}", get_timestamp()),
},
None => format!("no_ref_id_type_{}", get_timestamp()),
}
} else {
format!("no_transaction_id_{}", get_timestamp())
}
}
}
}
// Helper function to create a repeat payment request (matching your JSON format)
#[allow(clippy::field_reassign_with_default)]
fn create_repeat_payment_request(mandate_id: &str) -> PaymentServiceRepeatEverythingRequest {
let request_ref_id = Identifier {
id_type: Some(IdType::Id(generate_unique_request_ref_id("repeat_req"))),
};
let mandate_reference = MandateReference {
mandate_id: Some(mandate_id.to_string()),
payment_method_id: None,
};
// Create metadata matching your JSON format
let mut metadata = HashMap::new();
metadata.insert("order_type".to_string(), "recurring".to_string());
metadata.insert(
"customer_note".to_string(),
"Monthly subscription payment".to_string(),
);
PaymentServiceRepeatEverythingRequest {
request_ref_id: Some(request_ref_id),
mandate_reference: Some(mandate_reference),
amount: REPEAT_AMOUNT,
currency: i32::from(Currency::Usd),
minor_amount: REPEAT_AMOUNT,
merchant_order_reference_id: Some(format!("repeat_order_{}", get_timestamp())),
metadata,
webhook_url: Some("https://your-webhook-url.com/payments/webhook".to_string()),
capture_method: None,
email: None,
browser_info: None,
test_mode: None,
payment_method_type: None,
merchant_account_metadata: HashMap::new(),
state: None,
recurring_mandate_payment_data: None,
address: None,
connector_customer_id: None,
description: None,
..Default::default()
}
}
// Test repeat payment (MIT) flow using previously created mandate
#[tokio::test]
async fn test_repeat_everything() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First, create a mandate using register
let register_request = create_register_request();
let mut register_grpc_request = Request::new(register_request);
add_authorizenet_metadata(&mut register_grpc_request);
let register_response = client
.register(register_grpc_request)
.await
.expect("gRPC register call failed")
.into_inner();
// Verify we got a mandate reference
assert!(
register_response.mandate_reference.is_some(),
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
"Mandate reference should be present"
);
let mandate_id = register_response
.mandate_reference
.as_ref()
.unwrap()
.mandate_id
.as_ref()
.expect("Mandate ID should be present");
// Now perform a repeat payment using the mandate
let repeat_request = create_repeat_payment_request(mandate_id);
let mut repeat_grpc_request = Request::new(repeat_request);
add_authorizenet_metadata(&mut repeat_grpc_request);
// Send the repeat payment request
let repeat_response = client
.repeat_everything(repeat_grpc_request)
.await
.expect("gRPC repeat_everything call failed")
.into_inner();
// Verify the response
assert!(
repeat_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// // Verify no error occurred
// assert!(
// repeat_response.error_message.is_none()
// || repeat_response.error_message.as_ref().unwrap().is_empty(),
// "No error message should be present for successful repeat payment"
// );
});
}
// Helper function to create a payment authorization request
#[allow(clippy::field_reassign_with_default)]
fn create_payment_authorize_request(
capture_method: common_enums::CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
// Initialize with all required fields
let mut request = PaymentServiceAuthorizeRequest::default();
let mut request_ref_id = Identifier::default();
request_ref_id.id_type = Some(IdType::Id(
generate_unique_request_ref_id("req_"), // Using timestamp to make unique
));
request.request_ref_id = Some(request_ref_id);
// Set the basic payment details matching working grpcurl
request.amount = TEST_AMOUNT;
request.minor_amount = TEST_AMOUNT;
request.currency = 146; // Currency value from working grpcurl
// Set up card payment method using the correct structure
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(2_i32), // Mastercard network for 5123456789012346
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
request.payment_method = Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
});
request.customer_id = Some("TEST_CONNECTOR".to_string());
// Set the customer information with unique email
request.email = Some(generate_unique_email().into());
// Generate random names for billing to prevent duplicate transaction errors
let billing_first_name = random_name();
let billing_last_name = random_name();
// Minimal address structure matching working grpcurl
request.address = Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some(billing_first_name.into()),
last_name: Some(billing_last_name.into()),
line1: Some("14 Main Street".to_string().into()),
line2: None,
line3: None,
city: Some("Pecan Springs".to_string().into()),
state: Some("TX".to_string().into()),
zip_code: Some("44628".to_string().into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
phone_number: None,
phone_country_code: None,
email: None,
}),
shipping_address: None, // Minimal address - no shipping for working grpcurl
});
let browser_info = BrowserInformation {
color_depth: None,
java_enabled: Some(false),
screen_height: Some(1080),
screen_width: Some(1920),
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string()),
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(),
),
java_script_enabled: Some(false),
language: Some("en-US".to_string()),
referer: None,
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
time_zone_offset_minutes: None,
};
request.browser_info = Some(browser_info);
request.return_url = Some("www.google.com".to_string());
// Set the transaction details
request.auth_type = i32::from(AuthenticationType::NoThreeDs);
request.request_incremental_authorization = true;
request.enrolled_for_3ds = true;
// Set capture method
if let common_enums::CaptureMethod::Manual = capture_method {
request.capture_method = Some(i32::from(CaptureMethod::Manual));
// request.request_incremental_authorization = true;
} else {
request.capture_method = Some(i32::from(CaptureMethod::Automatic));
}
// Set the connector metadata (Base64 encoded)
let mut metadata = HashMap::new();
metadata.insert("metadata".to_string(), BASE64_METADATA.to_string());
request.metadata = metadata;
request
}
// Helper function to create a payment sync request
fn create_payment_get_request(transaction_id: &str) -> PaymentServiceGetRequest {
let transaction_id_obj = Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
};
let request_ref_id = Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
};
PaymentServiceGetRequest {
transaction_id: Some(transaction_id_obj),
request_ref_id: Some(request_ref_id),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: 146, // Currency value from working grpcurl
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
let request_ref_id = Identifier {
id_type: Some(IdType::Id(generate_unique_request_ref_id("capture"))),
};
let transaction_id_obj = Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
};
PaymentServiceCaptureRequest {
request_ref_id: Some(request_ref_id),
transaction_id: Some(transaction_id_obj),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
connector_metadata: HashMap::new(),
browser_info: None,
capture_method: None,
state: None,
}
}
// Helper function to create a void request
fn create_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
let request_ref_id = Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
};
let transaction_id_obj = Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
};
PaymentServiceVoidRequest {
transaction_id: Some(transaction_id_obj),
request_ref_id: Some(request_ref_id),
cancellation_reason: None,
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
// Helper function to sleep for a short duration to allow server processing
fn allow_processing_time() {
std::thread::sleep(std::time::Duration::from_secs(3));
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
let request_ref_id = Identifier {
id_type: Some(IdType::Id(generate_unique_request_ref_id("refund"))),
};
let transaction_id_obj = Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
};
// Create refund metadata with credit card information as required by Authorize.net
let mut refund_metadata = HashMap::new();
refund_metadata.insert(
"refund_metadata".to_string(),
format!(
"{{\"creditCard\":{{\"cardNumber\":\"{TEST_CARD_NUMBER}\",\"expirationDate\":\"2025-12\"}}}}",
),
);
PaymentServiceRefundRequest {
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
request_ref_id: Some(request_ref_id),
refund_id: generate_unique_request_ref_id("refund_id"),
transaction_id: Some(transaction_id_obj),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: Some("Test refund".to_string()),
webhook_url: None,
merchant_account_id: None,
capture_method: None,
metadata: HashMap::new(),
refund_metadata,
browser_info: None,
state: None,
}
}
// Helper function to create a refund get request
fn create_refund_get_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
let request_ref_id = Identifier {
id_type: Some(IdType::Id(generate_unique_request_ref_id("refund_get"))),
};
let transaction_id_obj = Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
};
RefundServiceGetRequest {
request_ref_id: Some(request_ref_id),
transaction_id: Some(transaction_id_obj),
refund_id: refund_id.to_string(),
browser_info: None,
refund_reason: None,
refund_metadata: HashMap::new(),
state: None,
}
}
// Helper function to create a register (setup mandate) request (matching your JSON format)
#[allow(clippy::field_reassign_with_default)]
fn create_register_request() -> PaymentServiceRegisterRequest {
let mut request = PaymentServiceRegisterRequest::default();
// Set amounts matching your JSON (3000 minor units)
request.minor_amount = Some(TEST_AMOUNT);
request.currency = i32::from(Currency::Usd);
// Set up card payment method with Visa network as in your JSON
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1_i32),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
request.payment_method = Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
});
// Set customer information with unique email
request.customer_name = Some(TEST_CARD_HOLDER.to_string());
request.email = Some(generate_unique_email().into());
// Add customer acceptance as required by the server (matching your JSON: "acceptance_type": "OFFLINE")
request.customer_acceptance = Some(CustomerAcceptance {
acceptance_type: i32::from(AcceptanceType::Offline),
accepted_at: 0, // You can set this to current timestamp if needed
online_mandate_details: None,
});
// Add billing address matching your JSON format
request.address = Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some("Test".to_string().into()),
last_name: Some("Customer001".to_string().into()),
line1: Some("123 Test St".to_string().into()),
line2: None,
line3: None,
city: Some("Test City".to_string().into()),
state: Some("NY".to_string().into()),
zip_code: Some("10001".to_string().into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
phone_number: None,
phone_country_code: None,
email: Some(generate_unique_email().into()),
}),
shipping_address: None,
});
// Set auth type as NO_THREE_DS
request.auth_type = i32::from(AuthenticationType::NoThreeDs);
// Set setup_future_usage to OFF_SESSION (matching your JSON: "setup_future_usage": "OFF_SESSION")
request.setup_future_usage = Some(i32::from(FutureUsage::OffSession));
// Set 3DS enrollment to false
request.enrolled_for_3ds = false;
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
// Set request reference ID with unique UUID (this will be unique every time)
request.request_ref_id = Some(Identifier {
id_type: Some(IdType::Id(generate_unique_request_ref_id("mandate"))),
});
// Set empty connector metadata
request.metadata = HashMap::new();
request
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// println!("Auth request for auto capture: {:?}", request);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_authorizenet_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// println!("Payment authorize response for auto: {:?}", response);
// Verify the response - transaction_id may not be present for failed or pending payments
let successful_statuses = [
i32::from(PaymentStatus::Charged),
i32::from(PaymentStatus::Authorized),
];
if successful_statuses.contains(&response.status) {
assert!(
response.transaction_id.is_some(),
"Transaction ID should be present for successful payments, but status was: {}",
response.status
);
}
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&response);
// Verify payment status - allow CHARGED, PENDING, or FAILURE (common in sandbox)
let acceptable_statuses = [
i32::from(PaymentStatus::Charged),
i32::from(PaymentStatus::Pending),
];
assert!(
acceptable_statuses.contains(&response.status),
"Payment should be in CHARGED, PENDING, or FAILURE state (sandbox) but was: {}",
response.status
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// println!("Auth request for manual capture: {:?}", auth_request);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_authorizenet_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Transaction_id may not be present for failed or pending payments
let successful_statuses = [
i32::from(PaymentStatus::Charged),
i32::from(PaymentStatus::Authorized),
i32::from(PaymentStatus::Pending),
];
// println!(
// "Payment authorize response: {:?}",
// auth_response
// );
if successful_statuses.contains(&auth_response.status) {
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present for successful payments, but status was: {}",
auth_response.status
);
}
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
| {
"chunk": 5,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_6 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
// Verify payment status is authorized (for manual capture) - allow PENDING or FAILURE in sandbox
let acceptable_statuses = [
i32::from(PaymentStatus::Authorized),
i32::from(PaymentStatus::Pending),
i32::from(PaymentStatus::Charged),
// i32::from(PaymentStatus::Failure),
];
// println!("print acceptable statuses: {:?}", acceptable_statuses);
assert!(
acceptable_statuses.contains(&auth_response.status),
"Payment should be in AUTHORIZED, PENDING, or FAILURE state (sandbox) but was: {}",
auth_response.status
);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_authorizenet_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture - allow PENDING or FAILURE in sandbox
let acceptable_statuses = [
i32::from(PaymentStatus::Charged),
i32::from(PaymentStatus::Pending),
// i32::from(PaymentStatus::Failure),
];
assert!(
acceptable_statuses.contains(&capture_response.status),
"Payment should be in CHARGED, PENDING, or FAILURE state after capture (sandbox) but was: {}",
capture_response.status
);
});
}
// Test payment sync
#[tokio::test]
async fn test_payment_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to sync
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_authorizenet_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized - allow PENDING or FAILURE in sandbox
let acceptable_statuses = [
i32::from(PaymentStatus::Authorized),
i32::from(PaymentStatus::Pending),
// i32::from(PaymentStatus::Failure),
];
assert!(
acceptable_statuses.contains(&auth_response.status),
"Payment should be in AUTHORIZED, PENDING, or FAILURE state (sandbox) but was: {}",
auth_response.status
);
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// Create get request
let get_request = create_payment_get_request(&_transaction_id);
// Add metadata headers for get request
let mut get_grpc_request = Request::new(get_request);
add_authorizenet_metadata(&mut get_grpc_request);
// Send the get request
let get_response = client
.get(get_grpc_request)
.await
.expect("gRPC payment_get call failed")
.into_inner();
// Verify the sync response
// Verify the payment status matches what we expect - allow PENDING or FAILURE in sandbox
let acceptable_statuses = [
i32::from(PaymentStatus::Authorized),
i32::from(PaymentStatus::Pending),
i32::from(PaymentStatus::Charged),
// i32::from(PaymentStatus::Failure),
];
assert!(
acceptable_statuses.contains(&get_response.status),
"Payment get should return AUTHORIZED, PENDING, or FAILURE state (sandbox) but was: {}",
get_response.status
);
// Verify we have transaction ID in the response
assert!(
get_response.transaction_id.is_some(),
"Transaction ID should be present in get response"
);
});
}
| {
"chunk": 6,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_7 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
// Test void flow (unique to AuthorizeDotNet)
#[tokio::test]
async fn test_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to void
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_authorizenet_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized or handle other states - allow PENDING or FAILURE in sandbox
let acceptable_statuses = [
i32::from(PaymentStatus::Authorized),
i32::from(PaymentStatus::Pending),
i32::from(PaymentStatus::Voided),
// i32::from(PaymentStatus::Failure),
];
// println!(
// "Auth response: {:?}",
// auth_response
// );
assert!(
acceptable_statuses.contains(&auth_response.status),
"Payment should be in AUTHORIZED, PENDING, or FAILURE (sandbox) but was: {}",
auth_response.status
);
// Skip void test if payment is not in AUTHORIZED state (but allow test to continue if PENDING)
if auth_response.status != i32::from(PaymentStatus::Authorized)
&& auth_response.status != i32::from(PaymentStatus::Pending)
{
return;
}
// Allow some time for the authorization to be processed
allow_processing_time();
// Additional async delay when running with other tests to avoid conflicts
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// println!("transaction_id: {}", transaction_id);
// Create void request
let void_request = create_void_request(&transaction_id);
// println!("Void request: {:?}", void_request);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_authorizenet_metadata(&mut void_grpc_request);
// println!("Void grpc request: {:?}", void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC void_payment call failed")
.into_inner();
// Accept VOIDED status
let acceptable_statuses = [i32::from(PaymentStatus::Voided)];
// println!("Void response: {:?}", void_response);
assert!(
acceptable_statuses.contains(&void_response.status),
"Payment should be in VOIDED state but was: {}",
void_response.status
);
});
}
// Test refund flow
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_authorizenet_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status or handle other states - allow PENDING or FAILURE in sandbox
let acceptable_statuses = [
i32::from(PaymentStatus::Charged),
i32::from(PaymentStatus::Pending),
];
assert!(
acceptable_statuses.contains(&auth_response.status),
"Payment should be in CHARGED, PENDING, or FAILURE state (sandbox) but was: {}",
auth_response.status
);
// Skip refund test if payment is not in CHARGED state (but allow test to continue if PENDING)
| {
"chunk": 7,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_8 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
if auth_response.status != i32::from(PaymentStatus::Charged)
&& auth_response.status != i32::from(PaymentStatus::Pending)
{
return;
}
// Wait a bit to ensure the payment is fully processed
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_authorizenet_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_result = client.refund(refund_grpc_request).await;
// Check if we have a successful refund OR any expected error (including gRPC errors)
let is_success_status = refund_result.as_ref().is_ok_and(|response| {
response.get_ref().status == i32::from(RefundStatus::RefundSuccess)
});
let has_expected_error = refund_result.as_ref().is_ok_and(|response| {
let error_msg = response.get_ref().error_message();
error_msg.contains(
"The referenced transaction does not meet the criteria for issuing a credit.",
) || error_msg.contains("credit")
|| error_msg.contains("refund")
|| error_msg.contains("transaction")
|| response.get_ref().status == i32::from(RefundStatus::RefundFailure)
});
let has_grpc_error = refund_result.is_err();
assert!(
is_success_status || has_expected_error || has_grpc_error,
"Refund should either succeed, have expected error, or gRPC error (common in sandbox). Got: {refund_result:?}"
);
});
}
// Test register (setup mandate) flow
#[tokio::test]
async fn test_register() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the register request
let request = create_register_request();
// Add metadata headers
let mut grpc_request = Request::new(request);
add_authorizenet_metadata(&mut grpc_request);
// Send the request
let response = client
.register(grpc_request)
.await
.expect("gRPC register call failed")
.into_inner();
// Verify the response
assert!(
response.registration_id.is_some(),
"Registration ID should be present"
);
// Check if we have a mandate reference
assert!(
response.mandate_reference.is_some(),
"Mandate reference should be present"
);
// Verify the mandate reference has the expected structure
if let Some(mandate_ref) = &response.mandate_reference {
assert!(
mandate_ref.mandate_id.is_some(),
"Mandate ID should be present"
);
// Verify the composite ID format (profile_id-payment_profile_id)
if let Some(mandate_id) = &mandate_ref.mandate_id {
assert!(
mandate_id.contains('-') || !mandate_id.is_empty(),
"Mandate ID should be either a composite ID or a profile ID"
);
}
}
// Verify no error occurred
assert!(
response.error_message.is_none() || response.error_message.as_ref().unwrap().is_empty(),
"No error message should be present for successful register"
);
});
}
// Test authorization with setup_future_usage
#[tokio::test]
async fn test_authorize_with_setup_future_usage() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create an authorization request with setup_future_usage
let mut auth_request =
create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add setup_future_usage to trigger profile creation
auth_request.setup_future_usage = Some(i32::from(FutureUsage::OnSession));
// Add metadata headers
let mut auth_grpc_request = Request::new(auth_request);
add_authorizenet_metadata(&mut auth_grpc_request);
// Send the authorization request
let auth_response = client
.authorize(auth_grpc_request)
.await
| {
"chunk": 8,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_7957748028931523727_9 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/authorizedotnet_payment_flows_test.rs
.expect("gRPC authorize with setup_future_usage call failed")
.into_inner();
// Verify the response - transaction_id may not be present for failed or pending payments
let successful_statuses = [
i32::from(PaymentStatus::Charged),
i32::from(PaymentStatus::Authorized),
];
if successful_statuses.contains(&auth_response.status) {
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present for successful payments, but status was: {}",
auth_response.status
);
}
// Verify payment status - allow PENDING or FAILURE in sandbox
let acceptable_statuses = [
i32::from(PaymentStatus::Charged),
i32::from(PaymentStatus::Pending),
i32::from(PaymentStatus::Authorized),
];
assert!(
acceptable_statuses.contains(&auth_response.status),
"Payment should be in CHARGED, PENDING, or FAILURE state (sandbox) but was: {}",
auth_response.status
);
// When setup_future_usage is set, a customer profile is created
// The mandate can be used in subsequent transactions
});
}
| {
"chunk": 9,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_1061119781833247450_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/test_currency.rs
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic, clippy::print_stdout)]
mod tests {
use common_enums::{Currency, CurrencyError};
#[test]
fn test_zero_decimal_currencies() {
// Test currencies that should have 0 decimal places
assert_eq!(
Currency::JPY
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
assert_eq!(
Currency::KRW
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
assert_eq!(
Currency::VND
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
assert_eq!(
Currency::BIF
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
assert_eq!(
Currency::CLP
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
}
#[test]
fn test_two_decimal_currencies() {
// Test currencies that should have 2 decimal places
assert_eq!(
Currency::USD
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
assert_eq!(
Currency::EUR
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
assert_eq!(
Currency::GBP
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
assert_eq!(
Currency::CAD
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
assert_eq!(
Currency::AUD
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
}
#[test]
fn test_three_decimal_currencies() {
// Test currencies that should have 3 decimal places
assert_eq!(
Currency::BHD
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
assert_eq!(
Currency::JOD
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
assert_eq!(
Currency::KWD
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
assert_eq!(
Currency::OMR
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
assert_eq!(
Currency::TND
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
}
#[test]
fn test_four_decimal_currencies() {
// Test currencies that should have 4 decimal places
assert_eq!(
Currency::CLF
.number_of_digits_after_decimal_point()
.unwrap(),
4
);
}
#[test]
fn test_currency_classification_completeness() {
// Test that all currencies in the enum are properly classified
let mut tested_currencies = 0;
let mut successful_classifications = 0;
// We'll iterate through some key currencies to verify they're all classified
let test_currencies = vec![
Currency::USD,
Currency::EUR,
Currency::GBP,
Currency::JPY,
Currency::KRW,
Currency::BHD,
Currency::JOD,
Currency::CLF,
Currency::CNY,
Currency::INR,
Currency::CAD,
Currency::AUD,
Currency::CHF,
Currency::SEK,
Currency::NOK,
Currency::DKK,
Currency::PLN,
Currency::CZK,
Currency::HUF,
Currency::RUB,
];
let mut failed_currencies = Vec::new();
for currency in test_currencies {
tested_currencies += 1;
match currency.number_of_digits_after_decimal_point() {
Ok(_) => successful_classifications += 1,
Err(_) => {
failed_currencies.push(currency);
println!("❌ Currency {currency:?} not properly classified");
}
}
}
// Fail the test if any currencies failed
assert!(
failed_currencies.is_empty(),
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_1061119781833247450_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/test_currency.rs
"The following currencies are not properly classified: {failed_currencies:?}"
);
println!("✅ Tested {tested_currencies} currencies, {successful_classifications} successful classifications");
assert_eq!(
tested_currencies, successful_classifications,
"All tested currencies should be properly classified"
);
}
#[test]
fn test_currency_error_message() {
// Since all current currencies should be classified, we can't easily test
// the error case without adding a fake currency. Instead, let's verify
// the error type exists and can be created
let error = CurrencyError::UnsupportedCurrency {
currency: "TEST".to_string(),
};
let error_string = format!("{error}");
assert!(error_string.contains("Unsupported currency: TEST"));
assert!(error_string.contains("Please add this currency to the supported currency list"));
}
#[test]
fn test_comprehensive_currency_coverage() {
// Test a representative sample from each classification
let currencies_to_test = vec![
// Zero decimal currencies
(Currency::BIF, 0),
(Currency::CLP, 0),
(Currency::DJF, 0),
(Currency::GNF, 0),
(Currency::JPY, 0),
(Currency::KMF, 0),
(Currency::KRW, 0),
(Currency::MGA, 0),
(Currency::PYG, 0),
(Currency::RWF, 0),
(Currency::UGX, 0),
(Currency::VND, 0),
(Currency::VUV, 0),
(Currency::XAF, 0),
(Currency::XOF, 0),
(Currency::XPF, 0),
// Three decimal currencies
(Currency::BHD, 3),
(Currency::JOD, 3),
(Currency::KWD, 3),
(Currency::OMR, 3),
(Currency::TND, 3),
// Four decimal currencies
(Currency::CLF, 4),
// Two decimal currencies (sample)
(Currency::USD, 2),
(Currency::EUR, 2),
(Currency::GBP, 2),
(Currency::AED, 2),
(Currency::AFN, 2),
(Currency::ALL, 2),
(Currency::AMD, 2),
(Currency::ANG, 2),
(Currency::AOA, 2),
];
for (currency, expected_decimals) in currencies_to_test {
match currency.number_of_digits_after_decimal_point() {
Ok(decimals) => {
assert_eq!(decimals, expected_decimals,
"Currency {currency:?} should have {expected_decimals} decimals, got {decimals}");
}
Err(e) => {
panic!("Currency {currency:?} should be classified but got error: {e}");
}
}
}
}
}
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-4265129285553488760_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/common.rs
use std::{future::Future, sync::Arc};
use grpc_api_types::{
health_check::health_client::HealthClient,
payments::{
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
},
};
use http::Uri;
use hyper_util::rt::TokioIo; // Add this import
use tempfile::NamedTempFile;
use tokio::net::UnixListener;
use tokio_stream::wrappers::UnixListenerStream;
use tonic::transport::{Channel, Endpoint, Server};
use tower::service_fn;
pub trait AutoClient {
fn new(channel: Channel) -> Self;
}
impl AutoClient for PaymentServiceClient<Channel> {
fn new(channel: Channel) -> Self {
Self::new(channel)
}
}
impl AutoClient for HealthClient<Channel> {
fn new(channel: Channel) -> Self {
Self::new(channel)
}
}
impl AutoClient for RefundServiceClient<Channel> {
fn new(channel: Channel) -> Self {
Self::new(channel)
}
}
/// # Panics
///
/// Will panic if the socket file cannot be created or removed
pub async fn server_and_client_stub<T>(
service: grpc_server::app::Service,
) -> Result<(impl Future<Output = ()>, T), Box<dyn std::error::Error>>
where
T: AutoClient,
{
let socket = NamedTempFile::new()?;
let socket = Arc::new(socket.into_temp_path());
std::fs::remove_file(&*socket)?;
let uds = UnixListener::bind(&*socket)?;
let stream = UnixListenerStream::new(uds);
let serve_future = async {
let result = Server::builder()
.add_service(
grpc_api_types::health_check::health_server::HealthServer::new(
service.health_check_service,
),
)
.add_service(
grpc_api_types::payments::payment_service_server::PaymentServiceServer::new(
service.payments_service,
),
)
.add_service(
grpc_api_types::payments::refund_service_server::RefundServiceServer::new(
service.refunds_service,
),
)
.serve_with_incoming(stream)
.await;
// Server must be running fine...
assert!(result.is_ok());
};
let socket = Arc::clone(&socket);
// Connect to the server over a Unix socket
// The URL will be ignored.
let channel = Endpoint::try_from("http://any.url")?
.connect_with_connector(service_fn(move |_: Uri| {
let socket = Arc::clone(&socket);
async move {
// Wrap the UnixStream with TokioIo to make it compatible with hyper
let unix_stream = tokio::net::UnixStream::connect(&*socket).await?;
Ok::<_, std::io::Error>(TokioIo::new(unix_stream))
}
}))
.await?;
let client = T::new(channel);
Ok((serve_future, client))
}
#[macro_export]
macro_rules! grpc_test {
($client:ident, $c_type:ty, $body:block) => {
let config = configs::Config::new().expect("Failed while parsing config");
let server = app::Service::new(std::sync::Arc::new(config)).await;
let (server_fut, mut $client) = common::server_and_client_stub::<$c_type>(server)
.await
.expect("Failed to create the server client pair");
let response = async { $body };
tokio::select! {
_ = server_fut => panic!("Server failed"),
_ = response => {}
}
};
}
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8391166333106684163_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/utils/credential_utils.rs
//! Common credential loading utilities for test files
//!
//! This module provides a generic way to load connector credentials from
//! the JSON configuration file (.github/test/creds.json)
#![allow(dead_code)]
use common_enums::enums::Currency;
use common_utils::pii::SecretSerdeValue;
use domain_types::router_data::ConnectorAuthType;
use hyperswitch_masking::Secret;
use std::{collections::HashMap, fs};
// Path to the credentials file - use environment variable if set (for CI), otherwise use relative path (for local)
fn get_creds_file_path() -> String {
std::env::var("CONNECTOR_AUTH_FILE_PATH")
.unwrap_or_else(|_| "../../.github/test/creds.json".to_string())
}
/// Generic credential structure that can deserialize any connector's credentials
#[derive(serde::Deserialize, Debug, Clone)]
pub struct ConnectorAccountDetails {
pub auth_type: String,
#[serde(default)]
pub api_key: Option<String>,
#[serde(default)]
pub key1: Option<String>,
#[serde(default)]
pub api_secret: Option<String>,
#[serde(default)]
pub key2: Option<String>,
#[serde(default)]
pub certificate: Option<String>,
#[serde(default)]
pub private_key: Option<String>,
#[serde(default)]
pub auth_key_map: Option<HashMap<Currency, SecretSerdeValue>>,
}
#[derive(serde::Deserialize, Debug, Clone)]
pub struct ConnectorCredentials {
pub connector_account_details: ConnectorAccountDetails,
#[serde(default)]
pub metadata: Option<serde_json::Value>,
}
/// All connector credentials stored in the JSON file
pub type AllCredentials = HashMap<String, ConnectorCredentials>;
/// Error type for credential loading operations
#[derive(Debug, thiserror::Error)]
pub enum CredentialError {
#[error("Failed to read credentials file: {0}")]
FileReadError(#[from] std::io::Error),
#[error("Failed to parse credentials JSON: {0}")]
ParseError(#[from] serde_json::Error),
#[error("Connector '{0}' not found in credentials")]
ConnectorNotFound(String),
#[error("Invalid auth type '{0}' for connector '{1}'")]
InvalidAuthType(String, String),
#[error("Missing required field '{0}' for auth type '{1}'")]
MissingField(String, String),
#[error("Invalid structure for connector '{0}': {1}")]
InvalidStructure(String, String),
}
/// Load credentials for a specific connector from the JSON configuration file
///
/// # Arguments
/// * `connector_name` - Name of the connector (e.g., "aci", "authorizedotnet")
///
/// # Returns
/// * `ConnectorAuthType` - The loaded and converted credentials
///
/// # Examples
/// ```
/// // Load Authorize.Net credentials
/// let auth = load_connector_auth("authorizedotnet").unwrap();
/// ```
pub fn load_connector_auth(connector_name: &str) -> Result<ConnectorAuthType, CredentialError> {
load_from_json(connector_name)
}
/// Load metadata for a specific connector from the JSON configuration file
///
/// # Arguments
/// * `connector_name` - Name of the connector (e.g., "nexinets", "fiserv")
///
/// # Returns
/// * `HashMap<String, String>` - The metadata key-value pairs, or empty map if no metadata
///
/// # Examples
/// ```
/// // Load connector metadata (e.g., terminal_id, shop_name)
/// let metadata = load_connector_metadata("fiserv").unwrap();
/// let terminal_id = metadata.get("terminal_id");
/// ```
pub fn load_connector_metadata(
connector_name: &str,
) -> Result<HashMap<String, String>, CredentialError> {
let creds_file_path = get_creds_file_path();
let creds_content = fs::read_to_string(&creds_file_path)?;
let json_value: serde_json::Value = serde_json::from_str(&creds_content)?;
let all_credentials = match load_credentials_individually(&json_value) {
Ok(creds) => creds,
Err(_e) => {
// Try standard parsing as fallback
serde_json::from_value(json_value)?
}
};
let connector_creds = all_credentials
.get(connector_name)
.ok_or_else(|| CredentialError::ConnectorNotFound(connector_name.to_string()))?;
match &connector_creds.metadata {
Some(serde_json::Value::Object(map)) => {
let mut result = HashMap::new();
for (key, value) in map {
if let Some(string_val) = value.as_str() {
result.insert(key.clone(), string_val.to_string());
}
}
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8391166333106684163_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/utils/credential_utils.rs
Ok(result)
}
_ => Ok(HashMap::new()),
}
}
/// Load credentials from JSON file
fn load_from_json(connector_name: &str) -> Result<ConnectorAuthType, CredentialError> {
let creds_file_path = get_creds_file_path();
let creds_content = fs::read_to_string(&creds_file_path)?;
let json_value: serde_json::Value = serde_json::from_str(&creds_content)?;
let all_credentials = match load_credentials_individually(&json_value) {
Ok(creds) => creds,
Err(_e) => {
// Try standard parsing as fallback
serde_json::from_value(json_value)?
}
};
let connector_creds = all_credentials
.get(connector_name)
.ok_or_else(|| CredentialError::ConnectorNotFound(connector_name.to_string()))?;
convert_to_auth_type(&connector_creds.connector_account_details, connector_name)
}
/// Load credentials by parsing each connector individually
fn load_credentials_individually(
json_value: &serde_json::Value,
) -> Result<AllCredentials, CredentialError> {
let mut all_credentials = HashMap::new();
let root_object = json_value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
"root".to_string(),
"Expected JSON object at root".to_string(),
)
})?;
for (connector_name, connector_value) in root_object {
match parse_single_connector(connector_name, connector_value) {
Ok(creds) => {
all_credentials.insert(connector_name.clone(), creds);
}
Err(_e) => {
// Continue loading other connectors instead of failing completely
}
}
}
if all_credentials.is_empty() {
return Err(CredentialError::InvalidStructure(
"root".to_string(),
"No valid connectors found".to_string(),
));
}
Ok(all_credentials)
}
/// Parse a single connector's credentials
fn parse_single_connector(
connector_name: &str,
connector_value: &serde_json::Value,
) -> Result<ConnectorCredentials, CredentialError> {
let connector_obj = connector_value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Expected JSON object".to_string(),
)
})?;
// Check if this is a flat structure (has connector_account_details directly)
if connector_obj.contains_key("connector_account_details") {
// Flat structure: connector_name -> { connector_account_details: {...} }
return parse_connector_credentials(connector_name, connector_value);
}
// Nested structure: connector_name -> { connector_1: {...}, connector_2: {...} } eg. stripe
for (_sub_name, sub_value) in connector_obj.iter() {
if let Some(sub_obj) = sub_value.as_object() {
if sub_obj.contains_key("connector_account_details") {
return parse_connector_credentials(connector_name, sub_value);
}
}
}
// If we get here, no valid connector_account_details was found
Err(CredentialError::InvalidStructure(
connector_name.to_string(),
"No connector_account_details found in flat or nested structure".to_string(),
))
}
/// Parse connector credentials from JSON value
fn parse_connector_credentials(
connector_name: &str,
connector_value: &serde_json::Value,
) -> Result<ConnectorCredentials, CredentialError> {
let connector_obj = connector_value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Expected JSON object".to_string(),
)
})?;
let account_details_value =
connector_obj
.get("connector_account_details")
.ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Missing connector_account_details".to_string(),
)
})?;
let account_details = parse_connector_account_details(connector_name, account_details_value)?;
// Parse metadata if present
let metadata = connector_obj
.get("metadata")
.map(|v| serde_json::from_value(v.clone()))
.transpose()?;
Ok(ConnectorCredentials {
connector_account_details: account_details,
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8391166333106684163_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/utils/credential_utils.rs
metadata,
})
}
/// Parse connector account details
fn parse_connector_account_details(
connector_name: &str,
value: &serde_json::Value,
) -> Result<ConnectorAccountDetails, CredentialError> {
let obj = value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"connector_account_details must be an object".to_string(),
)
})?;
// Extract auth_type first
let auth_type = obj
.get("auth_type")
.and_then(|v| v.as_str())
.ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Missing or invalid auth_type".to_string(),
)
})?
.to_string();
// Handle different auth types with specific parsing logic
match auth_type.as_str() {
"CurrencyAuthKey" => {
// Special handling for CurrencyAuthKey which has complex nested structure
parse_currency_auth_key_details(connector_name, obj)
}
_ => {
// For other auth types, use standard serde parsing
serde_json::from_value(value.clone()).map_err(CredentialError::ParseError)
}
}
}
/// Special parsing logic for CurrencyAuthKey auth type
fn parse_currency_auth_key_details(
connector_name: &str,
obj: &serde_json::Map<String, serde_json::Value>,
) -> Result<ConnectorAccountDetails, CredentialError> {
let auth_key_map_value = obj.get("auth_key_map").ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Missing auth_key_map for CurrencyAuthKey".to_string(),
)
})?;
let auth_key_map_obj = auth_key_map_value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"auth_key_map must be an object".to_string(),
)
})?;
let mut auth_key_map = HashMap::new();
for (currency_str, secret_value) in auth_key_map_obj {
let currency = currency_str.parse::<Currency>().map_err(|_| {
CredentialError::InvalidStructure(
connector_name.to_string(),
format!("Invalid currency: {}", currency_str),
)
})?;
let secret_serde_value = SecretSerdeValue::new(secret_value.clone());
auth_key_map.insert(currency, secret_serde_value);
}
Ok(ConnectorAccountDetails {
auth_type: "CurrencyAuthKey".to_string(),
api_key: None,
key1: None,
api_secret: None,
key2: None,
certificate: None,
private_key: None,
auth_key_map: Some(auth_key_map),
})
}
/// Convert generic credential details to specific ConnectorAuthType
fn convert_to_auth_type(
details: &ConnectorAccountDetails,
connector_name: &str,
) -> Result<ConnectorAuthType, CredentialError> {
match details.auth_type.as_str() {
"HeaderKey" => {
let api_key = details.api_key.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_key".to_string(), "HeaderKey".to_string())
})?;
Ok(ConnectorAuthType::HeaderKey {
api_key: Secret::new(api_key.clone()),
})
}
"BodyKey" => {
let api_key = details.api_key.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_key".to_string(), "BodyKey".to_string())
})?;
let key1 = details.key1.as_ref().ok_or_else(|| {
CredentialError::MissingField("key1".to_string(), "BodyKey".to_string())
})?;
Ok(ConnectorAuthType::BodyKey {
api_key: Secret::new(api_key.clone()),
key1: Secret::new(key1.clone()),
})
}
"SignatureKey" => {
let api_key = details.api_key.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_key".to_string(), "SignatureKey".to_string())
})?;
let key1 = details.key1.as_ref().ok_or_else(|| {
CredentialError::MissingField("key1".to_string(), "SignatureKey".to_string())
})?;
let api_secret = details.api_secret.as_ref().ok_or_else(|| {
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8391166333106684163_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/utils/credential_utils.rs
CredentialError::MissingField("api_secret".to_string(), "SignatureKey".to_string())
})?;
Ok(ConnectorAuthType::SignatureKey {
api_key: Secret::new(api_key.clone()),
key1: Secret::new(key1.clone()),
api_secret: Secret::new(api_secret.clone()),
})
}
"MultiAuthKey" => {
let api_key = details.api_key.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_key".to_string(), "MultiAuthKey".to_string())
})?;
let key1 = details.key1.as_ref().ok_or_else(|| {
CredentialError::MissingField("key1".to_string(), "MultiAuthKey".to_string())
})?;
let api_secret = details.api_secret.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_secret".to_string(), "MultiAuthKey".to_string())
})?;
let key2 = details.key2.as_ref().ok_or_else(|| {
CredentialError::MissingField("key2".to_string(), "MultiAuthKey".to_string())
})?;
Ok(ConnectorAuthType::MultiAuthKey {
api_key: Secret::new(api_key.clone()),
key1: Secret::new(key1.clone()),
api_secret: Secret::new(api_secret.clone()),
key2: Secret::new(key2.clone()),
})
}
"CurrencyAuthKey" => {
// For CurrencyAuthKey, we expect the auth_key_map field to contain the mapping
let auth_key_map = details.auth_key_map.as_ref().ok_or_else(|| {
CredentialError::MissingField(
"auth_key_map".to_string(),
"CurrencyAuthKey".to_string(),
)
})?;
Ok(ConnectorAuthType::CurrencyAuthKey {
auth_key_map: auth_key_map.clone(),
})
}
"CertificateAuth" => {
let certificate = details.certificate.as_ref().ok_or_else(|| {
CredentialError::MissingField(
"certificate".to_string(),
"CertificateAuth".to_string(),
)
})?;
let private_key = details.private_key.as_ref().ok_or_else(|| {
CredentialError::MissingField(
"private_key".to_string(),
"CertificateAuth".to_string(),
)
})?;
Ok(ConnectorAuthType::CertificateAuth {
certificate: Secret::new(certificate.clone()),
private_key: Secret::new(private_key.clone()),
})
}
"NoKey" => Ok(ConnectorAuthType::NoKey),
"TemporaryAuth" => Ok(ConnectorAuthType::TemporaryAuth),
_ => Err(CredentialError::InvalidAuthType(
details.auth_type.clone(),
connector_name.to_string(),
)),
}
}
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8239156977382081034_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/dlocal_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::{
collections::HashMap,
str::FromStr,
time::{Duration, SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
Address, AuthenticationType, BrowserInformation, CaptureMethod, CardDetails,
CardPaymentMethodType, CountryAlpha2, Currency, Identifier, PaymentAddress, PaymentMethod,
PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundServiceGetRequest, RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tokio::time::sleep;
use tonic::{transport::Channel, Request};
// Constants for dlocal connector
const CONNECTOR_NAME: &str = "dlocal";
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "5105105105105100";
const TEST_CARD_EXP_MONTH: &str = "10";
const TEST_CARD_EXP_YEAR: &str = "2040";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add dlocal metadata headers to a request
fn add_dlocal_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load dlocal credentials");
let (api_key, key1, api_secret) = match auth {
domain_types::router_data::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => (api_key.expose(), key1.expose(), api_secret.expose()),
_ => panic!("Expected SignatureKey auth type for dlocal"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"signature-key".parse().expect("Failed to parse x-auth"),
);
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-api-secret",
api_secret.parse().expect("Failed to parse x-api-secret"),
);
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to extract transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to create a payment authorization request
#[allow(clippy::field_reassign_with_default)]
fn create_payment_authorize_request(
capture_method: common_enums::CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
// Initialize with all required fields
let mut request = PaymentServiceAuthorizeRequest::default();
// Set request reference ID
let mut request_ref_id = Identifier::default();
request_ref_id.id_type = Some(IdType::Id(format!("dlocal_test_{}", get_timestamp())));
request.request_ref_id = Some(request_ref_id);
// Set the basic payment details
request.amount = TEST_AMOUNT;
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8239156977382081034_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/dlocal_payment_flows_test.rs
request.minor_amount = TEST_AMOUNT;
request.currency = i32::from(Currency::Myr);
// Set up card payment method using the correct structure
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1_i32), // Default to Visa network
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
request.payment_method = Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
});
// Set connector customer ID
request.customer_id = Some("TEST_CONNECTOR".to_string());
// Set the customer information with static email (can be made dynamic)
request.email = Some(TEST_EMAIL.to_string().into());
// Set up address structure
request.address = Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some("Test".to_string().into()),
last_name: Some("User".to_string().into()),
line1: Some("123 Test Street".to_string().into()),
line2: None,
line3: None,
city: Some("Test City".to_string().into()),
state: Some("NY".to_string().into()),
zip_code: Some("10001".to_string().into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::My)),
phone_number: None,
phone_country_code: None,
email: None,
}),
shipping_address: None,
});
// Set up browser information
let browser_info = BrowserInformation {
color_depth: None,
java_enabled: Some(false),
screen_height: Some(1080),
screen_width: Some(1920),
user_agent: Some("Mozilla/5.0 (compatible; TestAgent/1.0)".to_string()),
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(),
),
java_script_enabled: Some(false),
language: Some("en-US".to_string()),
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
time_zone_offset_minutes: None,
referer: None,
};
request.browser_info = Some(browser_info);
// Set return URL
request.return_url = Some("https://example.com/return".to_string());
// Set the transaction details
request.auth_type = i32::from(AuthenticationType::NoThreeDs);
request.request_incremental_authorization = true;
request.enrolled_for_3ds = true;
// Set capture method with proper conversion
if let common_enums::CaptureMethod::Manual = capture_method {
request.capture_method = Some(i32::from(CaptureMethod::Manual));
} else {
request.capture_method = Some(i32::from(CaptureMethod::Automatic));
}
// Set connector metadata (empty for generic template)
request.metadata = HashMap::new();
request
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("dlocal_sync_{}", get_timestamp()))),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Myr),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8239156977382081034_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/dlocal_payment_flows_test.rs
currency: i32::from(Currency::Myr),
multiple_capture_data: None,
connector_metadata: HashMap::new(),
request_ref_id: None,
browser_info: None,
capture_method: None,
state: None,
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Myr),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
webhook_url: None,
metadata: HashMap::new(),
refund_metadata: HashMap::new(),
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
state: None,
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
browser_info: None,
request_ref_id: None,
refund_metadata: HashMap::new(),
state: None,
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: Some("Customer requested cancellation".to_string()),
request_ref_id: None,
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_dlocal_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Verify the response
assert!(
response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&response);
// Verify payment status - in sandbox, payments may be rejected
let acceptable_statuses = [i32::from(PaymentStatus::Charged)];
assert!(
acceptable_statuses.contains(&response.status),
"Payment should be in CHARGED state (sandbox). Got status: {}",
response.status
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_dlocal_metadata(&mut auth_grpc_request);
// Send the auth request
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8239156977382081034_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/dlocal_payment_flows_test.rs
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&auth_response);
// Verify payment status - in sandbox, payments may be rejected
let acceptable_auth_statuses = [i32::from(PaymentStatus::Authorized)];
assert!(
acceptable_auth_statuses.contains(&auth_response.status),
"Payment should be in AUTHORIZED state (sandbox). Got status: {}",
auth_response.status
);
});
}
// Test payment sync
#[tokio::test]
async fn test_payment_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to sync
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_dlocal_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Add 5-second delay before sync request
sleep(Duration::from_secs(5)).await;
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_dlocal_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response - in sandbox, payments may be rejected
let acceptable_sync_statuses = [i32::from(PaymentStatus::Authorized)];
assert!(
acceptable_sync_statuses.contains(&sync_response.status),
"Payment should be in AUTHORIZED state (sandbox). Got status: {}",
sync_response.status
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_dlocal_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status - in sandbox, payments may be rejected
let acceptable_capture_auth_statuses = [i32::from(PaymentStatus::Authorized)];
assert!(
acceptable_capture_auth_statuses.contains(&auth_response.status),
"Payment should be in AUTHORIZED state (sandbox). Got status: {}",
auth_response.status
);
// Add 5-second delay before capture request
sleep(Duration::from_secs(5)).await;
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_dlocal_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8239156977382081034_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/dlocal_payment_flows_test.rs
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status after capture - in sandbox, may still be rejected
let acceptable_capture_statuses = [i32::from(PaymentStatus::Charged)];
assert!(
acceptable_capture_statuses.contains(&capture_response.status),
"Payment should be in CHARGED state (sandbox). Got status: {}",
capture_response.status
);
});
}
// Test refund flow
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to refund
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_dlocal_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status - in sandbox, payments may be rejected
let acceptable_payment_statuses = [i32::from(PaymentStatus::Charged)];
assert!(
acceptable_payment_statuses.contains(&auth_response.status),
"Payment should be in CHARGED state (sandbox). Got status: {}",
auth_response.status
);
// Add 5-second delay before refund request
sleep(Duration::from_secs(5)).await;
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_dlocal_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Extract the refund ID
let refund_id = refund_response.refund_id.clone();
// Verify the refund response
assert!(!refund_id.is_empty(), "Refund ID should not be empty");
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in SUCCESS state"
);
});
}
// Test refund sync flow
#[tokio::test]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// First create a payment
let auth_request =
create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_dlocal_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Add 5-second delay before refund request
sleep(Duration::from_secs(5)).await;
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_dlocal_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Extract the refund ID
let refund_id = refund_response.refund_id.clone();
// Verify the refund response
assert!(!refund_id.is_empty(), "Refund ID should not be empty");
// Add 5-second delay before refund sync request
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8239156977382081034_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/dlocal_payment_flows_test.rs
sleep(Duration::from_secs(5)).await;
// Create refund sync request
let refund_sync_request = create_refund_sync_request(&transaction_id, &refund_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_dlocal_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request
let refund_sync_response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund_sync call failed")
.into_inner();
// Verify the refund sync response
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in SUCCESS state"
);
});
});
}
// Test payment void flow
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture (so it stays in authorized state)
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_dlocal_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status - in sandbox, payments may be rejected
let acceptable_void_auth_statuses = [i32::from(PaymentStatus::Authorized)];
assert!(
acceptable_void_auth_statuses.contains(&auth_response.status),
"Payment should be in AUTHORIZED state (sandbox). Got status: {}",
auth_response.status
);
// Add 5-second delay before void request
sleep(Duration::from_secs(5)).await;
// Create void request
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_dlocal_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC payment_void call failed")
.into_inner();
// Verify the void response - in sandbox, may have different statuses
let acceptable_void_statuses = [i32::from(PaymentStatus::Voided)];
assert!(
acceptable_void_statuses.contains(&void_response.status),
"Payment should be in VOIDED state (sandbox). Got status: {}",
void_response.status
);
});
}
| {
"chunk": 5,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-3379426412121211531_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/nexinets_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::{
collections::HashMap,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentStatus, RefundResponse, RefundServiceGetRequest, RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
// Constants for Nexinets connector
const CONNECTOR_NAME: &str = "nexinets";
const AUTH_TYPE: &str = "body-key";
const MERCHANT_ID: &str = "12abc123-f8a3-99b8-9ef8-b31180358hh4";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4111111111111111"; // Valid test card for Nexinets
const TEST_CARD_EXP_MONTH: &str = "10";
const TEST_CARD_EXP_YEAR: &str = "25";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add Nexinets metadata headers to a request
fn add_nexinets_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load nexinets credentials");
let (api_key, key1) = match auth {
domain_types::router_data::ConnectorAuthType::BodyKey { api_key, key1 } => {
(api_key.expose(), key1.expose())
}
_ => panic!("Expected BodyKey auth type for nexinets"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to extract connector Refund ID from response
fn extract_refund_id(response: &RefundResponse) -> &String {
&response.refund_id
}
// Helper function to extract connector request ref ID from response
fn extract_request_ref_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.response_ref_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector response_ref_id"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to create a payment authorize request
fn create_payment_authorize_request(
capture_method: CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-3379426412121211531_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/nexinets_payment_flows_test.rs
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_network: Some(1),
card_issuer: None,
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some("https://duck.com".to_string()),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress::default()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("nexinets_test_{}", get_timestamp()))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(
transaction_id: &str,
request_ref_id: &str,
) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(request_ref_id.to_string())),
}),
// all_keys_required: None,
capture_method: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
handle_response: None,
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(
transaction_id: &str,
request_ref_id: &str,
) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
multiple_capture_data: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(request_ref_id.to_string())),
}),
..Default::default()
}
}
// Helper function to create a refund request
fn create_refund_request(
transaction_id: &str,
request_ref_id: &str,
) -> PaymentServiceRefundRequest {
// Create connector metadata as a proper JSON object
let mut connector_metadata = HashMap::new();
connector_metadata.insert("order_id".to_string(), request_ref_id);
let connector_metadata_json =
serde_json::to_string(&connector_metadata).expect("Failed to serialize connector metadata");
let mut metadata = HashMap::new();
metadata.insert("connector_metadata".to_string(), connector_metadata_json);
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Eur),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
webhook_url: None,
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
metadata,
..Default::default()
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(
transaction_id: &str,
refund_id: &str,
request_ref_id: &str,
) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-3379426412121211531_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/nexinets_payment_flows_test.rs
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(request_ref_id.to_string())),
}),
browser_info: None,
refund_metadata: HashMap::new(),
state: None,
}
}
// Helper function to visit 3DS authentication URL using reqwest
async fn visit_3ds_authentication_url(
request_ref_id: &str,
) -> Result<(), Box<dyn std::error::Error>> {
// Get the key1 value from auth credentials for the URL
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load nexinets credentials");
let key1 = match auth {
domain_types::router_data::ConnectorAuthType::BodyKey { key1, .. } => key1.expose(),
_ => panic!("Expected BodyKey auth type for nexinets"),
};
// Construct the 3DS authentication URL with correct format
let url = format!("https://pptest.payengine.de/three-ds-v2-order/{key1}/{request_ref_id}",);
// Create reqwest client with timeout and proper TLS configuration
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.danger_accept_invalid_certs(false) // Keep TLS verification enabled
.user_agent("nexinets-test-client/1.0")
.build()?;
// Send GET request
let response = client.get(&url).send().await?;
// Read response body for additional debugging (optional)
let body = response.text().await?;
// Log first 200 characters of response for debugging (if not empty)
if !body.is_empty() {
let _preview = if body.len() > 200 {
&body[..200]
} else {
&body
};
}
Ok(())
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_nexinets_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Verify the response
assert!(
response.transaction_id.is_some(),
"Resource ID should be present"
);
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending)
|| response.status == i32::from(PaymentStatus::Pending)
|| response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AuthenticationPending or Pending state"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 2 seconds
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_nexinets_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Extract the request ref ID which is Order_id for nexinets
let request_ref_id = extract_request_ref_id(&auth_response);
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-3379426412121211531_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/nexinets_payment_flows_test.rs
let mut final_payment_status = auth_response.status;
// Check if payment requires 3DS authentication
if auth_response.status == i32::from(PaymentStatus::AuthenticationPending) {
// Visit the 3DS authentication URL to simulate user completing authentication
let _ = visit_3ds_authentication_url(&request_ref_id).await;
// Wait a moment for the authentication state to be updated
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
// Sync the payment to get updated status after 3DS authentication
let sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
let mut sync_grpc_request = Request::new(sync_request);
add_nexinets_metadata(&mut sync_grpc_request);
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
final_payment_status = sync_response.status;
// Note: Simply visiting the 3DS URL doesn't complete the authentication
// The payment may still be in AuthenticationPending state
// In a real scenario, the user would interact with the 3DS page
// For testing purposes, we'll accept either AuthenticationPending or Authorized
assert!(
final_payment_status == i32::from(PaymentStatus::Authorized)
|| final_payment_status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AUTHORIZED or still AUTHENTICATION_PENDING state after visiting 3DS URL. Current status: {final_payment_status}",
);
} else {
// Verify payment status is authorized (for manual capture without 3DS)
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture"
);
}
// Only proceed with capture if payment is in Authorized state
// If still in AuthenticationPending, skip capture as it requires user
// interaction
if final_payment_status == i32::from(PaymentStatus::Authorized) {
// Create capture request (which already includes proper connector metadata)
let capture_request = create_payment_capture_request(&transaction_id, &request_ref_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_nexinets_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
}
});
}
// Test payment sync
#[tokio::test]
async fn test_payment_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 4 seconds
tokio::time::sleep(std::time::Duration::from_secs(4)).await;
// First create a payment to sync
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_nexinets_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Extract the request ref ID which is Order_id for nexinets
let request_ref_id = extract_request_ref_id(&auth_response);
// Check if payment requires 3DS authentication
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-3379426412121211531_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/nexinets_payment_flows_test.rs
if auth_response.status == i32::from(PaymentStatus::AuthenticationPending) {
let _ = visit_3ds_authentication_url(&request_ref_id).await;
// Wait a moment for the authentication state to be updated
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
}
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_nexinets_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// For testing purposes, we'll accept AuthenticationPending or Authorized
assert!(
sync_response.status == i32::from(PaymentStatus::Authorized)
|| sync_response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AUTHORIZED or AUTHENTICATION_PENDING state. Current status: {}",
sync_response.status
);
});
}
// Test refund flow - handles both success and error cases
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 6 seconds
tokio::time::sleep(std::time::Duration::from_secs(6)).await;
// Create the payment authorization request
let request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_nexinets_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
// Extract the request ref ID which is Order_id for nexinets
let request_ref_id = extract_request_ref_id(&response);
// Check if payment requires 3DS authentication
if response.status == i32::from(PaymentStatus::AuthenticationPending) {
let _ = visit_3ds_authentication_url(&request_ref_id).await;
// Wait a moment for the authentication state to be updated
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
// Sync the payment to get updated status after 3DS authentication
let sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
let mut sync_grpc_request = Request::new(sync_request);
add_nexinets_metadata(&mut sync_grpc_request);
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
assert!(
sync_response.status == i32::from(PaymentStatus::Charged)
|| sync_response.status == i32::from(PaymentStatus::Authorized)
|| sync_response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in CHARGED, AUTHORIZED, or AUTHENTICATION_PENDING state after 3DS URL visit. Current status: {}",
sync_response.status
);
} else {
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending)
|| response.status == i32::from(PaymentStatus::Pending)
|| response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AuthenticationPending or Pending state"
);
}
// Wait a bit longer to ensure the payment is fully processed
tokio::time::sleep(tokio::time::Duration::from_secs(12)).await;
// Only attempt refund if payment is in a refundable state
// Check final payment status to determine if refund is possible
let final_sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
| {
"chunk": 4,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-3379426412121211531_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/nexinets_payment_flows_test.rs
let mut final_sync_grpc_request = Request::new(final_sync_request);
add_nexinets_metadata(&mut final_sync_grpc_request);
let final_sync_response = client
.get(final_sync_grpc_request)
.await
.expect("gRPC final payment_sync call failed")
.into_inner();
if final_sync_response.status == i32::from(PaymentStatus::Charged)
|| final_sync_response.status == i32::from(PaymentStatus::Authorized)
{
// Create refund request
let refund_request = create_refund_request(&transaction_id, &request_ref_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_nexinets_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in RefundSuccess state"
);
}
});
}
// Test refund sync flow - runs as a separate test since refund + sync is
// complex
#[tokio::test]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// Add delay of 8 seconds
tokio::time::sleep(std::time::Duration::from_secs(8)).await;
// First create a payment
let auth_request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_nexinets_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Extract the request ref ID which is Order_id for nexinets
let request_ref_id = extract_request_ref_id(&auth_response);
// Check if payment requires 3DS authentication
if auth_response.status == i32::from(PaymentStatus::AuthenticationPending) {
let _ = visit_3ds_authentication_url(&request_ref_id).await;
// Wait a moment for the authentication state to be updated
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
} else {
// Wait for payment to process
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
}
// Create sync request to check payment status
let sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_nexinets_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
assert!(
sync_response.status == i32::from(PaymentStatus::Charged)
|| sync_response.status == i32::from(PaymentStatus::Authorized)
|| sync_response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in CHARGED, AUTHORIZED, or AUTHENTICATION_PENDING state. Current status: {}",
sync_response.status
);
// Only attempt refund if payment is in a refundable state
if sync_response.status == i32::from(PaymentStatus::Charged)
|| sync_response.status == i32::from(PaymentStatus::Authorized)
{
// Create refund request
| {
"chunk": 5,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-3379426412121211531_6 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/nexinets_payment_flows_test.rs
let refund_request = create_refund_request(&transaction_id, &request_ref_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_nexinets_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Verify the refund response
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in RefundSuccess state"
);
let refund_id = extract_refund_id(&refund_response);
// Wait a bit longer to ensure the refund is fully processed
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
// Create refund sync request with our mock ID
let refund_sync_request =
create_refund_sync_request(&transaction_id, refund_id, &request_ref_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_nexinets_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request
let refund_sync_response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund sync call failed")
.into_inner();
// Verify the refund sync response
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund Sync should be in RefundSuccess state"
);
}
});
});
}
| {
"chunk": 6,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6064476266321129275_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/aci_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
use hyperswitch_masking::{ExposeInterface, Secret};
mod common;
mod utils;
use std::{
collections::HashMap,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, AcceptanceType, Address, AuthenticationType,
BrowserInformation, CaptureMethod, CardDetails, CardPaymentMethodType, CountryAlpha2,
Currency, CustomerAcceptance, FutureUsage, Identifier, MandateReference, PaymentAddress,
PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceRegisterRequest, PaymentServiceRepeatEverythingRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundStatus,
},
};
use tonic::{transport::Channel, Request};
// Constants for aci connector
const CONNECTOR_NAME: &str = "aci";
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4111111111111111";
const TEST_CARD_EXP_MONTH: &str = "10";
const TEST_CARD_EXP_YEAR: &str = "2030";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add aci metadata headers to a request
fn add_aci_metadata<T>(request: &mut Request<T>) {
// Get API credentials using the common credential loading utility
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load ACI credentials");
let (api_key, key1) = match auth {
domain_types::router_data::ConnectorAuthType::BodyKey { api_key, key1 } => {
(api_key.expose(), key1.expose())
}
_ => panic!("Expected BodyKey auth type for ACI"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"body-key".parse().expect("Failed to parse x-auth"),
);
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
request.metadata_mut().append(
"x-connector-request-reference-id",
format!("conn_ref_{}", get_timestamp())
.parse()
.expect("Failed to parse x-connector-request-reference-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to create a payment authorization request
#[allow(clippy::field_reassign_with_default)]
fn create_payment_authorize_request(
capture_method: common_enums::CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
// Initialize with all required fields
let mut request = PaymentServiceAuthorizeRequest::default();
// Set request reference ID
request.request_ref_id = Some(Identifier {
id_type: Some(IdType::Id(format!("aci_test_{}", get_timestamp()))),
});
| {
"chunk": 0,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6064476266321129275_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/aci_payment_flows_test.rs
// Set the basic payment details
request.amount = TEST_AMOUNT;
request.minor_amount = TEST_AMOUNT;
request.currency = i32::from(Currency::Usd);
// Set up card payment method using the correct structure
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1_i32), // Default to Visa network
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
request.payment_method = Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
});
// Set connector customer ID
request.customer_id = Some("TEST_CONNECTOR".to_string());
// Set the customer information with static email (can be made dynamic)
request.email = Some(TEST_EMAIL.to_string().into());
// Set up address structure
request.address = Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some("Test".to_string().into()),
last_name: Some("User".to_string().into()),
line1: Some("123 Test Street".to_string().into()),
line2: None,
line3: None,
city: Some("Test City".to_string().into()),
state: Some("NY".to_string().into()),
zip_code: Some("10001".to_string().into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
phone_number: None,
phone_country_code: None,
email: None,
}),
shipping_address: None,
});
// Set up browser information
let browser_info = BrowserInformation {
color_depth: None,
java_enabled: Some(false),
screen_height: Some(1080),
screen_width: Some(1920),
user_agent: Some("Mozilla/5.0 (compatible; TestAgent/1.0)".to_string()),
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(),
),
java_script_enabled: Some(false),
language: Some("en-US".to_string()),
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
time_zone_offset_minutes: None,
referer: None,
};
request.browser_info = Some(browser_info);
// Set return URL
request.return_url = Some("https://example.com/return".to_string());
// Set the transaction details
request.auth_type = i32::from(AuthenticationType::NoThreeDs);
request.request_incremental_authorization = true;
request.enrolled_for_3ds = true;
// Set capture method with proper conversion
if let common_enums::CaptureMethod::Manual = capture_method {
request.capture_method = Some(i32::from(CaptureMethod::Manual));
} else {
request.capture_method = Some(i32::from(CaptureMethod::Automatic));
}
// Set connector metadata (empty for generic template)
request.metadata = HashMap::new();
request
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("aci_sync_{}", get_timestamp()))),
}),
capture_method: Some(i32::from(CaptureMethod::Automatic)),
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
| {
"chunk": 1,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6064476266321129275_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/aci_payment_flows_test.rs
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
connector_metadata: HashMap::new(),
request_ref_id: None,
browser_info: None,
capture_method: None,
state: None,
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
webhook_url: None,
metadata: HashMap::new(),
refund_metadata: HashMap::new(),
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
state: None,
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: Some("Customer requested cancellation".to_string()),
request_ref_id: None,
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
// Helper function to create a register (setup mandate) request
fn create_register_request() -> PaymentServiceRegisterRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1_i32), // Visa network
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
PaymentServiceRegisterRequest {
minor_amount: Some(TEST_AMOUNT),
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
customer_name: Some(TEST_CARD_HOLDER.to_string()),
email: Some(TEST_EMAIL.to_string().into()),
customer_acceptance: Some(CustomerAcceptance {
acceptance_type: i32::from(AcceptanceType::Offline),
accepted_at: 0,
online_mandate_details: None,
}),
address: Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some("Test".to_string().into()),
last_name: Some("Customer".to_string().into()),
line1: Some("123 Test St".to_string().into()),
line2: None,
line3: None,
city: Some("Test City".to_string().into()),
state: Some("NY".to_string().into()),
zip_code: Some("10001".to_string().into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
phone_number: None,
phone_country_code: None,
email: Some(TEST_EMAIL.to_string().into()),
}),
shipping_address: None,
}),
auth_type: i32::from(AuthenticationType::NoThreeDs),
setup_future_usage: Some(i32::from(FutureUsage::OffSession)),
enrolled_for_3ds: false,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("mandate_{}", get_timestamp()))),
}),
metadata: HashMap::new(),
..Default::default()
}
}
// Helper function to create a repeat payment request (matching your JSON format)
| {
"chunk": 2,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6064476266321129275_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/aci_payment_flows_test.rs
#[allow(clippy::field_reassign_with_default)]
fn create_repeat_payment_request(mandate_id: &str) -> PaymentServiceRepeatEverythingRequest {
let mandate_reference = MandateReference {
mandate_id: Some(mandate_id.to_string()),
payment_method_id: None,
};
// Create metadata matching your JSON format
let mut metadata = HashMap::new();
metadata.insert("order_type".to_string(), "recurring".to_string());
metadata.insert(
"customer_note".to_string(),
"Monthly subscription payment".to_string(),
);
PaymentServiceRepeatEverythingRequest {
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("mandate_{}", get_timestamp()))),
}),
mandate_reference: Some(mandate_reference),
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
minor_amount: TEST_AMOUNT,
merchant_order_reference_id: Some(format!("repeat_order_{}", get_timestamp())),
metadata,
webhook_url: Some("https://your-webhook-url.com/payments/webhook".to_string()),
capture_method: None,
email: None,
browser_info: None,
test_mode: None,
payment_method_type: None,
merchant_account_metadata: HashMap::new(),
state: None,
..Default::default()
}
}
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_aci_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Verify the response
assert!(
response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&response);
// Verify payment status
assert_eq!(
response.status,
i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state for automatic capture"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_aci_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized (for manual capture)
assert_eq!(
auth_response.status,
i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture"
);
});
}
// Test payment sync
#[tokio::test]
async fn test_payment_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to sync
| {
"chunk": 3,
"crate": "grpc-server",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.