id stringlengths 20 153 | type stringclasses 1
value | granularity stringclasses 14
values | content stringlengths 16 84.3k | metadata dict |
|---|---|---|---|---|
connector-service_mini_connector-integration_6700735980109314159_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/xendit/transformers.rs
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<XenditCaptureResponse, Self>,
) -> Result<Self, Self::Error> {
let status = common_enums::AttemptStatus::from(item.response.status);
let response = if status == common_enums::AttemptStatus::Failure {
Err(ErrorResponse {
code: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_CODE.to_string()),
message: item
.response
.failure_code
.clone()
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
reason: Some(
item.response
.failure_code
.unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
),
attempt_status: None,
connector_transaction_id: None,
status_code: item.http_code,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(
item.response.reference_id.peek().to_string(),
),
incremental_authorization_allowed: None,
status_code: item.http_code,
})
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct XenditRefundRequest {
pub amount: FloatMajorUnit,
pub payment_request_id: String,
pub reason: String,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<XenditRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>>
for XenditRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: XenditRouterData<
RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let amount = XenditAmountConvertor::convert(
item.router_data.request.minor_refund_amount,
item.router_data.request.currency,
)
.change_context(ConnectorError::RequestEncodingFailed)?;
Ok(Self {
amount: amount.to_owned(),
payment_request_id: item.router_data.request.connector_transaction_id.clone(),
reason: "REQUESTED_BY_CUSTOMER".to_string(),
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub status: RefundStatus,
pub amount: FloatMajorUnit,
pub currency: Currency,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
RequiresAction,
Succeeded,
Failed,
Pending,
Cancelled,
}
impl<F> TryFrom<ResponseRouterData<RefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundResponse, Self>) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let response_amount =
XenditAmountConvertor::convert_back(response.amount, response.currency)?;
let response_integrity_object = {
Some(RefundIntegrityObject {
refund_amount: response_amount,
currency: response.currency,
})
};
Ok(Self {
response: Ok(RefundsResponseData {
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_6700735980109314159_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/xendit/transformers.rs
connector_refund_id: response.id,
refund_status: common_enums::RefundStatus::from(response.status),
status_code: http_code,
}),
request: RefundsData {
integrity_object: response_integrity_object,
..router_data.request
},
..router_data
})
}
}
impl From<RefundStatus> for common_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed | RefundStatus::Cancelled => Self::Failure,
RefundStatus::Pending | RefundStatus::RequiresAction => Self::Pending,
}
}
}
impl<F> TryFrom<ResponseRouterData<RefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundResponse, Self>) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: response.id,
refund_status: common_enums::RefundStatus::from(response.status),
status_code: http_code,
}),
..router_data
})
}
}
fn is_mandate_payment<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
item: &PaymentsAuthorizeData<T>,
) -> bool {
(item.setup_future_usage == Some(common_enums::enums::FutureUsage::OffSession))
|| item
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
| {
"chunk": 6,
"crate": "connector-integration",
"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_connector-integration_26567170429461802_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/volt/transformers.rs
use common_enums::{self, AttemptStatus, Currency};
use common_utils::{consts, id_type::CustomerId, request::Method, types::MinorUnit};
use domain_types::{
connector_flow::{Authorize, CreateAccessToken, PSync},
connector_types::{
AccessTokenRequestData, AccessTokenResponseData, PaymentFlowData, PaymentsAuthorizeData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundsData, RefundsResponseData,
ResponseId,
},
errors,
payment_method_data::{BankRedirectData, PaymentMethodData, PaymentMethodDataTypes},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
utils,
};
use hyperswitch_masking::{ExposeInterface, Secret};
use interfaces::webhooks::IncomingWebhookEvent;
use serde::{Deserialize, Serialize};
use crate::{connectors::volt::VoltRouterData, types::ResponseRouterData};
// Type alias for refunds router data following existing patterns
pub type RefundsResponseRouterData<F, T> =
ResponseRouterData<T, RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>>;
// Empty request type for PSync GET requests
#[derive(Debug, Serialize, Default)]
pub struct VoltPsyncRequest;
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
VoltRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
> for VoltPsyncRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
_item: VoltRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self)
}
}
fn get_attempt_status((item, current_status): (VoltPaymentStatus, AttemptStatus)) -> AttemptStatus {
match item {
VoltPaymentStatus::Received | VoltPaymentStatus::Settled => AttemptStatus::Charged,
VoltPaymentStatus::Completed | VoltPaymentStatus::DelayedAtBank => AttemptStatus::Pending,
VoltPaymentStatus::NewPayment
| VoltPaymentStatus::BankRedirect
| VoltPaymentStatus::AwaitingCheckoutAuthorisation => AttemptStatus::AuthenticationPending,
VoltPaymentStatus::RefusedByBank
| VoltPaymentStatus::RefusedByRisk
| VoltPaymentStatus::NotReceived
| VoltPaymentStatus::ErrorAtBank
| VoltPaymentStatus::CancelledByUser
| VoltPaymentStatus::AbandonedByUser
| VoltPaymentStatus::Failed => AttemptStatus::Failure,
VoltPaymentStatus::Unknown => current_status,
}
}
const PASSWORD: &str = "password";
pub mod webhook_headers {
pub const X_VOLT_SIGNED: &str = "X-Volt-Signed";
pub const X_VOLT_TIMED: &str = "X-Volt-Timed";
pub const USER_AGENT: &str = "User-Agent";
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsRequest {
amount: MinorUnit,
currency_code: Currency,
#[serde(rename = "type")]
transaction_type: TransactionType,
merchant_internal_reference: String,
shopper: ShopperDetails,
payment_success_url: Option<String>,
payment_failure_url: Option<String>,
payment_pending_url: Option<String>,
payment_cancel_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionType {
Bills,
Goods,
PersonToPerson,
Other,
Services,
}
#[derive(Debug, Serialize)]
pub struct ShopperDetails {
reference: common_utils::id_type::CustomerId,
email: Option<common_utils::pii::Email>,
first_name: Secret<String>,
last_name: Secret<String>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ serde::Serialize,
>
TryFrom<
VoltRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for VoltPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: VoltRouterData<
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_26567170429461802_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/volt/transformers.rs
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
PaymentMethodData::BankRedirect(bank_redirect) => match bank_redirect {
BankRedirectData::OpenBankingUk { .. } => {
let amount = item.router_data.request.amount;
let currency_code = item.router_data.request.currency;
let merchant_internal_reference = item
.router_data
.resource_common_data
.connector_request_reference_id
.clone();
let payment_success_url = item.router_data.request.router_return_url.clone();
let payment_failure_url = item.router_data.request.router_return_url.clone();
let payment_pending_url = item.router_data.request.router_return_url.clone();
let payment_cancel_url = item.router_data.request.router_return_url.clone();
let shopper = ShopperDetails {
email: item.router_data.request.email.clone(),
first_name: item
.router_data
.resource_common_data
.get_billing_first_name()?,
last_name: item
.router_data
.resource_common_data
.get_billing_last_name()?,
reference: item
.router_data
.resource_common_data
.get_customer_id()
.unwrap_or_else(|_| CustomerId::default()),
};
let transaction_type = TransactionType::Services; //transaction_type is a form of enum, it is pre defined and value for this can not be taken from user so we are keeping it as Services as this transaction is type of service.
Ok(Self {
amount: MinorUnit::new(amount),
currency_code,
merchant_internal_reference,
payment_success_url,
payment_failure_url,
payment_pending_url,
payment_cancel_url,
shopper,
transaction_type,
})
}
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Eps { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Ideal { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Sofort { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
)
.into())
}
},
PaymentMethodData::Card(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_26567170429461802_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/volt/transformers.rs
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
)
.into())
}
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct VoltAuthUpdateRequest {
grant_type: String,
client_id: Secret<String>,
client_secret: Secret<String>,
username: Secret<String>,
password: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for VoltAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
let auth = VoltAuthType::try_from(auth_type)?;
Ok(Self {
grant_type: PASSWORD.to_string(),
username: auth.username,
password: auth.password,
client_id: auth.client_id,
client_secret: auth.client_secret,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ serde::Serialize,
>
TryFrom<
VoltRouterData<
RouterDataV2<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
>,
T,
>,
> for VoltAuthUpdateRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: VoltRouterData<
RouterDataV2<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
Self::try_from(&item.router_data.connector_auth_type)
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct VoltAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
pub expires_in: i64,
}
impl<F, T>
TryFrom<
ResponseRouterData<
VoltAuthUpdateResponse,
RouterDataV2<F, PaymentFlowData, T, AccessTokenResponseData>,
>,
> for RouterDataV2<F, PaymentFlowData, T, AccessTokenResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
VoltAuthUpdateResponse,
RouterDataV2<F, PaymentFlowData, T, AccessTokenResponseData>,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessTokenResponseData {
access_token: item.response.access_token.expose(),
expires_in: Some(item.response.expires_in),
token_type: Some(item.response.token_type),
}),
..item.router_data
})
}
}
pub struct VoltAuthType {
pub(super) username: Secret<String>,
pub(super) password: Secret<String>,
pub(super) client_id: Secret<String>,
pub(super) client_secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for VoltAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Ok(Self {
username: api_key.to_owned(),
password: api_secret.to_owned(),
client_id: key1.to_owned(),
client_secret: key2.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsResponse {
checkout_url: String,
id: String,
}
impl<F, T>
TryFrom<
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_26567170429461802_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/volt/transformers.rs
ResponseRouterData<
VoltPaymentsResponse,
RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>,
>,
> for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
VoltPaymentsResponse,
RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let url = item.response.checkout_url;
let redirection_data = Some(RedirectForm::Form {
endpoint: url,
method: Method::Get,
form_fields: Default::default(),
});
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: redirection_data.map(Box::new),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(strum::Display)]
pub enum VoltPaymentStatus {
NewPayment,
Completed,
Received,
NotReceived,
BankRedirect,
DelayedAtBank,
AwaitingCheckoutAuthorisation,
RefusedByBank,
RefusedByRisk,
ErrorAtBank,
CancelledByUser,
AbandonedByUser,
Failed,
Settled,
Unknown,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum VoltPaymentsResponseData {
PsyncResponse(VoltPsyncResponse),
WebhookResponse(VoltPaymentWebhookObjectResource),
}
#[derive(Debug, Serialize, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPsyncResponse {
status: VoltPaymentStatus,
id: String,
merchant_internal_reference: Option<String>,
}
impl<F> TryFrom<ResponseRouterData<VoltPsyncResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ResponseRouterData<VoltPsyncResponse, Self>) -> Result<Self, Self::Error> {
let current_status = match &item.router_data.response {
Ok(_) => AttemptStatus::Pending,
Err(err) => err.attempt_status.unwrap_or(AttemptStatus::Pending),
};
let status = get_attempt_status((item.response.status.clone(), current_status));
let payments_response_data = match status {
AttemptStatus::Failure => Err(ErrorResponse {
code: item.response.status.clone().to_string(),
message: item.response.status.clone().to_string(),
reason: Some(item.response.status.to_string()),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(item.response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
_ => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item
.response
.merchant_internal_reference
.or(Some(item.response.id)),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response: payments_response_data,
..item.router_data
})
}
}
impl<F, T>
TryFrom<
ResponseRouterData<
VoltPaymentsResponseData,
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_26567170429461802_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/volt/transformers.rs
RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>,
>,
> for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
VoltPaymentsResponseData,
RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
match item.response {
VoltPaymentsResponseData::PsyncResponse(payment_response) => {
let current_status = match &item.router_data.response {
Ok(_) => AttemptStatus::Pending,
Err(err) => err.attempt_status.unwrap_or(AttemptStatus::Pending),
};
let status = get_attempt_status((payment_response.status.clone(), current_status));
let mut router_data = item.router_data;
router_data.response = match status {
AttemptStatus::Failure => Err(ErrorResponse {
code: payment_response.status.clone().to_string(),
message: payment_response.status.clone().to_string(),
reason: Some(payment_response.status.to_string()),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(payment_response.id),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
_ => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.id.clone(),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: payment_response
.merchant_internal_reference
.or(Some(payment_response.id)),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
};
Ok(router_data)
}
VoltPaymentsResponseData::WebhookResponse(webhook_response) => {
let detailed_status = webhook_response.detailed_status.clone();
let status = AttemptStatus::from(webhook_response.status);
let mut router_data = item.router_data;
router_data.response = match status {
AttemptStatus::Failure => Err(ErrorResponse {
code: detailed_status
.clone()
.map(|volt_status| volt_status.to_string())
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_owned()),
message: detailed_status
.clone()
.map(|volt_status| volt_status.to_string())
.unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_owned()),
reason: detailed_status
.clone()
.map(|volt_status| volt_status.to_string()),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(webhook_response.payment.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
_ => Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
webhook_response.payment.clone(),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_26567170429461802_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/volt/transformers.rs
network_txn_id: None,
connector_response_reference_id: webhook_response
.merchant_internal_reference
.or(Some(webhook_response.payment)),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
};
Ok(router_data)
}
}
}
}
impl From<VoltWebhookPaymentStatus> for AttemptStatus {
fn from(status: VoltWebhookPaymentStatus) -> Self {
match status {
VoltWebhookPaymentStatus::Received => Self::Charged,
VoltWebhookPaymentStatus::Failed | VoltWebhookPaymentStatus::NotReceived => {
Self::Failure
}
VoltWebhookPaymentStatus::Completed | VoltWebhookPaymentStatus::Pending => {
Self::Pending
}
}
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundRequest {
pub amount: MinorUnit,
pub external_reference: String,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ serde::Serialize,
> TryFrom<VoltRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>>
for VoltRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: VoltRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: MinorUnit::new(item.router_data.request.refund_amount),
external_reference: item.router_data.request.refund_id.clone(),
})
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct RefundResponse {
id: String,
}
impl<F> TryFrom<RefundsResponseRouterData<F, RefundResponse>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: RefundsResponseRouterData<F, RefundResponse>) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: common_enums::RefundStatus::Pending, //We get Refund Status only by Webhooks
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentWebhookBodyReference {
pub payment: String,
pub merchant_internal_reference: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundWebhookBodyReference {
pub refund: String,
pub external_reference: Option<String>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum WebhookResponse {
// the enum order shouldn't be changed as this is being used during serialization and deserialization
Refund(VoltRefundWebhookBodyReference),
Payment(VoltPaymentWebhookBodyReference),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum VoltWebhookBodyEventType {
Payment(VoltPaymentsWebhookBodyEventType),
Refund(VoltRefundsWebhookBodyEventType),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsWebhookBodyEventType {
pub status: VoltWebhookPaymentStatus,
pub detailed_status: Option<VoltDetailedStatus>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundsWebhookBodyEventType {
pub status: VoltWebhookRefundsStatus,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum VoltWebhookObjectResource {
Payment(VoltPaymentWebhookObjectResource),
Refund(VoltRefundWebhookObjectResource),
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltPaymentWebhookObjectResource {
#[serde(alias = "id")]
pub payment: String,
pub merchant_internal_reference: Option<String>,
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_26567170429461802_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/volt/transformers.rs
pub status: VoltWebhookPaymentStatus,
pub detailed_status: Option<VoltDetailedStatus>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoltRefundWebhookObjectResource {
pub refund: String,
pub external_reference: Option<String>,
pub status: VoltWebhookRefundsStatus,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VoltWebhookPaymentStatus {
Completed,
Failed,
Pending,
Received,
NotReceived,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum VoltWebhookRefundsStatus {
RefundConfirmed,
RefundFailed,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[derive(strum::Display)]
pub enum VoltDetailedStatus {
RefusedByRisk,
RefusedByBank,
ErrorAtBank,
CancelledByUser,
AbandonedByUser,
Failed,
Completed,
BankRedirect,
DelayedAtBank,
AwaitingCheckoutAuthorisation,
}
impl From<VoltWebhookBodyEventType> for IncomingWebhookEvent {
fn from(status: VoltWebhookBodyEventType) -> Self {
match status {
VoltWebhookBodyEventType::Payment(payment_data) => match payment_data.status {
VoltWebhookPaymentStatus::Received => Self::PaymentIntentSuccess,
VoltWebhookPaymentStatus::Failed | VoltWebhookPaymentStatus::NotReceived => {
Self::PaymentIntentFailure
}
VoltWebhookPaymentStatus::Completed | VoltWebhookPaymentStatus::Pending => {
Self::PaymentIntentProcessing
}
},
VoltWebhookBodyEventType::Refund(refund_data) => match refund_data.status {
VoltWebhookRefundsStatus::RefundConfirmed => Self::RefundSuccess,
VoltWebhookRefundsStatus::RefundFailed => Self::RefundFailure,
},
}
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct VoltErrorResponse {
pub exception: VoltErrorException,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct VoltAuthErrorResponse {
pub code: u64,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VoltErrorException {
pub code: u64,
pub message: String,
pub error_list: Option<Vec<VoltErrorList>>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct VoltErrorList {
pub property: String,
pub message: String,
}
| {
"chunk": 6,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
use common_enums::enums::{self, AttemptStatus, CountryAlpha2};
use common_utils::{ext_traits::Encode, pii, request::Method, types::StringMajorUnit};
use domain_types::{
connector_flow::{Authorize, Capture, Refund, SetupMandate, Void},
connector_types::{
MandateReference, MandateReferenceId, PaymentFlowData, PaymentVoidData,
PaymentsAuthorizeData, PaymentsCaptureData, PaymentsResponseData, RefundFlowData,
RefundSyncData, RefundsData, RefundsResponseData, ResponseId, SetupMandateRequestData,
},
errors::{self, ConnectorError},
mandates::MandateDataType,
payment_method_data::{
GooglePayWalletData, PaymentMethodData, PaymentMethodDataTypes, RawCardNumber, WalletData,
},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use super::NoonRouterData;
use crate::{types::ResponseRouterData, utils};
// These needs to be accepted from SDK, need to be done after 1.0.0 stability as API contract will change
const GOOGLEPAY_API_VERSION_MINOR: u8 = 0;
const GOOGLEPAY_API_VERSION: u8 = 2;
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum NoonChannels {
Web,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum NoonSubscriptionType {
Unscheduled,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonSubscriptionData {
#[serde(rename = "type")]
subscription_type: NoonSubscriptionType,
//Short description about the subscription.
name: String,
max_amount: StringMajorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonBillingAddress {
street: Option<Secret<String>>,
street2: Option<Secret<String>>,
city: Option<String>,
state_province: Option<Secret<String>>,
country: Option<CountryAlpha2>,
postal_code: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonBilling {
address: NoonBillingAddress,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonOrder {
amount: StringMajorUnit,
currency: Option<enums::Currency>,
channel: NoonChannels,
category: Option<String>,
reference: String,
//Short description of the order.
name: String,
nvp: Option<NoonOrderNvp>,
ip_address: Option<Secret<String, pii::IpAddress>>,
}
#[derive(Debug, Serialize)]
pub struct NoonOrderNvp {
#[serde(flatten)]
inner: std::collections::BTreeMap<String, Secret<String>>,
}
fn get_value_as_string(value: &serde_json::Value) -> String {
match value {
serde_json::Value::String(string) => string.to_owned(),
serde_json::Value::Null
| serde_json::Value::Bool(_)
| serde_json::Value::Number(_)
| serde_json::Value::Array(_)
| serde_json::Value::Object(_) => value.to_string(),
}
}
impl NoonOrderNvp {
pub fn new(metadata: &serde_json::Value) -> Self {
let metadata_as_string = metadata.to_string();
let hash_map: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new());
let inner = hash_map
.into_iter()
.enumerate()
.map(|(index, (hs_key, hs_value))| {
let noon_key = format!("{}", index + 1);
// to_string() function on serde_json::Value returns a string with "" quotes. Noon doesn't allow this. Hence get_value_as_string function
let noon_value = format!("{hs_key}={}", get_value_as_string(&hs_value));
(noon_key, Secret::new(noon_value))
})
.collect();
Self { inner }
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum NoonPaymentActions {
Authorize,
Sale,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonConfiguration {
tokenize_c_c: Option<bool>,
payment_action: NoonPaymentActions,
return_url: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonSubscription {
subscription_identifier: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
pub struct NoonCard<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
name_on_card: Option<Secret<String>>,
number_plain: RawCardNumber<T>,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvv: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePayPaymentMethod {
pub display_name: String,
pub network: String,
#[serde(rename = "type")]
pub pm_type: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonApplePaymentData {
version: Secret<String>,
data: Secret<String>,
signature: Secret<String>,
header: NoonApplePayHeader,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePayData {
payment_data: NoonApplePaymentData,
payment_method: NoonApplePayPaymentMethod,
transaction_identifier: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePayTokenData {
token: NoonApplePayData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonApplePay {
payment_info: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonGooglePay {
api_version_minor: u8,
api_version: u8,
payment_method_data: GooglePayWalletData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPayPal {
return_url: String,
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", content = "data", rename_all = "UPPERCASE")]
pub enum NoonPaymentData<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
Card(NoonCard<T>),
Subscription(NoonSubscription),
ApplePay(NoonApplePay),
GooglePay(NoonGooglePay),
PayPal(NoonPayPal),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NoonApiOperations {
Initiate,
Capture,
Reverse,
Refund,
CancelSubscription,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
api_operation: NoonApiOperations,
order: NoonOrder,
configuration: NoonConfiguration,
payment_data: NoonPaymentData<T>,
subscription: Option<NoonSubscriptionData>,
billing: Option<NoonBilling>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
NoonRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for NoonPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
data: NoonRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let item = &data.router_data;
let amount = data.connector.amount_converter.convert(
data.router_data.request.minor_amount,
data.router_data.request.currency,
);
let (payment_data, currency, category) = match item.request.connector_mandate_id() {
Some(mandate_id) => (
NoonPaymentData::Subscription(NoonSubscription {
subscription_identifier: Secret::new(mandate_id),
}),
None,
None,
),
_ => (
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard {
name_on_card: item.resource_common_data.get_optional_billing_full_name(),
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
number_plain: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
cvv: req_card.card_cvc,
})),
PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
WalletData::GooglePay(google_pay_data) => {
Ok(NoonPaymentData::GooglePay(NoonGooglePay {
api_version_minor: GOOGLEPAY_API_VERSION_MINOR,
api_version: GOOGLEPAY_API_VERSION,
payment_method_data: google_pay_data,
}))
}
WalletData::ApplePay(apple_pay_data) => {
let payment_token_data = NoonApplePayTokenData {
token: NoonApplePayData {
payment_data: wallet_data
.get_wallet_token_as_json("Apple Pay".to_string())?,
payment_method: NoonApplePayPaymentMethod {
display_name: apple_pay_data.payment_method.display_name,
network: apple_pay_data.payment_method.network,
pm_type: apple_pay_data.payment_method.pm_type,
},
transaction_identifier: Secret::new(
apple_pay_data.transaction_identifier,
),
},
};
let payment_token = payment_token_data
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(NoonPaymentData::ApplePay(NoonApplePay {
payment_info: Secret::new(payment_token),
}))
}
WalletData::PaypalRedirect(_) => Ok(NoonPaymentData::PayPal(NoonPayPal {
return_url: item.request.get_router_return_url()?,
})),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::BluecodeRedirect { .. }
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Noon"),
)),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Noon"),
))
}
}?,
Some(item.request.currency),
Some(item.request.order_category.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "order_category",
},
)?),
),
};
let ip_address = item.request.get_ip_address_as_optional();
let channel = NoonChannels::Web;
let billing = item
.resource_common_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| NoonBilling {
address: NoonBillingAddress {
street: address.line1.clone(),
street2: address.line2.clone(),
city: address.city.clone(),
// If state is passed in request, country becomes mandatory, keep a check while debugging failed payments
state_province: address.state.clone(),
country: address.country,
postal_code: address.zip.clone(),
},
});
// The description should not have leading or trailing whitespaces, also it should not have double whitespaces and a max 50 chars according to Noon's Docs
let name: String = item
.resource_common_data
.get_description()?
.trim()
.replace(" ", " ")
.chars()
.take(50)
.collect();
let order = NoonOrder {
amount: amount.change_context(ConnectorError::ParsingFailed)?,
currency,
channel,
category,
reference: item
.resource_common_data
.connector_request_reference_id
.clone(),
name,
nvp: item.request.metadata.as_ref().map(NoonOrderNvp::new),
ip_address,
};
let payment_action = if item.request.is_auto_capture()? {
NoonPaymentActions::Sale
} else {
NoonPaymentActions::Authorize
};
Ok(Self {
api_operation: NoonApiOperations::Initiate,
order,
billing,
configuration: NoonConfiguration {
payment_action,
return_url: item.request.router_return_url.clone(),
tokenize_c_c: None,
},
payment_data,
subscription: None,
})
}
}
// Auth Struct
pub struct NoonAuthType {
pub(super) api_key: Secret<String>,
pub(super) application_identifier: Secret<String>,
pub(super) business_identifier: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NoonAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => Ok(Self {
api_key: api_key.to_owned(),
application_identifier: api_secret.to_owned(),
business_identifier: key1.to_owned(),
}),
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Default, Debug, Deserialize, Serialize, strum::Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum NoonPaymentStatus {
Initiated,
Authorized,
Captured,
PartiallyCaptured,
PartiallyRefunded,
PaymentInfoAdded,
#[serde(rename = "3DS_ENROLL_INITIATED")]
ThreeDsEnrollInitiated,
#[serde(rename = "3DS_ENROLL_CHECKED")]
ThreeDsEnrollChecked,
#[serde(rename = "3DS_RESULT_VERIFIED")]
ThreeDsResultVerified,
MarkedForReview,
Authenticated,
PartiallyReversed,
#[default]
Pending,
Cancelled,
Failed,
Refunded,
Expired,
Reversed,
Rejected,
Locked,
}
fn get_payment_status(data: (NoonPaymentStatus, AttemptStatus)) -> AttemptStatus {
let (item, current_status) = data;
match item {
NoonPaymentStatus::Authorized => AttemptStatus::Authorized,
NoonPaymentStatus::Captured
| NoonPaymentStatus::PartiallyCaptured
| NoonPaymentStatus::PartiallyRefunded
| NoonPaymentStatus::Refunded => AttemptStatus::Charged,
NoonPaymentStatus::Reversed | NoonPaymentStatus::PartiallyReversed => AttemptStatus::Voided,
NoonPaymentStatus::Cancelled | NoonPaymentStatus::Expired => {
AttemptStatus::AuthenticationFailed
}
NoonPaymentStatus::ThreeDsEnrollInitiated | NoonPaymentStatus::ThreeDsEnrollChecked => {
AttemptStatus::AuthenticationPending
}
NoonPaymentStatus::ThreeDsResultVerified => AttemptStatus::AuthenticationSuccessful,
NoonPaymentStatus::Failed | NoonPaymentStatus::Rejected => AttemptStatus::Failure,
NoonPaymentStatus::Pending | NoonPaymentStatus::MarkedForReview => AttemptStatus::Pending,
NoonPaymentStatus::Initiated
| NoonPaymentStatus::PaymentInfoAdded
| NoonPaymentStatus::Authenticated => AttemptStatus::Started,
NoonPaymentStatus::Locked => current_status,
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonSubscriptionObject {
identifier: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsOrderResponse {
status: NoonPaymentStatus,
id: u64,
error_code: u64,
error_message: Option<String>,
reference: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonCheckoutData {
post_url: url::Url,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsResponseResult {
order: NoonPaymentsOrderResponse,
checkout_data: Option<NoonCheckoutData>,
subscription: Option<NoonSubscriptionObject>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonPaymentsResponse {
result: NoonPaymentsResponseResult,
}
impl<F, T> TryFrom<ResponseRouterData<NoonPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<NoonPaymentsResponse, Self>) -> Result<Self, Self::Error> {
let order = item.response.result.order;
let current_attempt_status = item.router_data.resource_common_data.status;
let status = get_payment_status((order.status, current_attempt_status));
let redirection_data = item.response.result.checkout_data.map(|redirection_data| {
Box::new(RedirectForm::Form {
endpoint: redirection_data.post_url.to_string(),
method: Method::Post,
form_fields: std::collections::HashMap::new(),
})
});
let mandate_reference = item.response.result.subscription.map(|subscription_data| {
Box::new(MandateReference {
connector_mandate_id: Some(subscription_data.identifier.expose()),
payment_method_id: None,
})
});
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response: match order.error_message {
Some(error_message) => Err(ErrorResponse {
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
code: order.error_code.to_string(),
message: error_message.clone(),
reason: Some(error_message),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(order.id.to_string()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
_ => {
let connector_response_reference_id =
order.reference.or(Some(order.id.to_string()));
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(order.id.to_string()),
redirection_data,
mandate_reference,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
status_code: item.http_code,
})
}
},
..item.router_data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonActionTransaction {
amount: StringMajorUnit,
currency: enums::Currency,
transaction_reference: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonActionOrder {
id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsActionRequest {
api_operation: NoonApiOperations,
order: NoonActionOrder,
transaction: NoonActionTransaction,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
NoonRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for NoonPaymentsActionRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
data: NoonRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let item = &data.router_data;
let amount = data.connector.amount_converter.convert(
data.router_data.request.minor_amount_to_capture,
data.router_data.request.currency,
);
let order = NoonActionOrder {
id: item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(ConnectorError::MissingRequiredField {
field_name: "connector_transaction_id",
})?,
};
let transaction = NoonActionTransaction {
amount: amount.change_context(ConnectorError::ParsingFailed)?,
currency: item.request.currency,
transaction_reference: None,
};
Ok(Self {
api_operation: NoonApiOperations::Capture,
order,
transaction,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsCancelRequest {
api_operation: NoonApiOperations,
order: NoonActionOrder,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
NoonRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
> for NoonPaymentsCancelRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: NoonRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let order = NoonActionOrder {
id: item.router_data.request.connector_transaction_id.clone(),
};
Ok(Self {
api_operation: NoonApiOperations::Reverse,
order,
})
}
}
#[derive(Debug, Serialize)]
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
#[serde(rename_all = "camelCase")]
pub struct NoonRevokeMandateRequest {
api_operation: NoonApiOperations,
subscription: NoonSubscriptionObject,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
NoonRouterData<RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>, T>,
> for NoonPaymentsActionRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
data: NoonRouterData<
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let item = &data.router_data;
let refund_amount = data.connector.amount_converter.convert(
data.router_data.request.minor_payment_amount,
data.router_data.request.currency,
);
let order = NoonActionOrder {
id: item.request.connector_transaction_id.clone(),
};
let transaction = NoonActionTransaction {
amount: refund_amount.change_context(ConnectorError::ParsingFailed)?,
currency: item.request.currency,
transaction_reference: Some(item.request.refund_id.clone()),
};
Ok(Self {
api_operation: NoonApiOperations::Refund,
order,
transaction,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub enum NoonRevokeStatus {
Cancelled,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonCancelSubscriptionObject {
status: NoonRevokeStatus,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonRevokeMandateResult {
subscription: NoonCancelSubscriptionObject,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NoonRevokeMandateResponse {
result: NoonRevokeMandateResult,
}
#[derive(Debug, Default, Deserialize, Clone, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Success,
Failed,
#[default]
Pending,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonPaymentsTransactionResponse {
id: String,
status: RefundStatus,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundResponseResult {
transaction: NoonPaymentsTransactionResponse,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
result: NoonRefundResponseResult,
result_code: u32,
class_description: String,
message: String,
}
impl<F> TryFrom<ResponseRouterData<RefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundResponse, Self>) -> Result<Self, Self::Error> {
let response = &item.response;
let refund_status =
enums::RefundStatus::from(response.result.transaction.status.to_owned());
let response = if utils::is_refund_failure(refund_status) {
Err(ErrorResponse {
status_code: item.http_code,
code: response.result_code.to_string(),
message: response.class_description.clone(),
reason: Some(response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(response.result.transaction.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: item.response.result.transaction.id,
refund_status,
status_code: item.http_code,
})
};
Ok(Self {
response,
..item.router_data
})
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
| {
"chunk": 6,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
pub struct NoonRefundResponseTransactions {
id: String,
status: RefundStatus,
transaction_reference: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonRefundSyncResponseResult {
transactions: Vec<NoonRefundResponseTransactions>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundSyncResponse {
result: NoonRefundSyncResponseResult,
result_code: u32,
class_description: String,
message: String,
}
impl<F> TryFrom<ResponseRouterData<RefundSyncResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundSyncResponse, Self>) -> Result<Self, Self::Error> {
let noon_transaction: &NoonRefundResponseTransactions = item
.response
.result
.transactions
.iter()
.find(|transaction| transaction.transaction_reference.is_some())
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let refund_status = enums::RefundStatus::from(noon_transaction.status.to_owned());
let response = if utils::is_refund_failure(refund_status) {
let response = &item.response;
Err(ErrorResponse {
status_code: item.http_code,
code: response.result_code.to_string(),
message: response.class_description.clone(),
reason: Some(response.message.clone()),
attempt_status: None,
connector_transaction_id: Some(noon_transaction.id.clone()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
} else {
Ok(RefundsResponseData {
connector_refund_id: noon_transaction.id.to_owned(),
refund_status,
status_code: item.http_code,
})
};
Ok(Self {
response,
..item.router_data
})
}
}
#[derive(Debug, Deserialize, strum::Display)]
pub enum NoonWebhookEventTypes {
Authenticate,
Authorize,
Capture,
Fail,
Refund,
Sale,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonWebhookBody {
pub order_id: u64,
pub order_status: NoonPaymentStatus,
pub event_type: NoonWebhookEventTypes,
pub event_id: String,
pub time_stamp: String,
}
#[derive(Debug, Deserialize)]
pub struct NoonWebhookSignature {
pub signature: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonWebhookOrderId {
pub order_id: u64,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonWebhookEvent {
pub order_status: NoonPaymentStatus,
pub event_type: NoonWebhookEventTypes,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonWebhookObject {
pub order_status: NoonPaymentStatus,
pub order_id: u64,
}
/// This from will ensure that webhook body would be properly parsed into PSync response
impl From<NoonWebhookObject> for NoonPaymentsResponse {
fn from(value: NoonWebhookObject) -> Self {
Self {
result: NoonPaymentsResponseResult {
order: NoonPaymentsOrderResponse {
status: value.order_status,
id: value.order_id,
//For successful payments Noon Always populates error_code as 0.
error_code: 0,
error_message: None,
reference: None,
},
checkout_data: None,
subscription: None,
},
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonErrorResponse {
pub result_code: u32,
pub message: String,
pub class_description: String,
}
#[derive(Debug, Serialize)]
pub struct SetupMandateRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(NoonPaymentsRequest<T>);
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
| {
"chunk": 7,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
NoonRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
> for SetupMandateRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
data: NoonRouterData<
RouterDataV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let item = &data.router_data;
let amount = data.connector.amount_converter.convert(
common_utils::types::MinorUnit::new(1),
data.router_data.request.currency,
);
let mandate_amount = &data.router_data.request.setup_mandate_details;
let (payment_data, currency, category) = match &item.request.mandate_id {
Some(mandate_ids) => match &mandate_ids.mandate_reference_id {
Some(MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
if let Some(mandate_id) = connector_mandate_ids.get_connector_mandate_id() {
(
NoonPaymentData::Subscription(NoonSubscription {
subscription_identifier: Secret::new(mandate_id),
}),
None,
None,
)
} else {
return Err(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
}
.into());
}
}
_ => {
return Err(errors::ConnectorError::MissingRequiredField {
field_name: "connector_mandate_id",
}
.into());
}
},
None => (
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard {
name_on_card: item.resource_common_data.get_optional_billing_full_name(),
number_plain: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
cvv: req_card.card_cvc,
})),
PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
WalletData::GooglePay(google_pay_data) => {
Ok(NoonPaymentData::GooglePay(NoonGooglePay {
api_version_minor: GOOGLEPAY_API_VERSION_MINOR,
api_version: GOOGLEPAY_API_VERSION,
payment_method_data: google_pay_data,
}))
}
WalletData::ApplePay(apple_pay_data) => {
let payment_token_data = NoonApplePayTokenData {
token: NoonApplePayData {
payment_data: wallet_data
.get_wallet_token_as_json("Apple Pay".to_string())?,
payment_method: NoonApplePayPaymentMethod {
display_name: apple_pay_data.payment_method.display_name,
network: apple_pay_data.payment_method.network,
pm_type: apple_pay_data.payment_method.pm_type,
},
transaction_identifier: Secret::new(
apple_pay_data.transaction_identifier,
),
},
};
| {
"chunk": 8,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_9 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
let payment_token = payment_token_data
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(NoonPaymentData::ApplePay(NoonApplePay {
payment_info: Secret::new(payment_token),
}))
}
WalletData::PaypalRedirect(_) => Ok(NoonPaymentData::PayPal(NoonPayPal {
return_url: item.request.get_router_return_url()?,
})),
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::BluecodeRedirect { .. }
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Noon"),
)),
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Noon"),
))
}
}?,
Some(item.request.currency),
// Get order_category from metadata field, return error if not provided
Some(
item.request
.metadata
.as_ref()
.and_then(|metadata| metadata.get("order_category"))
.and_then(|value| value.as_str())
.map(|s| s.to_string())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "order_category in metadata",
})?,
),
),
};
let ip_address = item.request.browser_info.as_ref().and_then(|browser_info| {
| {
"chunk": 9,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_10 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
browser_info
.ip_address
.map(|ip| Secret::new(ip.to_string()))
});
let channel = NoonChannels::Web;
let billing = item
.resource_common_data
.get_optional_billing()
.and_then(|billing_address| billing_address.address.as_ref())
.map(|address| NoonBilling {
address: NoonBillingAddress {
street: address.line1.clone(),
street2: address.line2.clone(),
city: address.city.clone(),
state_province: address.state.clone(),
country: address.country,
postal_code: address.zip.clone(),
},
});
// The description should not have leading or trailing whitespaces, also it should not have double whitespaces and a max 50 chars according to Noon's Docs
let name: String = item
.resource_common_data
.get_description()?
.trim()
.replace(" ", " ")
.chars()
.take(50)
.collect();
let subscription = mandate_amount.as_ref().and_then(|mandate_data| {
mandate_data.mandate_type.as_ref().and_then(|mandate_type| {
let mandate_amount_data = match mandate_type {
MandateDataType::SingleUse(amount_data) => Some(amount_data),
MandateDataType::MultiUse(amount_data_opt) => amount_data_opt.as_ref(),
};
mandate_amount_data.and_then(|amount_data| {
data.connector
.amount_converter
.convert(amount_data.amount, amount_data.currency)
.ok()
.map(|max_amount| NoonSubscriptionData {
subscription_type: NoonSubscriptionType::Unscheduled,
name: name.clone(),
max_amount,
})
})
})
});
let tokenize_c_c = subscription.is_some().then_some(true);
let order = NoonOrder {
amount: amount.change_context(ConnectorError::ParsingFailed)?,
currency,
channel,
category,
reference: item
.resource_common_data
.connector_request_reference_id
.clone(),
name,
nvp: item.request.metadata.as_ref().map(NoonOrderNvp::new),
ip_address,
};
let payment_action = match item.request.capture_method {
Some(common_enums::CaptureMethod::Automatic)
| None
| Some(common_enums::CaptureMethod::SequentialAutomatic) => NoonPaymentActions::Sale,
Some(common_enums::CaptureMethod::Manual) => NoonPaymentActions::Authorize,
Some(_) => NoonPaymentActions::Authorize,
};
Ok(SetupMandateRequest(NoonPaymentsRequest {
api_operation: NoonApiOperations::Initiate,
order,
billing,
configuration: NoonConfiguration {
payment_action,
return_url: item.request.router_return_url.clone(),
tokenize_c_c,
},
payment_data,
subscription,
}))
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SetupMandateResponse {
pub result_code: u32,
pub message: String,
pub result_class: Option<u32>,
pub class_description: Option<String>,
pub action_hint: Option<String>,
pub request_reference: Option<String>,
pub result: NoonPaymentsResponseResult,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<SetupMandateResponse, Self>>
for RouterDataV2<F, PaymentFlowData, SetupMandateRequestData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<SetupMandateResponse, Self>) -> Result<Self, Self::Error> {
let order = item.response.result.order;
| {
"chunk": 10,
"crate": "connector-integration",
"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_connector-integration_-5995661011311607473_11 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/noon/transformers.rs
let current_attempt_status = item.router_data.resource_common_data.status;
let status = get_payment_status((order.status, current_attempt_status));
let redirection_data = item.response.result.checkout_data.map(|redirection_data| {
Box::new(RedirectForm::Form {
endpoint: redirection_data.post_url.to_string(),
method: Method::Post,
form_fields: std::collections::HashMap::new(),
})
});
let mandate_reference = item.response.result.subscription.map(|subscription_data| {
Box::new(MandateReference {
connector_mandate_id: Some(subscription_data.identifier.expose()),
payment_method_id: None,
})
});
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response: match order.error_message {
Some(error_message) => Err(ErrorResponse {
code: order.error_code.to_string(),
message: error_message.clone(),
reason: Some(error_message),
status_code: item.http_code,
attempt_status: Some(status),
connector_transaction_id: Some(order.id.to_string()),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
_ => {
let connector_response_reference_id =
order.reference.or(Some(order.id.to_string()));
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(order.id.to_string()),
redirection_data,
mandate_reference,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id,
incremental_authorization_allowed: None,
status_code: item.http_code,
})
}
},
..item.router_data
})
}
}
| {
"chunk": 11,
"crate": "connector-integration",
"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_connector-integration_1534611827297484703_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/placetopay/transformers.rs
use common_utils::types::MinorUnit;
use domain_types::{
connector_flow::{Authorize, Capture, PSync, RSync, Void},
connector_types::{
PaymentFlowData, PaymentVoidData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData,
RefundsResponseData, ResponseId,
},
errors::{self, ConnectorError},
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, RawCardNumber},
router_data::ConnectorAuthType,
router_data_v2::RouterDataV2,
utils,
};
use error_stack::ResultExt;
use hyperswitch_masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use crate::{connectors::placetopay::PlacetopayRouterData, types::ResponseRouterData};
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAuthType {
pub(super) login: Secret<String>,
pub(super) tran_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for PlacetopayAuthType {
type Error = domain_types::errors::ConnectorError;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
login: api_key.to_owned(),
tran_key: key1.to_owned(),
}),
_ => Err(domain_types::errors::ConnectorError::FailedToObtainAuthType),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAuth {
login: Secret<String>,
tran_key: Secret<String>,
nonce: Secret<String>,
seed: String,
}
impl TryFrom<&ConnectorAuthType> for PlacetopayAuth {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
let placetopay_auth = PlacetopayAuthType::try_from(auth_type)?;
let nonce_bytes = domain_types::utils::generate_random_bytes(16);
let now = common_utils::date_time::date_as_yyyymmddthhmmssmmmz()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let seed = format!("{}+00:00", now.split_at(now.len() - 5).0);
let nonce_b64 = base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
nonce_bytes.clone(),
);
let mut hasher = ring::digest::Context::new(&ring::digest::SHA256);
hasher.update(&nonce_bytes);
hasher.update(seed.as_bytes());
hasher.update(placetopay_auth.tran_key.peek().as_bytes());
let encoded_digest =
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, hasher.finish());
let nonce = Secret::new(nonce_b64);
Ok(Self {
login: placetopay_auth.login,
tran_key: encoded_digest.into(),
nonce,
seed,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
auth: PlacetopayAuth,
payment: PlacetopayPayment,
instrument: PlacetopayInstrument<T>,
ip_address: Secret<String, common_utils::pii::IpAddress>,
user_agent: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPayment {
reference: String,
description: String,
amount: PlacetopayAmount,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayAmount {
currency: common_enums::Currency,
total: MinorUnit,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayInstrument<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
card: PlacetopayCard<T>,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayCard<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
number: RawCardNumber<T>,
expiration: Secret<String>,
cvv: Secret<String>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_1534611827297484703_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/placetopay/transformers.rs
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
PlacetopayRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for PlacetopayPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PlacetopayRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let browser_info = item.router_data.request.get_browser_info()?;
let ip_address = browser_info.get_ip_address()?;
let user_agent = browser_info.get_user_agent()?;
let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
let payment = PlacetopayPayment {
reference: item
.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
description: item.router_data.resource_common_data.get_description()?,
amount: PlacetopayAmount {
currency: item.router_data.request.currency,
total: item.router_data.request.minor_amount,
},
};
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = PlacetopayCard {
number: req_card.card_number.clone(),
expiration: req_card
.clone()
.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned())?,
cvv: req_card.card_cvc.clone(),
};
Ok(Self {
ip_address,
user_agent,
auth,
payment,
instrument: PlacetopayInstrument {
card: card.to_owned(),
},
})
}
PaymentMethodData::Wallet(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Placetopay"),
)
.into())
}
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
PlacetopayRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
> for PlacetopayNextActionRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PlacetopayRouterData<
RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
let internal_reference = item
.router_data
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Void;
Ok(Self {
auth,
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_1534611827297484703_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/placetopay/transformers.rs
internal_reference,
action,
})
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayTransactionStatus {
Ok,
Failed,
Approved,
Rejected,
Pending,
PendingValidation,
PendingProcess,
Error,
}
impl From<PlacetopayTransactionStatus> for common_enums::AttemptStatus {
fn from(item: PlacetopayTransactionStatus) -> Self {
match item {
PlacetopayTransactionStatus::Approved | PlacetopayTransactionStatus::Ok => {
Self::Charged
}
PlacetopayTransactionStatus::Failed
| PlacetopayTransactionStatus::Rejected
| PlacetopayTransactionStatus::Error => Self::Failure,
PlacetopayTransactionStatus::Pending
| PlacetopayTransactionStatus::PendingValidation
| PlacetopayTransactionStatus::PendingProcess => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayStatusResponse {
status: PlacetopayTransactionStatus,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPaymentsResponse {
status: PlacetopayStatusResponse,
internal_reference: u64,
authorization: Option<Secret<String>>,
}
// Authorize flow uses the unified payment response handling with capture method consideration
impl<F, T> TryFrom<ResponseRouterData<PlacetopayPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<PlacetopayPaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::from(item.response.status.status),
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.internal_reference.to_string(),
),
redirection_data: None,
mandate_reference: None,
connector_metadata: item
.response
.authorization
.clone()
.map(|authorization| serde_json::json!(authorization)),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayPsyncRequest {
auth: PlacetopayAuth,
internal_reference: u64,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
PlacetopayRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
> for PlacetopayPsyncRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PlacetopayRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
let internal_reference = item
.router_data
.request
.get_connector_transaction_id()?
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
auth,
internal_reference,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayNextActionRequest {
auth: PlacetopayAuth,
internal_reference: u64,
action: PlacetopayNextAction,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PlacetopayNextAction {
Refund,
Reverse,
Void,
Process,
Checkout,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_1534611827297484703_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/placetopay/transformers.rs
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
PlacetopayRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for PlacetopayNextActionRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PlacetopayRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
let internal_reference = item
.router_data
.request
.get_connector_transaction_id()
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Checkout;
Ok(Self {
auth,
internal_reference,
action,
})
}
}
// REFUND TYPES
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundRequest {
auth: PlacetopayAuth,
internal_reference: u64,
action: PlacetopayNextAction,
authorization: Option<Secret<String>>,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
PlacetopayRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>,
> for PlacetopayRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PlacetopayRouterData<
RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
if item.router_data.request.minor_refund_amount
== item.router_data.request.minor_payment_amount
{
let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
let internal_reference = item
.router_data
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let action = PlacetopayNextAction::Reverse;
let authorization = match item.router_data.request.connector_metadata.clone() {
Some(metadata) => metadata.as_str().map(|auth| auth.to_string()),
None => None,
};
Ok(Self {
auth,
internal_reference,
action,
authorization: authorization.map(Secret::new),
})
} else {
Err(errors::ConnectorError::NotSupported {
message: "Partial Refund".to_string(),
connector: "placetopay",
}
.into())
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayRefundStatus {
Ok,
Failed,
Approved,
Rejected,
Pending,
PendingValidation,
PendingProcess,
Refunded,
Error,
}
impl From<PlacetopayRefundStatus> for common_enums::RefundStatus {
fn from(item: PlacetopayRefundStatus) -> Self {
match item {
PlacetopayRefundStatus::Ok
| PlacetopayRefundStatus::Approved
| PlacetopayRefundStatus::Refunded => Self::Success,
PlacetopayRefundStatus::Failed
| PlacetopayRefundStatus::Rejected
| PlacetopayRefundStatus::Error => Self::Failure,
PlacetopayRefundStatus::Pending
| PlacetopayRefundStatus::PendingProcess
| PlacetopayRefundStatus::PendingValidation => Self::Pending,
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundStatusResponse {
status: PlacetopayRefundStatus,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRefundResponse {
status: PlacetopayRefundStatusResponse,
internal_reference: u64,
}
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_1534611827297484703_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/placetopay/transformers.rs
impl<F> TryFrom<ResponseRouterData<PlacetopayRefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<PlacetopayRefundResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.internal_reference.to_string(),
refund_status: common_enums::RefundStatus::from(item.response.status.status),
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayRsyncRequest {
auth: PlacetopayAuth,
internal_reference: u64,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
PlacetopayRouterData<
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
T,
>,
> for PlacetopayRsyncRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: PlacetopayRouterData<
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = PlacetopayAuth::try_from(&item.router_data.connector_auth_type)?;
let internal_reference = item
.router_data
.request
.connector_transaction_id
.parse::<u64>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
auth,
internal_reference,
})
}
}
impl<F> TryFrom<ResponseRouterData<PlacetopayRefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<PlacetopayRefundResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.internal_reference.to_string(),
refund_status: common_enums::RefundStatus::from(item.response.status.status),
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayErrorResponse {
pub status: PlacetopayError,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayError {
pub status: PlacetopayErrorStatus,
pub message: Option<String>,
pub reason: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayErrorStatus {
Failed,
}
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
#[cfg(test)]
mod tests {
use cards::CardNumber;
use common_enums::{AttemptStatus, AuthenticationType, PaymentMethod};
use domain_types::{
connector_types::{PaymentFlowData, PaymentsAuthorizeData},
payment_address::{Address, PhoneDetails},
payment_method_data::{Card, DefaultPCIHolder, PaymentMethodData, RawCardNumber},
router_request_types::BrowserInformation,
router_response_types::Response,
};
use interfaces::{
connector_integration_v2::ConnectorIntegrationV2,
connector_types::{BoxedConnector, ConnectorServiceTrait},
};
use serde_json::{json, to_value};
use crate::connectors::Razorpay;
mod authorize {
use std::str::FromStr;
use cards::CardNumber;
use common_enums::{
AttemptStatus, AuthenticationType, Currency, PaymentMethod, PaymentMethodType,
};
use common_utils::{
id_type::MerchantId, pii::Email, request::RequestContent, types::MinorUnit,
};
use domain_types::{
connector_types::{PaymentFlowData, PaymentsAuthorizeData},
payment_address::{Address, PaymentAddress, PhoneDetails},
payment_method_data::{Card, DefaultPCIHolder, PaymentMethodData, RawCardNumber},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_request_types::BrowserInformation,
router_response_types::Response,
types::{ConnectorParams, Connectors},
};
use interfaces::{
connector_integration_v2::ConnectorIntegrationV2,
connector_types::{BoxedConnector, ConnectorServiceTrait},
};
use serde_json::{json, to_value, Value};
use crate::connectors::Razorpay;
#[test]
fn test_build_request_valid() {
let email = Email::try_from("testuser@gmail.com".to_string()).unwrap();
let test_router_data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "IRRELEVANT_PAYMENT_ID".to_string(),
attempt_id: "IRRELEVANT_ATTEMPT_ID".to_string(),
status: AttemptStatus::Pending,
payment_method: PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(
None,
Some(Address {
address: None,
phone: Some(PhoneDetails {
number: Some("1234567890".to_string().into()),
country_code: Some("+1".to_string()),
}),
email: Some(email.clone()),
}),
None,
None,
),
auth_type: AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: Some("order_QMSVrXxHS9sBmu".to_string()),
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_12345".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentsAuthorizeData {
authentication_data: None,
payment_method_data: PaymentMethodData::Card(Card {
card_number: RawCardNumber(
CardNumber::from_str("5123456789012346").unwrap(),
),
card_exp_month: "12".to_string().into(),
card_exp_year: "2026".to_string().into(),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
card_holder_name: Some("Test User".to_string().into()),
co_badged_card_data: None,
}),
amount: 1000,
order_tax_amount: None,
email: Some(email.clone()),
customer_name: None,
currency: Currency::USD,
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: None,
router_return_url: None,
webhook_url: None,
integrity_object: None,
complete_authorize_url: None,
mandate_id: None,
setup_future_usage: None,
off_session: None,
browser_info: Some(BrowserInformation {
color_depth: None,
java_enabled: Some(false),
java_script_enabled: None,
language: Some("en-US".to_string()),
screen_height: Some(1080),
screen_width: Some(1920),
time_zone: None,
ip_address: None,
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
.to_string(),
),
user_agent: Some(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string(),
),
referer: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
}),
order_category: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: Some(PaymentMethodType::Credit),
customer_id: None,
request_incremental_authorization: false,
metadata: None,
minor_amount: MinorUnit::new(1000),
merchant_order_reference_id: None,
shipping_cost: None,
merchant_account_id: None,
merchant_config_currency: None,
all_keys_required: None,
access_token: None,
customer_acceptance: None,
split_payments: None,
request_extended_authorization: None,
setup_mandate_details: None,
enable_overcapture: None,
merchant_account_metadata: None,
},
response: Err(ErrorResponse {
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: 500,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result = connector.get_request_body(&test_router_data);
let request_content = result.unwrap();
let actual_json: Value = match request_content {
Some(RequestContent::Json(payload)) => {
to_value(&payload).expect("Failed to serialize payload to JSON")
}
_ => panic!("Expected JSON payload"),
};
let expected_json: Value = json!({
"amount": 1000,
"currency": "USD",
"contact": "1234567890",
"email": "testuser@gmail.com",
"order_id": "order_QMSVrXxHS9sBmu",
"method": "card",
"card": {
"number": "5123456789012346",
"expiry_month": "12",
"expiry_year": "2026",
"cvv": "123"
},
"authentication": {
"authentication_channel": "browser"
},
"browser": {
"java_enabled": false,
"language": "en-US",
"screen_height": 1080,
"screen_width": 1920
},
"ip": "127.0.0.1",
"referer": "https://example.com",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"
});
assert_eq!(actual_json, expected_json);
}
#[test]
fn test_build_request_missing() {
let test_router_data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "MISSING_EMAIL_ID".to_string(),
attempt_id: "MISSING_CARD_ID".to_string(),
status: AttemptStatus::Pending,
payment_method: PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(None, None, None, None),
auth_type: AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: Some("order_missing".to_string()),
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_missing".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentsAuthorizeData {
authentication_data: None,
payment_method_data: PaymentMethodData::Card(Card {
card_number: RawCardNumber(CardNumber::from_str("").unwrap_or_default()),
card_exp_month: "".to_string().into(),
card_exp_year: "".to_string().into(),
card_cvc: "".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
card_holder_name: Some("Test User".to_string().into()),
co_badged_card_data: None,
}),
amount: 1000,
order_tax_amount: None,
email: None,
customer_name: None,
currency: Currency::USD,
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: None,
mandate_id: None,
setup_future_usage: None,
off_session: None,
integrity_object: None,
browser_info: None,
order_category: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: Some(PaymentMethodType::Credit),
customer_id: None,
request_incremental_authorization: false,
metadata: None,
minor_amount: MinorUnit::new(1000),
merchant_order_reference_id: None,
shipping_cost: None,
merchant_account_id: None,
merchant_config_currency: None,
all_keys_required: None,
access_token: None,
customer_acceptance: None,
split_payments: None,
request_extended_authorization: None,
setup_mandate_details: None,
enable_overcapture: None,
merchant_account_metadata: None,
},
response: Err(ErrorResponse {
code: "HE_01".to_string(),
message: "Missing required fields".to_string(),
reason: None,
status_code: 400,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result = connector.get_request_body(&test_router_data);
assert!(
result.is_err(),
"Expected error for missing required fields, but got: {result:?}"
);
}
#[test]
fn test_build_request_invalid() {
use common_utils::pii::Email;
let email = Email::try_from("invalid-email@nowhere.com".to_string()).unwrap();
let test_router_data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "INVALID_PAYMENT".to_string(),
attempt_id: "INVALID_ATTEMPT".to_string(),
status: AttemptStatus::Pending,
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
payment_method: PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(None, None, None, None),
auth_type: AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: Some("invalid_id".to_string()),
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_invalid".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentsAuthorizeData {
authentication_data: None,
payment_method_data: PaymentMethodData::Card(Card {
card_number: RawCardNumber(CardNumber::from_str("123").unwrap_or_default()),
card_exp_month: "99".to_string().into(),
card_exp_year: "1999".to_string().into(),
card_cvc: "1".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
card_holder_name: Some("Test User".to_string().into()),
co_badged_card_data: None,
}),
amount: 1000,
order_tax_amount: None,
email: Some(email),
customer_name: None,
currency: Currency::USD,
confirm: true,
integrity_object: None,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: None,
mandate_id: None,
setup_future_usage: None,
off_session: None,
browser_info: None,
order_category: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: Some(PaymentMethodType::Credit),
customer_id: None,
request_incremental_authorization: false,
metadata: None,
minor_amount: MinorUnit::new(1000),
merchant_order_reference_id: None,
shipping_cost: None,
merchant_account_id: None,
merchant_config_currency: None,
all_keys_required: None,
access_token: None,
customer_acceptance: None,
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
split_payments: None,
request_extended_authorization: None,
setup_mandate_details: None,
enable_overcapture: None,
merchant_account_metadata: None,
},
response: Err(ErrorResponse {
code: "HE_02".to_string(),
message: "Invalid format".to_string(),
reason: None,
status_code: 422,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result = connector.get_request_body(&test_router_data);
assert!(
result.is_err(),
"Expected error for invalid field values, but got: {result:?}"
);
}
#[test]
fn test_handle_response_v2_valid_authorize_response() {
use std::str::FromStr;
use common_enums::Currency;
use common_utils::{id_type::MerchantId, pii::Email, types::MinorUnit};
use domain_types::{
connector_types::PaymentFlowData,
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
types::{ConnectorParams, Connectors},
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let email = Email::try_from("testuser@gmail.com".to_string()).unwrap();
let data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "IRRELEVANT_PAYMENT_ID".to_string(),
attempt_id: "IRRELEVANT_ATTEMPT_ID".to_string(),
status: AttemptStatus::Pending,
payment_method: PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(
None,
Some(Address {
address: None,
phone: Some(PhoneDetails {
number: Some("1234567890".to_string().into()),
country_code: Some("+1".to_string()),
}),
email: Some(email.clone()),
}),
None,
None,
),
auth_type: AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: Some("order_QMsUrrLPdwNxPG".to_string()),
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_12345".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentsAuthorizeData {
authentication_data: None,
payment_method_data: PaymentMethodData::Card(Card {
card_number: RawCardNumber(
CardNumber::from_str("5123450000000008").unwrap(),
),
card_exp_month: "12".to_string().into(),
card_exp_year: "2025".to_string().into(),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
card_holder_name: Some("Test User".to_string().into()),
co_badged_card_data: None,
}),
amount: 1000,
order_tax_amount: None,
email: Some(email),
customer_name: None,
currency: Currency::USD,
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: None,
router_return_url: None,
webhook_url: None,
integrity_object: None,
complete_authorize_url: None,
mandate_id: None,
setup_future_usage: None,
off_session: None,
browser_info: Some(BrowserInformation {
color_depth: None,
java_enabled: Some(false),
java_script_enabled: None,
language: Some("en-US".to_string()),
screen_height: Some(1080),
screen_width: Some(1920),
time_zone: None,
ip_address: None,
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
.to_string(),
),
user_agent: Some(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string(),
),
referer: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
}),
order_category: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: Some(common_enums::PaymentMethodType::Credit),
customer_id: None,
request_incremental_authorization: false,
metadata: None,
minor_amount: MinorUnit::new(1000),
merchant_order_reference_id: None,
shipping_cost: None,
merchant_account_id: None,
merchant_config_currency: None,
all_keys_required: None,
access_token: None,
customer_acceptance: None,
split_payments: None,
request_extended_authorization: None,
setup_mandate_details: None,
enable_overcapture: None,
merchant_account_metadata: None,
},
response: Err(ErrorResponse {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
| {
"chunk": 6,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
status_code: 500,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let http_response = Response {
headers: None,
response: br#"{
"razorpay_payment_id":"pay_QMsUsXCDy9sX3b",
"next":[
{
"action":"redirect",
"url":"https://api.razorpay.com/v1/payments/QMsUsXCDy9sX3b/authenticate"
}
]
}"#
.to_vec()
.into(),
status_code: 200,
};
let result = connector
.handle_response_v2(&data, None, http_response)
.unwrap();
assert!(matches!(
result.resource_common_data.status,
AttemptStatus::AuthenticationPending
));
}
#[test]
fn test_handle_authorize_error_response() {
use domain_types::{
connector_flow::Authorize,
connector_types::{PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData},
};
let http_response = Response {
headers: None,
response: br#"{
"error": {
"code": "BAD_REQUEST_ERROR",
"description": "The id provided does not exist",
"source": "internal",
"step": "payment_initiation",
"reason": "input_validation_failed",
"metadata": {}
}
}"#
.to_vec()
.into(),
status_code: 400,
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result =
<dyn ConnectorServiceTrait<DefaultPCIHolder> + Sync as ConnectorIntegrationV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<DefaultPCIHolder>,
PaymentsResponseData,
>>::get_error_response_v2(&**connector, http_response, None)
.unwrap();
let actual_json = to_value(&result).unwrap();
let expected_json = json!({
"code": "BAD_REQUEST_ERROR",
"message": "The id provided does not exist",
"reason": "input_validation_failed",
"status_code": 400,
"attempt_status": "failure",
"connector_transaction_id": null,
"network_advice_code": null,
"network_decline_code": null,
"network_error_message": null
});
assert_eq!(actual_json, expected_json);
}
#[test]
fn test_handle_authorize_missing_required_fields() {
use domain_types::{
connector_flow::Authorize,
connector_types::{PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData},
};
let http_response = Response {
headers: None,
response: br#"{
"error": {
"description": "Missing required fields",
"step": "payment_initiation",
"reason": "input_validation_failed"
}
}"#
.to_vec()
.into(),
status_code: 400,
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result =
<dyn ConnectorServiceTrait<DefaultPCIHolder> + Sync as ConnectorIntegrationV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<DefaultPCIHolder>,
PaymentsResponseData,
>>::get_error_response_v2(&**connector, http_response, None);
assert!(
result.is_err(),
"Expected panic due to missing required fields",
);
}
}
| {
"chunk": 7,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
#[test]
fn test_handle_authorize_invalid_error_fields() {
use domain_types::{
connector_flow::Authorize,
connector_types::{PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData},
};
let http_response = Response {
headers: None,
response: br#"{
"error": {
"code": 500,
"description": "Card number is invalid.",
"step": "payment_authorization",
"reason": "input_validation_failed",
"source": "business",
"metadata": {}
}
}"#
.to_vec()
.into(),
status_code: 400,
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result =
<dyn ConnectorServiceTrait<DefaultPCIHolder> + Sync as ConnectorIntegrationV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<DefaultPCIHolder>,
PaymentsResponseData,
>>::get_error_response_v2(&**connector, http_response, None);
assert!(
result.is_err(),
"Expected panic due to missing required fields"
);
}
#[test]
fn test_handle_response_v2_missing_fields_authorize_response() {
use std::str::FromStr;
use common_enums::Currency;
use common_utils::{id_type::MerchantId, pii::Email, types::MinorUnit};
use domain_types::{
connector_types::PaymentFlowData,
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
types::{ConnectorParams, Connectors},
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let email = Email::try_from("testuser@gmail.com".to_string()).unwrap();
let data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "IRRELEVANT_PAYMENT_ID".to_string(),
attempt_id: "IRRELEVANT_ATTEMPT_ID".to_string(),
status: AttemptStatus::Pending,
payment_method: PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(
None,
Some(Address {
address: None,
phone: Some(PhoneDetails {
number: Some("1234567890".to_string().into()),
country_code: Some("+1".to_string()),
}),
email: Some(email.clone()),
}),
None,
None,
),
auth_type: AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: Some("order_QMsUrrLPdwNxPG".to_string()),
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_12345".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
| {
"chunk": 8,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_9 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentsAuthorizeData {
authentication_data: None,
payment_method_data: PaymentMethodData::Card(Card {
card_number: RawCardNumber(CardNumber::from_str("5123450000000008").unwrap()),
card_exp_month: "12".to_string().into(),
card_exp_year: "2025".to_string().into(),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
card_holder_name: Some("Test User".to_string().into()),
co_badged_card_data: None,
}),
amount: 1000,
order_tax_amount: None,
email: Some(email),
customer_name: None,
currency: Currency::USD,
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: None,
mandate_id: None,
setup_future_usage: None,
off_session: None,
browser_info: Some(BrowserInformation {
color_depth: None,
java_enabled: Some(false),
java_script_enabled: None,
language: Some("en-US".to_string()),
screen_height: Some(1080),
screen_width: Some(1920),
time_zone: None,
ip_address: None,
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
.to_string(),
),
user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string()),
referer: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
}),
order_category: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: Some(common_enums::PaymentMethodType::Credit),
customer_id: None,
request_incremental_authorization: false,
metadata: None,
minor_amount: MinorUnit::new(1000),
merchant_order_reference_id: None,
shipping_cost: None,
integrity_object: None,
merchant_account_id: None,
merchant_config_currency: None,
all_keys_required: None,
access_token: None,
customer_acceptance: None,
split_payments: None,
request_extended_authorization: None,
setup_mandate_details: None,
enable_overcapture: None,
merchant_account_metadata: None,
},
response: Err(ErrorResponse {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: 500,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let http_response = Response {
headers: None,
response: br#"{
"next":[
{
"action":"redirect",
"url":"https://api.razorpay.com/v1/payments/QMsUsXCDy9sX3b/authenticate"
}
]
}"#
.to_vec()
| {
"chunk": 9,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_10 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
.into(),
status_code: 200,
};
let result = connector.handle_response_v2(&data, None, http_response);
assert!(
result.is_err(),
"Expected error due to missing razorpay_payment_id, but got success."
);
}
#[test]
fn test_handle_response_v2_invalid_json_authorize_response() {
use std::str::FromStr;
use common_enums::Currency;
use common_utils::{id_type::MerchantId, pii::Email, types::MinorUnit};
use domain_types::{
connector_types::PaymentFlowData,
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
types::{ConnectorParams, Connectors},
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let email = Email::try_from("testuser@gmail.com".to_string()).unwrap();
let data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "IRRELEVANT_PAYMENT_ID".to_string(),
attempt_id: "IRRELEVANT_ATTEMPT_ID".to_string(),
status: AttemptStatus::Pending,
payment_method: PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(
None,
Some(Address {
address: None,
phone: Some(PhoneDetails {
number: Some("1234567890".to_string().into()),
country_code: Some("+1".to_string()),
}),
email: Some(email.clone()),
}),
None,
None,
),
auth_type: AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: Some("order_QMsUrrLPdwNxPG".to_string()),
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_12345".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentsAuthorizeData {
authentication_data: None,
payment_method_data: PaymentMethodData::Card(Card {
card_number: RawCardNumber(CardNumber::from_str("5123450000000008").unwrap()),
card_exp_month: "12".to_string().into(),
card_exp_year: "2025".to_string().into(),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
card_holder_name: Some("Test User".to_string().into()),
| {
"chunk": 10,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_11 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
co_badged_card_data: None,
}),
amount: 1000,
order_tax_amount: None,
email: Some(email),
customer_name: None,
currency: Currency::USD,
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: None,
mandate_id: None,
setup_future_usage: None,
off_session: None,
browser_info: Some(BrowserInformation {
color_depth: None,
java_enabled: Some(false),
java_script_enabled: None,
language: Some("en-US".to_string()),
screen_height: Some(1080),
screen_width: Some(1920),
time_zone: None,
ip_address: None,
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
.to_string(),
),
user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string()),
referer: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
}),
order_category: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: Some(common_enums::PaymentMethodType::Credit),
customer_id: None,
request_incremental_authorization: false,
metadata: None,
minor_amount: MinorUnit::new(1000),
merchant_order_reference_id: None,
shipping_cost: None,
integrity_object: None,
merchant_account_id: None,
merchant_config_currency: None,
all_keys_required: None,
access_token: None,
customer_acceptance: None,
split_payments: None,
request_extended_authorization: None,
setup_mandate_details: None,
enable_overcapture: None,
merchant_account_metadata: None,
},
response: Err(ErrorResponse {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: 500,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let http_response = Response {
headers: None,
response: br#"{"razorpay_payment_id": "pay_xyz", "next": [ { "action": "redirect" "url": "https://api.razorpay.com/v1/payments/xyz/authenticate" } ]"#.to_vec().into(),
status_code: 200,
};
let result = connector.handle_response_v2(&data, None, http_response);
assert!(
result.is_err(),
"Expected error due to missing razorpay_payment_id, but got success."
);
}
mod order {
use common_utils::{pii::Email, request::RequestContent};
use domain_types::{
payment_address::{Address, PhoneDetails},
payment_method_data::DefaultPCIHolder,
router_data::ConnectorAuthType,
types::{ConnectorParams, Connectors},
};
use interfaces::connector_types::BoxedConnector;
use serde_json::{to_value, Value};
use crate::connectors::Razorpay;
#[test]
fn test_build_request_valid_order() {
use common_enums::Currency;
use common_utils::{id_type::MerchantId, request::RequestContent, types::MinorUnit};
use domain_types::{
connector_types::PaymentCreateOrderData,
| {
"chunk": 11,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_12 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
};
use serde_json::{to_value, Value};
let email = Email::try_from("testuser@gmail.com".to_string()).unwrap();
let test_router_data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: domain_types::connector_types::PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "IRRELEVANT_PAYMENT_ID".to_string(),
attempt_id: "IRRELEVANT_ATTEMPT_ID".to_string(),
status: common_enums::AttemptStatus::Pending,
payment_method: common_enums::PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(
None,
Some(Address {
address: None,
phone: Some(PhoneDetails {
number: Some("1234567890".to_string().into()),
country_code: Some("+1".to_string()),
}),
email: Some(email.clone()),
}),
None,
None,
),
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_12345".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: domain_types::types::Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentCreateOrderData {
amount: MinorUnit::new(1000),
currency: Currency::USD,
integrity_object: None,
metadata: None,
webhook_url: None,
},
response: Err(ErrorResponse {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: 500,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result = connector.get_request_body(&test_router_data).unwrap();
let actual_json: Value = match result {
Some(RequestContent::Json(payload)) => {
| {
"chunk": 12,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_13 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
to_value(&payload).expect("Failed to serialize payload")
}
Some(RequestContent::RawBytes(bytes)) => {
// Handle raw bytes - try to parse as JSON
let json_str =
String::from_utf8(bytes).expect("Failed to convert bytes to string");
serde_json::from_str(&json_str).expect("Failed to parse bytes as JSON")
}
Some(RequestContent::FormUrlEncoded(form_data)) => {
// Convert form data to JSON for comparison
to_value(&form_data).expect("Failed to serialize form data")
}
None => panic!("Expected some request content"),
Some(other) => panic!("Unexpected RequestContent type: {other:?}"),
};
assert_eq!(actual_json["amount"], 1000);
assert_eq!(actual_json["currency"], "USD");
let receipt_value = &actual_json["receipt"];
assert!(
receipt_value.is_string(),
"Expected receipt to be a string, got: {receipt_value:?}"
);
let receipt_str = receipt_value.as_str().unwrap();
assert!(!receipt_str.is_empty(), "Expected non-empty receipt string");
}
#[test]
fn test_build_request_missing() {
use common_enums::Currency;
use common_utils::{id_type::MerchantId, types::MinorUnit};
use domain_types::{
connector_types::PaymentCreateOrderData,
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
};
use crate::connectors::Razorpay;
let test_router_data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: domain_types::connector_types::PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "".to_string(),
attempt_id: "".to_string(),
status: common_enums::AttemptStatus::Pending,
payment_method: common_enums::PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::default(),
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentCreateOrderData {
amount: MinorUnit::new(0),
currency: Currency::default(),
integrity_object: None,
| {
"chunk": 13,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_14 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
metadata: None,
webhook_url: None,
},
response: Err(ErrorResponse {
code: "HE_01".to_string(),
message: "Missing required fields".to_string(),
reason: None,
status_code: 400,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result = connector.get_request_body(&test_router_data);
let req = result.unwrap();
let actual_json: Value = match req {
Some(RequestContent::Json(payload)) => {
to_value(&payload).expect("Failed to serialize payload")
}
None => {
return;
}
Some(RequestContent::RawBytes(bytes)) => {
let json_str =
String::from_utf8(bytes).expect("Failed to convert bytes to string");
serde_json::from_str(&json_str).expect("Failed to parse bytes as JSON")
}
Some(RequestContent::FormUrlEncoded(form_data)) => {
to_value(&form_data).expect("Failed to serialize form data")
}
Some(other) => panic!("Unexpected RequestContent type: {other:?}"),
};
assert_eq!(actual_json["amount"], 0);
assert_eq!(actual_json["currency"], "USD");
let receipt_value = &actual_json["receipt"];
assert!(
receipt_value.is_string(),
"Expected receipt to be a string, got: {receipt_value:?}"
);
}
#[test]
fn test_build_request_invalid() {
use common_enums::{
AttemptStatus, AuthenticationType, Currency, PaymentMethod, PaymentMethodType,
};
use common_utils::{id_type::MerchantId, types::MinorUnit};
use domain_types::{
connector_types::{PaymentFlowData, PaymentsAuthorizeData},
payment_address::PaymentAddress,
payment_method_data::{Card, PaymentMethodData},
router_data::ErrorResponse,
router_data_v2::RouterDataV2,
types::{ConnectorParams, Connectors},
};
use crate::connectors::Razorpay;
let test_router_data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "invalid_payment_id".to_string(),
attempt_id: "invalid_attempt_id".to_string(),
status: AttemptStatus::Pending,
payment_method: PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(None, None, None, None),
auth_type: AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: Some("order_invalid".to_string()),
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_invalid".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
| {
"chunk": 14,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_15 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "invalid_key".to_string().into(),
key1: "invalid_key1".to_string().into(),
},
request: PaymentsAuthorizeData {
authentication_data: None,
payment_method_data: PaymentMethodData::Card(Card {
card_number: Default::default(),
card_exp_month: "".to_string().into(),
card_exp_year: "".to_string().into(),
card_cvc: "".to_string().into(),
card_issuer: None,
card_network: None,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: None,
card_holder_name: Some("Test User".to_string().into()),
co_badged_card_data: None,
}),
amount: 1000,
order_tax_amount: None,
email: None,
customer_name: None,
currency: Currency::USD,
confirm: true,
statement_descriptor_suffix: None,
statement_descriptor: None,
capture_method: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: None,
mandate_id: None,
setup_future_usage: None,
off_session: None,
browser_info: None,
order_category: None,
session_token: None,
enrolled_for_3ds: false,
related_transaction_id: None,
payment_experience: None,
payment_method_type: Some(PaymentMethodType::Credit),
customer_id: None,
request_incremental_authorization: false,
metadata: None,
integrity_object: None,
minor_amount: MinorUnit::new(1000),
merchant_order_reference_id: None,
shipping_cost: None,
merchant_account_id: None,
merchant_config_currency: None,
all_keys_required: None,
access_token: None,
customer_acceptance: None,
split_payments: None,
request_extended_authorization: None,
setup_mandate_details: None,
enable_overcapture: None,
merchant_account_metadata: None,
},
response: Err(ErrorResponse {
code: "HE_INVALID".to_string(),
message: "Invalid request body".to_string(),
reason: None,
status_code: 422,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result = connector.get_request_body(&test_router_data);
assert!(
result.is_err(),
"Expected error for invalid request data, but got: {result:?}"
);
}
}
#[test]
fn test_handle_response_v2_valid_order_response() {
use common_enums::Currency;
use common_utils::{id_type::MerchantId, pii::Email, types::MinorUnit};
| {
"chunk": 15,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_16 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
use domain_types::{
connector_types::{PaymentCreateOrderData, PaymentFlowData},
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
types::{ConnectorParams, Connectors},
};
let email = Email::try_from("testuser@gmail.com".to_string()).unwrap();
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "IRRELEVANT_PAYMENT_ID".to_string(),
attempt_id: "IRRELEVANT_ATTEMPT_ID".to_string(),
status: common_enums::AttemptStatus::Pending,
payment_method: common_enums::PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(
None,
Some(Address {
address: None,
phone: Some(PhoneDetails {
number: Some("1234567890".to_string().into()),
country_code: Some("+1".to_string()),
}),
email: Some(email.clone()),
}),
None,
None,
),
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_12345".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentCreateOrderData {
amount: MinorUnit::new(1000),
currency: Currency::USD,
integrity_object: None,
metadata: None,
webhook_url: None,
},
response: Err(ErrorResponse {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: 500,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let http_response = Response {
headers: None,
response: br#"{
"amount":1000,
"amount_due":1000,
"amount_paid":0,
"attempts":0,
"created_at":1745490447,
"currency":"USD",
"entity":"order",
"id":"order_QMrTOdLWvEHsXz",
"notes":[],
"offer_id":null,
"receipt":"141674f6-30d3-4a17-b904-27fe6ca085c7",
"status":"created"
}"#
| {
"chunk": 16,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_17 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
.to_vec()
.into(),
status_code: 200,
};
let result = connector
.handle_response_v2(&data, None, http_response)
.unwrap();
assert_eq!(
result.response.unwrap().order_id,
"order_QMrTOdLWvEHsXz".to_string()
);
}
#[test]
fn test_handle_response_missing() {
use common_enums::Currency;
use common_utils::{id_type::MerchantId, pii::Email, types::MinorUnit};
use domain_types::{
connector_types::PaymentCreateOrderData,
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
types::{ConnectorParams, Connectors},
};
let email = Email::try_from("testuser@gmail.com".to_string()).unwrap();
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "IRRELEVANT_PAYMENT_ID".to_string(),
attempt_id: "IRRELEVANT_ATTEMPT_ID".to_string(),
status: common_enums::AttemptStatus::Pending,
payment_method: common_enums::PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(
None,
Some(Address {
address: None,
phone: Some(PhoneDetails {
number: Some("1234567890".to_string().into()),
country_code: Some("+1".to_string()),
}),
email: Some(email.clone()),
}),
None,
None,
),
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_12345".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentCreateOrderData {
amount: MinorUnit::new(1000),
currency: Currency::USD,
integrity_object: None,
metadata: None,
webhook_url: None,
},
response: Err(ErrorResponse {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: 500,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let http_response = Response {
headers: None,
response: br#"{
| {
"chunk": 17,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_18 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
"amount":1000,
"currency":"USD",
"status":"created"
}"#
.to_vec()
.into(),
status_code: 200,
};
let result = connector.handle_response_v2(&data, None, http_response);
assert!(
result.is_err(),
"Expected error due to missing order_id or receipt"
);
}
#[test]
fn test_handle_response_invalid() {
use common_enums::Currency;
use common_utils::{id_type::MerchantId, pii::Email, types::MinorUnit};
use domain_types::{
connector_types::PaymentCreateOrderData,
payment_address::PaymentAddress,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
types::{ConnectorParams, Connectors},
};
let email = Email::try_from("testuser@gmail.com".to_string()).unwrap();
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: PaymentFlowData {
merchant_id: MerchantId::default(),
customer_id: None,
connector_customer: None,
payment_id: "IRRELEVANT_PAYMENT_ID".to_string(),
attempt_id: "IRRELEVANT_ATTEMPT_ID".to_string(),
status: common_enums::AttemptStatus::Pending,
payment_method: common_enums::PaymentMethod::Card,
description: None,
return_url: None,
address: PaymentAddress::new(
None,
Some(Address {
address: None,
phone: Some(PhoneDetails {
number: Some("1234567890".to_string().into()),
country_code: Some("+1".to_string()),
}),
email: Some(email.clone()),
}),
None,
None,
),
auth_type: common_enums::AuthenticationType::NoThreeDs,
connector_meta_data: None,
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
preprocessing_id: None,
connector_api_version: None,
connector_request_reference_id: "ref_12345".to_string(),
test_mode: None,
connector_http_status_code: None,
external_latency: None,
raw_connector_response: None,
connectors: Connectors {
razorpay: ConnectorParams {
base_url: "https://api.razorpay.com/".to_string(),
dispute_base_url: None,
..Default::default()
},
..Default::default()
},
vault_headers: None,
connector_response_headers: None,
raw_connector_request: None,
minor_amount_capturable: None,
connector_response: None,
recurring_mandate_payment_data: None,
},
connector_auth_type: ConnectorAuthType::BodyKey {
api_key: "dummy_api_key".to_string().into(),
key1: "dummy_key1".to_string().into(),
},
request: PaymentCreateOrderData {
amount: MinorUnit::new(1000),
currency: Currency::USD,
integrity_object: None,
metadata: None,
webhook_url: None,
},
response: Err(ErrorResponse {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: 500,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
let http_response = Response {
| {
"chunk": 18,
"crate": "connector-integration",
"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_connector-integration_-7309825778239710861_19 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/test.rs
headers: None,
response: br#"{
"amount":1000,
"currency":"USD",
"status":"created"
}"#
.to_vec()
.into(),
status_code: 500,
};
let result = connector.handle_response_v2(&data, None, http_response);
assert!(
result.is_err(),
"Expected error due to invalid response format"
);
}
#[test]
fn test_handle_error_response_valid() {
let http_response = Response {
headers: None,
response: br#"{
"error": {
"code": "BAD_REQUEST_ERROR",
"description": "Order receipt should be unique.",
"step": "payment_initiation",
"reason": "input_validation_failed",
"source": "business",
"metadata": {
"order_id": "order_OL0t841dI8F9NV"
}
}
}"#
.to_vec()
.into(),
status_code: 400,
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result =
<dyn ConnectorServiceTrait<DefaultPCIHolder> + Sync as ConnectorIntegrationV2<
domain_types::connector_flow::CreateOrder,
domain_types::connector_types::PaymentFlowData,
domain_types::connector_types::PaymentCreateOrderData,
domain_types::connector_types::PaymentCreateOrderResponse,
>>::get_error_response_v2(&**connector, http_response, None)
.unwrap();
let actual_json = to_value(&result).unwrap();
let expected_json = json!({
"code": "BAD_REQUEST_ERROR",
"message": "Order receipt should be unique.",
"reason": "input_validation_failed",
"status_code": 400,
"attempt_status": "failure",
"connector_transaction_id": null,
"network_advice_code": null,
"network_decline_code": null,
"network_error_message": null
});
assert_eq!(actual_json, expected_json);
}
#[test]
fn test_handle_error_response_invalid_json() {
let http_response = Response {
headers: None,
response: br#"{ "error": { "code": "BAD_REQUEST_ERROR" "#.to_vec().into(),
status_code: 400,
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result =
<dyn ConnectorServiceTrait<DefaultPCIHolder> + Sync as ConnectorIntegrationV2<
domain_types::connector_flow::CreateOrder,
domain_types::connector_types::PaymentFlowData,
domain_types::connector_types::PaymentCreateOrderData,
domain_types::connector_types::PaymentCreateOrderResponse,
>>::get_error_response_v2(&**connector, http_response, None);
assert!(result.is_err(), "Expected error for invalid JSON");
}
#[test]
fn test_handle_error_response_missing_error_field() {
let http_response = Response {
headers: None,
response: br#"{
"message": "Some generic message",
"status": "failed"
}"#
.to_vec()
.into(),
status_code: 400,
};
let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Razorpay::new());
let result =
<dyn ConnectorServiceTrait<DefaultPCIHolder> + Sync as ConnectorIntegrationV2<
domain_types::connector_flow::CreateOrder,
domain_types::connector_types::PaymentFlowData,
domain_types::connector_types::PaymentCreateOrderData,
domain_types::connector_types::PaymentCreateOrderResponse,
>>::get_error_response_v2(&**connector, http_response, None)
.unwrap();
let actual_json = to_value(&result).unwrap();
let expected_json = json!({
"code": "ROUTE_ERROR",
"message": "Some generic message",
"reason": "Some generic message",
"status_code": 400,
"attempt_status": "failure",
"connector_transaction_id": null,
| {
"chunk": 19,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
use std::collections::HashMap;
use base64::{engine::general_purpose::STANDARD, Engine};
use common_enums::{self, AttemptStatus, CardNetwork};
use common_utils::{ext_traits::ByteSliceExt, pii::Email, request::Method, types::MinorUnit};
use domain_types::{
connector_flow::{Authorize, Capture, CreateOrder, RSync, Refund},
connector_types::{
PaymentCreateOrderData, PaymentCreateOrderResponse, PaymentFlowData, PaymentsAuthorizeData,
PaymentsCaptureData, PaymentsResponseData, RefundFlowData, RefundSyncData, RefundsData,
RefundsResponseData, ResponseId,
},
errors,
payment_method_data::{Card, PaymentMethodData, PaymentMethodDataTypes, RawCardNumber},
router_data::ConnectorAuthType,
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use tracing::info;
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub enum Currency {
#[default]
USD,
EUR,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Amount {
pub currency: common_enums::Currency,
pub value: MinorUnit,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CardBrand {
Visa,
}
#[derive(Debug, PartialEq)]
pub enum ConnectorError {
ParsingFailed,
NotImplemented,
FailedToObtainAuthType,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayCard<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
number: RawCardNumber<T>,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Option<Secret<String>>,
holder_name: Option<Secret<String>>,
brand: Option<CardNetwork>,
network_payment_reference: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "lowercase")]
pub enum RazorpayPaymentMethod<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
#[serde(rename = "scheme")]
RazorpayCard(Box<RazorpayCard<T>>),
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub enum AuthType {
#[default]
PreAuth,
}
#[serde_with::skip_serializing_none]
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Address {
city: String,
country: common_enums::CountryAlpha2,
house_number_or_name: Secret<String>,
postal_code: Secret<String>,
state_or_province: Option<Secret<String>>,
street: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum PaymentMethod<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
RazorpayPaymentMethod(Box<RazorpayPaymentMethod<T>>),
}
#[serde_with::skip_serializing_none]
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct CardDetails<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub number: RawCardNumber<T>,
pub name: Option<Secret<String>>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Secret<String>,
pub cvv: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
pub enum AuthenticationChannel {
#[default]
Browser,
App,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct AuthenticationDetails {
pub authentication_channel: AuthenticationChannel,
}
#[serde_with::skip_serializing_none]
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct BrowserInfo {
pub java_enabled: Option<bool>,
pub javascript_enabled: Option<bool>,
pub timezone_offset: Option<i32>,
pub color_depth: Option<i32>,
pub screen_width: Option<i32>,
pub screen_height: Option<i32>,
pub language: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayPaymentRequest<
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub amount: MinorUnit,
pub currency: String,
pub contact: Secret<String>,
pub email: Email,
pub order_id: String,
pub method: PaymentMethodType,
pub card: PaymentMethodSpecificData<T>,
pub authentication: Option<AuthenticationDetails>,
pub browser: Option<BrowserInfo>,
pub ip: Secret<String>,
pub referer: String,
pub user_agent: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged, rename_all = "snake_case")]
pub enum PaymentMethodSpecificData<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
Card(CardDetails<T>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PaymentMethodType {
Card,
Wallet,
Upi,
Emi,
Netbanking,
}
pub struct RazorpayRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for RazorpayRouterData<T> {
type Error = error_stack::Report<domain_types::errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
pub enum RazorpayAuthType {
AuthToken(Secret<String>),
ApiKeySecret {
api_key: Secret<String>,
api_secret: Secret<String>,
},
}
impl RazorpayAuthType {
pub fn generate_authorization_header(&self) -> String {
let auth_type_name = match self {
RazorpayAuthType::AuthToken(_) => "AuthToken",
RazorpayAuthType::ApiKeySecret { .. } => "ApiKeySecret",
};
info!("Type of auth Token is {}", auth_type_name);
match self {
RazorpayAuthType::AuthToken(token) => format!("Bearer {}", token.peek()),
RazorpayAuthType::ApiKeySecret {
api_key,
api_secret,
} => {
let credentials = format!("{}:{}", api_key.peek(), api_secret.peek());
let encoded = STANDARD.encode(credentials);
format!("Basic {encoded}")
}
}
}
}
impl TryFrom<&ConnectorAuthType> for RazorpayAuthType {
type Error = domain_types::errors::ConnectorError;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self::AuthToken(api_key.to_owned())),
ConnectorAuthType::SignatureKey {
api_key,
api_secret,
..
} => Ok(Self::ApiKeySecret {
api_key: api_key.to_owned(),
api_secret: api_secret.to_owned(),
}),
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self::ApiKeySecret {
api_key: api_key.to_owned(),
api_secret: key1.to_owned(),
}),
_ => Err(domain_types::errors::ConnectorError::FailedToObtainAuthType),
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<(&Card<T>, Option<Secret<String>>)> for RazorpayPaymentMethod<T>
{
type Error = ConnectorError;
fn try_from(
(card, card_holder_name): (&Card<T>, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let razorpay_card = RazorpayCard {
number: card.card_number.clone(),
expiry_month: card.card_exp_month.clone(),
expiry_year: card.card_exp_year.clone(),
cvc: Some(card.card_cvc.clone()),
holder_name: card_holder_name,
brand: card.card_network.clone(),
network_payment_reference: None,
};
Ok(RazorpayPaymentMethod::RazorpayCard(Box::new(razorpay_card)))
}
}
fn extract_payment_method_and_data<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
payment_method_data: &PaymentMethodData<T>,
customer_name: Option<String>,
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
) -> Result<(PaymentMethodType, PaymentMethodSpecificData<T>), domain_types::errors::ConnectorError>
{
match payment_method_data {
PaymentMethodData::Card(card_data) => {
let card_holder_name = customer_name.clone();
let card = PaymentMethodSpecificData::Card(CardDetails {
number: card_data.card_number.clone(),
name: card_holder_name.map(Secret::new),
expiry_month: Some(card_data.card_exp_month.clone()),
expiry_year: card_data.card_exp_year.clone(),
cvv: Some(card_data.card_cvc.clone()),
});
Ok((PaymentMethodType::Card, card))
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::OpenBanking(_) => {
Err(domain_types::errors::ConnectorError::NotImplemented(
"Only Card payment method is supported for Razorpay".to_string(),
))
}
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<(
&RazorpayRouterData<
&RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
&Card<T>,
)> for RazorpayPaymentRequest<T>
{
type Error = error_stack::Report<domain_types::errors::ConnectorError>;
fn try_from(
value: (
&RazorpayRouterData<
&RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
&Card<T>,
),
) -> Result<Self, Self::Error> {
let (item, _card_data) = value;
let amount = item.amount;
let currency = item.router_data.request.currency.to_string();
let billing = item
.router_data
.resource_common_data
.address
.get_payment_billing();
let contact = billing
.and_then(|billing| billing.phone.as_ref())
.and_then(|phone| phone.number.clone())
.ok_or(domain_types::errors::ConnectorError::MissingRequiredField {
field_name: "contact",
})?;
let billing_email = item
.router_data
.resource_common_data
.get_billing_email()
.ok();
let email = billing_email
.or(item.router_data.request.email.clone())
.ok_or(domain_types::errors::ConnectorError::MissingRequiredField {
field_name: "email",
})?;
let order_id = item
.router_data
.resource_common_data
.reference_id
.clone()
.ok_or(domain_types::errors::ConnectorError::MissingRequiredField {
field_name: "order_id",
})?;
let (method, card) = extract_payment_method_and_data(
&item.router_data.request.payment_method_data,
item.router_data.request.customer_name.clone(),
)?;
let browser_info_opt = item.router_data.request.browser_info.as_ref();
let authentication_channel = match browser_info_opt {
Some(_) => AuthenticationChannel::Browser,
None => AuthenticationChannel::App,
};
let authentication = Some(AuthenticationDetails {
authentication_channel,
});
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
let browser = browser_info_opt.map(|info| BrowserInfo {
java_enabled: info.java_enabled,
javascript_enabled: info.java_script_enabled,
timezone_offset: info.time_zone,
color_depth: info.color_depth.map(|v| v as i32),
screen_width: info.screen_width.map(|v| v as i32),
screen_height: info.screen_height.map(|v| v as i32),
language: info.language.clone(),
});
let ip = item
.router_data
.request
.get_ip_address_as_optional()
.map(|ip| Secret::new(ip.expose()))
.unwrap_or_else(|| Secret::new("127.0.0.1".to_string()));
let user_agent = item
.router_data
.request
.browser_info
.as_ref()
.and_then(|info| info.get_user_agent().ok())
.unwrap_or_else(|| "Mozilla/5.0".to_string());
let referer = item
.router_data
.request
.browser_info
.as_ref()
.and_then(|info| info.get_referer().ok())
.unwrap_or_else(|| "https://example.com".to_string());
Ok(RazorpayPaymentRequest {
amount,
currency,
contact,
email,
order_id,
method,
card,
authentication,
browser,
ip,
referer,
user_agent,
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
&RazorpayRouterData<
&RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
> for RazorpayPaymentRequest<T>
{
type Error = error_stack::Report<domain_types::errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<
&RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(card) => RazorpayPaymentRequest::try_from((item, card)),
_ => Err(domain_types::errors::ConnectorError::NotImplemented(
"Only card payments are supported".into(),
)
.into()),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayPaymentResponse {
pub razorpay_payment_id: String,
pub next: Option<Vec<NextAction>>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct NextAction {
pub action: String,
pub url: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged, rename_all = "snake_case")]
pub enum RazorpayResponse {
PaymentResponse(Box<RazorpayPaymentResponse>),
PsyncResponse(Box<RazorpayPsyncResponse>),
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayPsyncResponse {
pub id: String,
pub entity: String,
pub amount: MinorUnit,
pub base_amount: i64,
pub currency: String,
pub base_currency: String,
pub status: RazorpayStatus,
pub method: PaymentMethodType,
pub order_id: Option<String>,
pub invoice_id: Option<String>,
pub description: Option<String>,
pub international: bool,
pub refund_status: Option<String>,
pub amount_refunded: i64,
pub captured: bool,
pub email: Email,
pub contact: Secret<String>,
pub fee: Option<i64>,
pub tax: Option<i64>,
pub error_code: Option<String>,
pub error_description: Option<String>,
pub error_source: Option<String>,
pub error_step: Option<String>,
pub error_reason: Option<String>,
pub notes: Option<HashMap<String, String>>,
pub created_at: i64,
pub card_id: Option<String>,
pub card: Option<SyncCardDetails>,
pub upi: Option<SyncUPIDetails>,
pub acquirer_data: Option<AcquirerData>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Deserialize)]
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
#[serde(rename_all = "snake_case")]
pub struct RazorpayRefundResponse {
pub id: String,
pub status: RazorpayRefundStatus,
pub receipt: Option<String>,
pub amount: MinorUnit,
pub currency: String,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayRefundRequest {
pub amount: MinorUnit,
}
impl ForeignTryFrom<RazorpayRefundStatus> for common_enums::RefundStatus {
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(item: RazorpayRefundStatus) -> Result<Self, Self::Error> {
match item {
RazorpayRefundStatus::Failed => Ok(Self::Failure),
RazorpayRefundStatus::Pending | RazorpayRefundStatus::Created => Ok(Self::Pending),
RazorpayRefundStatus::Processed => Ok(Self::Success),
}
}
}
impl
TryFrom<
&RazorpayRouterData<
&RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
>,
> for RazorpayRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<
&RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
}
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct SyncCardDetails {
pub id: String,
pub entity: String,
pub name: String,
pub last4: String,
pub network: String,
pub r#type: String,
pub issuer: Option<String>,
pub emi: bool,
pub sub_type: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct SyncUPIDetails {
pub payer_account_type: String,
pub vpa: Secret<String>,
pub flow: String,
pub bank: String,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct AcquirerData {
pub auth_code: Option<String>,
pub rrn: Option<Secret<String>>,
pub authentication_reference_number: Option<Secret<String>>,
pub bank_transaction_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RazorpayStatus {
Created,
Authorized,
Captured,
Refunded,
Failed,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptureMethod {
#[default]
Automatic,
Manual,
ManualMultiple,
Scheduled,
SequentialAutomatic,
}
pub trait ForeignTryFrom<F>: Sized {
type Error;
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
fn get_authorization_razorpay_payment_status_from_action(
is_manual_capture: bool,
has_next_action: bool,
) -> AttemptStatus {
if has_next_action {
AttemptStatus::AuthenticationPending
} else if is_manual_capture {
AttemptStatus::Authorized
} else {
AttemptStatus::Charged
}
}
fn get_psync_razorpay_payment_status(
is_manual_capture: bool,
razorpay_status: RazorpayStatus,
) -> AttemptStatus {
match razorpay_status {
RazorpayStatus::Created => AttemptStatus::Pending,
RazorpayStatus::Authorized => {
if is_manual_capture {
AttemptStatus::Authorized
} else {
AttemptStatus::Charged
}
}
RazorpayStatus::Captured => AttemptStatus::Charged,
RazorpayStatus::Refunded => AttemptStatus::AutoRefunded,
RazorpayStatus::Failed => AttemptStatus::Failure,
}
}
impl
ForeignTryFrom<(
RazorpayRefundResponse,
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
u16,
)> for RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(response, data, http_code): (
RazorpayRefundResponse,
RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
u16,
),
) -> Result<Self, Self::Error> {
let status = common_enums::RefundStatus::foreign_try_from(response.status)?;
let refunds_response_data = RefundsResponseData {
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
connector_refund_id: response.id,
refund_status: status,
status_code: http_code,
};
Ok(Self {
resource_common_data: RefundFlowData {
status,
..data.resource_common_data
},
response: Ok(refunds_response_data),
..data
})
}
}
impl
ForeignTryFrom<(
RazorpayRefundResponse,
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
u16,
)> for RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(response, data, http_code): (
RazorpayRefundResponse,
RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
u16,
),
) -> Result<Self, Self::Error> {
let status = common_enums::RefundStatus::foreign_try_from(response.status)?;
let refunds_response_data = RefundsResponseData {
connector_refund_id: response.id,
refund_status: status,
status_code: http_code,
};
Ok(Self {
resource_common_data: RefundFlowData {
status,
..data.resource_common_data
},
response: Ok(refunds_response_data),
..data
})
}
}
impl<F, Req>
ForeignTryFrom<(
RazorpayResponse,
RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>,
u16,
Option<common_enums::CaptureMethod>,
bool,
Option<common_enums::PaymentMethodType>,
)> for RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(response, data, _http_code, _capture_method, _is_multiple_capture_psync_flow, _pmt): (
RazorpayResponse,
RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>,
u16,
Option<common_enums::CaptureMethod>,
bool,
Option<common_enums::PaymentMethodType>,
),
) -> Result<Self, Self::Error> {
let is_manual_capture = false;
match response {
RazorpayResponse::PaymentResponse(payment_response) => {
let status =
get_authorization_razorpay_payment_status_from_action(is_manual_capture, true);
let redirect_url = payment_response
.next
.as_ref()
.and_then(|next_actions| next_actions.first())
.map(|action| action.url.clone())
.ok_or_else(
|| domain_types::errors::ConnectorError::MissingRequiredField {
field_name: "next.url",
},
)?;
let form_fields = HashMap::new();
let payment_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
payment_response.razorpay_payment_id.clone(),
),
redirection_data: Some(Box::new(RedirectForm::Form {
endpoint: redirect_url,
method: Method::Get,
form_fields,
})),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: data.resource_common_data.reference_id.clone(),
incremental_authorization_allowed: None,
mandate_reference: None,
status_code: _http_code,
};
let error = None;
Ok(Self {
response: error.map_or_else(|| Ok(payment_response_data), Err),
resource_common_data: PaymentFlowData {
status,
..data.resource_common_data
},
..data
})
}
RazorpayResponse::PsyncResponse(psync_response) => {
let status =
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
get_psync_razorpay_payment_status(is_manual_capture, psync_response.status);
let psync_response_data = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(psync_response.id),
redirection_data: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: data.resource_common_data.reference_id.clone(),
incremental_authorization_allowed: None,
mandate_reference: None,
status_code: _http_code,
};
let error = None;
Ok(Self {
response: error.map_or_else(|| Ok(psync_response_data), Err),
resource_common_data: PaymentFlowData {
status,
..data.resource_common_data
},
..data
})
}
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RazorpayErrorResponse {
StandardError { error: RazorpayError },
SimpleError { message: String },
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayError {
pub code: String,
pub description: String,
pub source: Option<String>,
pub step: Option<String>,
pub reason: Option<String>,
pub metadata: Option<Metadata>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Metadata {
pub order_id: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayOrderRequest {
pub amount: MinorUnit,
pub currency: String,
pub receipt: String,
pub partial_payment: Option<bool>,
pub first_payment_min_amount: Option<MinorUnit>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_capture: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub method: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub discount: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub offer_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(rename = "token[expire_at]", skip_serializing_if = "Option::is_none")]
pub __token_91_expire_at_93_: Option<i64>,
#[serde(rename = "token[max_amount]", skip_serializing_if = "Option::is_none")]
pub __token_91_max_amount_93_: Option<i64>,
#[serde(rename = "token[auth_type]", skip_serializing_if = "Option::is_none")]
pub __token_91_auth_type_93_: Option<String>,
#[serde(rename = "token[frequency]", skip_serializing_if = "Option::is_none")]
pub __token_91_frequency_93_: Option<String>,
#[serde(rename = "bank_account[name]", skip_serializing_if = "Option::is_none")]
pub __bank_account_91_name_93_: Option<String>,
#[serde(
rename = "bank_account[account_number]",
skip_serializing_if = "Option::is_none"
)]
pub __bank_account_91_account_number_93_: Option<String>,
#[serde(rename = "bank_account[ifsc]", skip_serializing_if = "Option::is_none")]
pub __bank_account_91_ifsc_93_: Option<Secret<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub phonepe_switch_context: Option<String>,
#[serde(rename = "notes[crm1]", skip_serializing_if = "Option::is_none")]
pub __notes_91_crm1_93_: Option<String>,
#[serde(rename = "notes[crm2]", skip_serializing_if = "Option::is_none")]
pub __notes_91_crm2_93_: Option<String>,
}
impl
TryFrom<
&RazorpayRouterData<
&RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
>,
> for RazorpayOrderRequest
{
type Error = error_stack::Report<domain_types::errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<
| {
"chunk": 6,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
&RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
>,
) -> Result<Self, Self::Error> {
let request_data = &item.router_data.request;
let converted_amount = item.amount;
// Extract metadata as a HashMap
let metadata_map = item
.router_data
.request
.metadata
.as_ref()
.and_then(|metadata| metadata.as_object())
.map(|obj| {
obj.iter()
.map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_string()))
.collect::<HashMap<String, String>>()
})
.unwrap_or_default();
Ok(RazorpayOrderRequest {
amount: converted_amount,
currency: request_data.currency.to_string(),
receipt: item
.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
partial_payment: None,
first_payment_min_amount: None,
payment_capture: Some(true),
method: metadata_map.get("method").cloned(),
discount: metadata_map
.get("discount")
.and_then(|v| v.parse::<i64>().ok()),
offer_id: metadata_map.get("offer_id").cloned(),
customer_id: metadata_map.get("customer_id").cloned(),
__token_91_expire_at_93_: metadata_map
.get("__token_91_expire_at_93_")
.and_then(|v| v.parse::<i64>().ok()),
__token_91_max_amount_93_: metadata_map
.get("__token_91_max_amount_93_")
.and_then(|v| v.parse::<i64>().ok()),
__token_91_auth_type_93_: metadata_map.get("__token_91_auth_type_93_").cloned(),
__token_91_frequency_93_: metadata_map.get("__token_91_frequency_93_").cloned(),
__bank_account_91_name_93_: metadata_map.get("__bank_account_91_name_93_").cloned(),
__bank_account_91_account_number_93_: metadata_map
.get("__bank_account_91_account_number_93_")
.cloned(),
__bank_account_91_ifsc_93_: metadata_map
.get("__bank_account_91_ifsc_93_")
.cloned()
.map(Secret::new),
account_id: metadata_map.get("account_id").cloned(),
phonepe_switch_context: metadata_map.get("phonepe_switch_context").cloned(),
__notes_91_crm1_93_: metadata_map.get("__notes_91_crm1_93_").cloned(),
__notes_91_crm2_93_: metadata_map.get("__notes_91_crm2_93_").cloned(),
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum RazorpayNotes {
Map(HashMap<String, String>),
EmptyVec(Vec<()>),
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayOrderResponse {
pub id: String,
pub entity: String,
pub amount: MinorUnit,
pub amount_paid: MinorUnit,
pub amount_due: MinorUnit,
pub currency: String,
pub receipt: String,
pub status: String,
pub attempts: u32,
pub notes: Option<RazorpayNotes>,
pub offer_id: Option<String>,
pub created_at: u64,
}
impl
ForeignTryFrom<(
RazorpayOrderResponse,
RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
u16,
bool,
)>
for RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(response, data, _status_code, _): (
RazorpayOrderResponse,
RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
u16,
bool,
),
) -> Result<Self, Self::Error> {
let order_response = PaymentCreateOrderResponse {
order_id: response.id,
};
Ok(Self {
| {
"chunk": 7,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
response: Ok(order_response),
..data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayWebhook {
pub account_id: String,
pub contains: Vec<String>,
pub entity: String,
pub event: String,
pub payload: Payload,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct Payload {
pub payment: Option<PaymentWrapper>,
pub refund: Option<RefundWrapper>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct PaymentWrapper {
pub entity: PaymentEntity,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RefundWrapper {
pub entity: RefundEntity,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct PaymentEntity {
pub id: String,
pub entity: RazorpayEntity,
pub amount: i64,
pub currency: String,
pub status: RazorpayPaymentStatus,
pub order_id: String,
pub invoice_id: Option<String>,
pub international: bool,
pub method: String,
pub amount_refunded: i64,
pub refund_status: Option<String>,
pub captured: bool,
pub description: Option<String>,
pub card_id: Option<String>,
pub bank: Option<String>,
pub wallet: Option<String>,
pub vpa: Option<Secret<String>>,
pub email: Option<Email>,
pub contact: Option<Secret<String>>,
pub notes: Vec<String>,
pub fee: Option<i64>,
pub tax: Option<i64>,
pub error_code: Option<String>,
pub error_description: Option<String>,
pub error_reason: Option<String>,
pub error_source: Option<String>,
pub error_step: Option<String>,
pub acquirer_data: Option<AcquirerData>,
pub card: Option<RazorpayWebhookCard>,
pub token_id: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RefundEntity {
pub id: String,
pub entity: RazorpayEntity,
pub amount: i64,
pub currency: String,
pub payment_id: String,
pub status: RazorpayRefundStatus,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayEntity {
Payment,
Refund,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayPaymentStatus {
Authorized,
Captured,
Failed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RazorpayRefundStatus {
Created,
Processed,
Failed,
Pending,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct RazorpayWebhookCard {
pub id: String,
pub entity: String,
pub name: String,
pub last4: String,
pub network: String,
#[serde(rename = "type")]
pub card_type: String,
pub sub_type: String,
pub issuer: Option<String>,
pub international: bool,
pub iin: String,
pub emi: bool,
}
pub fn get_webhook_object_from_body(
body: Vec<u8>,
) -> Result<Payload, error_stack::Report<errors::ConnectorError>> {
let webhook: RazorpayWebhook = body
.parse_struct("RazorpayWebhook")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(webhook.payload)
}
pub(crate) fn get_razorpay_payment_webhook_status(
entity: RazorpayEntity,
status: RazorpayPaymentStatus,
) -> Result<AttemptStatus, errors::ConnectorError> {
match entity {
RazorpayEntity::Payment => match status {
RazorpayPaymentStatus::Authorized => Ok(AttemptStatus::Authorized),
RazorpayPaymentStatus::Captured => Ok(AttemptStatus::Charged),
RazorpayPaymentStatus::Failed => Ok(AttemptStatus::AuthorizationFailed),
},
RazorpayEntity::Refund => Err(errors::ConnectorError::RequestEncodingFailed),
}
}
pub(crate) fn get_razorpay_refund_webhook_status(
entity: RazorpayEntity,
status: RazorpayRefundStatus,
) -> Result<common_enums::RefundStatus, errors::ConnectorError> {
match entity {
RazorpayEntity::Refund => match status {
RazorpayRefundStatus::Processed => Ok(common_enums::RefundStatus::Success),
RazorpayRefundStatus::Created | RazorpayRefundStatus::Pending => {
Ok(common_enums::RefundStatus::Pending)
}
| {
"chunk": 8,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_9 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
RazorpayRefundStatus::Failed => Ok(common_enums::RefundStatus::Failure),
},
RazorpayEntity::Payment => Err(errors::ConnectorError::RequestEncodingFailed),
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpayCaptureRequest {
pub amount: MinorUnit,
pub currency: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RazorpayCaptureResponse {
pub id: String,
pub entity: RazorpayEntity,
pub amount: i64,
pub currency: String,
pub status: RazorpayPaymentStatus,
pub order_id: String,
pub invoice_id: Option<String>,
pub international: bool,
pub method: String,
pub amount_refunded: i64,
pub refund_status: Option<String>,
pub captured: bool,
pub description: Option<String>,
pub card_id: Option<String>,
pub bank: Option<String>,
pub wallet: Option<String>,
pub vpa: Option<Secret<String>>,
pub email: Option<Email>,
pub contact: Option<Secret<String>>,
pub customer_id: Option<String>,
pub token_id: Option<String>,
pub notes: Vec<String>,
pub fee: Option<i64>,
pub tax: Option<i64>,
pub error_code: Option<String>,
pub error_description: Option<String>,
pub error_reason: Option<String>,
pub error_source: Option<String>,
pub error_step: Option<String>,
pub acquirer_data: Option<AcquirerData>,
}
impl
TryFrom<
&RazorpayRouterData<
&RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
>,
> for RazorpayCaptureRequest
{
type Error = error_stack::Report<domain_types::errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<
&RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let request_data = &item.router_data.request;
Ok(RazorpayCaptureRequest {
amount: item.amount,
currency: request_data.currency.to_string(),
})
}
}
impl<F, Req>
ForeignTryFrom<(
RazorpayCaptureResponse,
RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>,
u16,
)> for RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(response, data, http_code): (
RazorpayCaptureResponse,
RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>,
u16,
),
) -> Result<Self, Self::Error> {
let status = match response.status {
RazorpayPaymentStatus::Captured => AttemptStatus::Charged,
RazorpayPaymentStatus::Authorized => AttemptStatus::Authorized,
RazorpayPaymentStatus::Failed => AttemptStatus::Failure,
};
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(response.id),
redirection_data: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(response.order_id),
incremental_authorization_allowed: None,
mandate_reference: None,
status_code: http_code,
}),
resource_common_data: PaymentFlowData {
status,
..data.resource_common_data
},
..data
})
}
}
// ============ UPI Web Collect Request ============
#[derive(Debug, Serialize)]
pub struct RazorpayWebCollectRequest {
pub currency: String,
pub amount: MinorUnit,
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<Email>,
pub order_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub contact: Option<Secret<String>>,
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub vpa: Option<Secret<String>>,
#[serde(rename = "notes[txn_uuid]", skip_serializing_if = "Option::is_none")]
pub __notes_91_txn_uuid_93_: Option<String>,
#[serde(
rename = "notes[transaction_id]",
skip_serializing_if = "Option::is_none"
)]
pub __notes_91_transaction_id_93_: Option<String>,
| {
"chunk": 9,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_10 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
pub callback_url: String,
pub ip: Secret<String>,
pub referer: String,
pub user_agent: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub flow: Option<String>,
#[serde(rename = "notes[cust_id]", skip_serializing_if = "Option::is_none")]
pub __notes_91_cust_id_93_: Option<String>,
#[serde(rename = "notes[cust_name]", skip_serializing_if = "Option::is_none")]
pub __notes_91_cust_name_93_: Option<String>,
#[serde(rename = "upi[flow]", skip_serializing_if = "Option::is_none")]
pub __upi_91_flow_93_: Option<String>,
#[serde(rename = "upi[type]", skip_serializing_if = "Option::is_none")]
pub __upi_91_type_93_: Option<String>,
#[serde(rename = "upi[end_date]", skip_serializing_if = "Option::is_none")]
pub __upi_91_end_date_93_: Option<i64>,
#[serde(rename = "upi[vpa]", skip_serializing_if = "Option::is_none")]
pub __upi_91_vpa_93_: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub recurring: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(rename = "upi[expiry_time]", skip_serializing_if = "Option::is_none")]
pub __upi_91_expiry_time_93_: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fee: Option<i64>,
#[serde(rename = "notes[BookingID]", skip_serializing_if = "Option::is_none")]
pub __notes_91_booking_id_93: Option<String>,
#[serde(rename = "notes[PNR]", skip_serializing_if = "Option::is_none")]
pub __notes_91_pnr_93: Option<String>,
#[serde(rename = "notes[PaymentID]", skip_serializing_if = "Option::is_none")]
pub __notes_91_payment_id_93: Option<String>,
#[serde(rename = "notes[lob]", skip_serializing_if = "Option::is_none")]
pub __notes_91_lob_93_: Option<String>,
#[serde(
rename = "notes[credit_line_id]",
skip_serializing_if = "Option::is_none"
)]
pub __notes_91_credit_line_id_93_: Option<String>,
#[serde(rename = "notes[loan_id]", skip_serializing_if = "Option::is_none")]
pub __notes_91_loan_id_93_: Option<String>,
#[serde(
rename = "notes[transaction_type]",
skip_serializing_if = "Option::is_none"
)]
pub __notes_91_transaction_type_93_: Option<String>,
#[serde(
rename = "notes[loan_product_code]",
skip_serializing_if = "Option::is_none"
)]
pub __notes_91_loan_product_code_93_: Option<String>,
#[serde(rename = "notes[pg_flow]", skip_serializing_if = "Option::is_none")]
pub __notes_91_pg_flow_93_: Option<String>,
#[serde(rename = "notes[TID]", skip_serializing_if = "Option::is_none")]
pub __notes_91_tid_93: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub account_id: Option<String>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
&RazorpayRouterData<
&RouterDataV2<
domain_types::connector_flow::Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
> for RazorpayWebCollectRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RazorpayRouterData<
&RouterDataV2<
domain_types::connector_flow::Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
) -> Result<Self, Self::Error> {
use domain_types::payment_method_data::{PaymentMethodData, UpiData};
use hyperswitch_masking::PeekInterface;
// Determine flow type and extract VPA based on UPI payment method
let (flow_type, vpa) = match &item.router_data.request.payment_method_data {
PaymentMethodData::Upi(UpiData::UpiCollect(collect_data)) => {
let vpa = collect_data
.vpa_id
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
| {
"chunk": 10,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_11 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
field_name: "vpa_id",
})?
.peek()
.to_string();
(None, Some(vpa))
}
PaymentMethodData::Upi(UpiData::UpiIntent(_))
| PaymentMethodData::Upi(UpiData::UpiQr(_)) => (Some("intent"), None),
_ => (None, None), // Default fallback
};
// Get order_id from the CreateOrder response (stored in reference_id)
let order_id = item
.router_data
.resource_common_data
.reference_id
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "order_id (reference_id)",
})?
.clone();
// Extract metadata as a HashMap
let metadata_map = item
.router_data
.request
.metadata
.as_ref()
.and_then(|metadata| metadata.as_object())
.map(|obj| {
obj.iter()
.map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_string()))
.collect::<HashMap<String, String>>()
})
.unwrap_or_default();
Ok(Self {
currency: item.router_data.request.currency.to_string(),
amount: item.amount,
email: item
.router_data
.resource_common_data
.get_billing_email()
.ok(),
order_id: order_id.to_string(),
contact: item
.router_data
.resource_common_data
.get_billing_phone_number()
.ok(),
method: match &item.router_data.request.payment_method_data {
PaymentMethodData::Upi(_) => "upi".to_string(),
PaymentMethodData::Card(_) => "card".to_string(),
_ => "card".to_string(), // Default to card
},
vpa: vpa.clone().map(Secret::new),
__notes_91_txn_uuid_93_: metadata_map.get("__notes_91_txn_uuid_93_").cloned(),
__notes_91_transaction_id_93_: metadata_map
.get("__notes_91_transaction_id_93_")
.cloned(),
callback_url: item.router_data.request.get_router_return_url()?,
ip: item
.router_data
.request
.get_ip_address_as_optional()
.map(|ip| Secret::new(ip.expose()))
.unwrap_or_else(|| Secret::new("127.0.0.1".to_string())),
referer: item
.router_data
.request
.browser_info
.as_ref()
.and_then(|info| info.get_referer().ok())
.unwrap_or_else(|| "https://example.com".to_string()),
user_agent: item
.router_data
.request
.browser_info
.as_ref()
.and_then(|info| info.get_user_agent().ok())
.unwrap_or_else(|| "Mozilla/5.0".to_string()),
description: Some("".to_string()),
flow: flow_type.map(|s| s.to_string()),
__notes_91_cust_id_93_: metadata_map.get("__notes_91_cust_id_93_").cloned(),
__notes_91_cust_name_93_: metadata_map.get("__notes_91_cust_name_93_").cloned(),
__upi_91_flow_93_: metadata_map.get("__upi_91_flow_93_").cloned(),
__upi_91_type_93_: metadata_map.get("__upi_91_type_93_").cloned(),
__upi_91_end_date_93_: metadata_map
.get("__upi_91_end_date_93_")
.and_then(|v| v.parse::<i64>().ok()),
__upi_91_vpa_93_: metadata_map.get("__upi_91_vpa_93_").cloned(),
recurring: None,
customer_id: None,
__upi_91_expiry_time_93_: metadata_map
.get("__upi_91_expiry_time_93_")
.and_then(|v| v.parse::<i64>().ok()),
fee: None,
__notes_91_booking_id_93: metadata_map.get("__notes_91_booking_id_93").cloned(),
__notes_91_pnr_93: metadata_map.get("__notes_91_pnr_93").cloned(),
__notes_91_payment_id_93: metadata_map.get("__notes_91_payment_id_93").cloned(),
| {
"chunk": 11,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_12 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
__notes_91_lob_93_: metadata_map.get("__notes_91_lob_93_").cloned(),
__notes_91_credit_line_id_93_: metadata_map
.get("__notes_91_credit_line_id_93_")
.cloned(),
__notes_91_loan_id_93_: metadata_map.get("__notes_91_loan_id_93_").cloned(),
__notes_91_transaction_type_93_: metadata_map
.get("__notes_91_transaction_type_93_")
.cloned(),
__notes_91_loan_product_code_93_: metadata_map
.get("__notes_91_loan_product_code_93_")
.cloned(),
__notes_91_pg_flow_93_: metadata_map.get("__notes_91_pg_flow_93_").cloned(),
__notes_91_tid_93: metadata_map.get("__notes_91_tid_93").cloned(),
account_id: None,
})
}
}
// ============ UPI Response Types ============
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RazorpayUpiPaymentsResponse {
SuccessIntent {
razorpay_payment_id: String,
link: String,
},
SuccessCollect {
razorpay_payment_id: String,
},
NullResponse {
razorpay_payment_id: Option<String>,
},
Error {
error: RazorpayErrorResponse,
},
}
// Wrapper type for UPI response transformations
#[derive(Debug)]
pub struct RazorpayUpiResponseData {
pub transaction_id: ResponseId,
pub redirection_data: Option<domain_types::router_response_types::RedirectForm>,
}
impl<F, Req>
ForeignTryFrom<(
RazorpayUpiPaymentsResponse,
RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>,
u16,
Vec<u8>, // raw_response
)> for RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>
{
type Error = domain_types::errors::ConnectorError;
fn foreign_try_from(
(upi_response, data, _status_code, _raw_response): (
RazorpayUpiPaymentsResponse,
RouterDataV2<F, PaymentFlowData, Req, PaymentsResponseData>,
u16,
Vec<u8>,
),
) -> Result<Self, Self::Error> {
let (transaction_id, redirection_data) = match upi_response {
RazorpayUpiPaymentsResponse::SuccessIntent {
razorpay_payment_id,
link,
} => {
let redirect_form =
domain_types::router_response_types::RedirectForm::Uri { uri: link };
(
ResponseId::ConnectorTransactionId(razorpay_payment_id),
Some(redirect_form),
)
}
RazorpayUpiPaymentsResponse::SuccessCollect {
razorpay_payment_id,
} => {
// For UPI Collect, there's no link, so no redirection data
(
ResponseId::ConnectorTransactionId(razorpay_payment_id),
None,
)
}
RazorpayUpiPaymentsResponse::NullResponse {
razorpay_payment_id,
} => {
// Handle null response - likely an error condition
match razorpay_payment_id {
Some(payment_id) => (ResponseId::ConnectorTransactionId(payment_id), None),
None => {
// Payment ID is null, this is likely an error
return Err(domain_types::errors::ConnectorError::ResponseHandlingFailed);
}
}
}
RazorpayUpiPaymentsResponse::Error { error: _ } => {
// Handle error case - this should probably return an error instead
return Err(domain_types::errors::ConnectorError::ResponseHandlingFailed);
}
};
let payments_response_data = PaymentsResponseData::TransactionResponse {
resource_id: transaction_id,
redirection_data: redirection_data.map(Box::new),
connector_metadata: None,
mandate_reference: None,
network_txn_id: None,
connector_response_reference_id: data.resource_common_data.reference_id.clone(),
incremental_authorization_allowed: None,
status_code: _status_code,
};
Ok(RouterDataV2 {
response: Ok(payments_response_data),
| {
"chunk": 12,
"crate": "connector-integration",
"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_connector-integration_3490651234547846205_13 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/razorpay/transformers.rs
resource_common_data: PaymentFlowData {
status: AttemptStatus::AuthenticationPending,
..data.resource_common_data
},
..data
})
}
}
| {
"chunk": 13,
"crate": "connector-integration",
"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_connector-integration_-7524950471884079166_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets/transformers.rs
use base64::Engine;
use common_enums::{enums, AttemptStatus};
use common_utils::{errors::CustomResult, request::Method};
use domain_types::{
connector_flow::{Authorize, Capture},
connector_types::{
MandateReference, PaymentFlowData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsResponseData, RefundFlowData, RefundSyncData, RefundsData, RefundsResponseData,
ResponseId,
},
errors::{self, ConnectorError},
payment_method_data::{
ApplePayWalletData, BankRedirectData, Card, PaymentMethodData, PaymentMethodDataTypes,
RawCardNumber, WalletData,
},
router_data::ConnectorAuthType,
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
utils,
};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{connectors::nexinets::NexinetsRouterData, types::ResponseRouterData};
pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
initial_amount: i64,
currency: enums::Currency,
channel: NexinetsChannel,
product: NexinetsProduct,
payment: Option<NexinetsPaymentDetails<T>>,
#[serde(rename = "async")]
nexinets_async: NexinetsAsyncDetails,
merchant_order_id: Option<String>,
}
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsChannel {
#[default]
Ecom,
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NexinetsProduct {
#[default]
Creditcard,
Paypal,
Giropay,
Sofort,
Eps,
Ideal,
Applepay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
pub enum NexinetsPaymentDetails<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
Card(Box<NexiCardDetails<T>>),
Wallet(Box<NexinetsWalletDetails>),
BankRedirects(Box<NexinetsBankRedirects>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexiCardDetails<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
#[serde(flatten)]
card_data: CardDataDetails<T>,
cof_contract: Option<CofContract>,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum CardDataDetails<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
CardDetails(Box<CardDetails<T>>),
PaymentInstrument(Box<PaymentInstrument>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
card_number: RawCardNumber<T>,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
verification: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInstrument {
payment_instrument_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct CofContract {
#[serde(rename = "type")]
recurring_type: RecurringType,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RecurringType {
Unscheduled,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsBankRedirects {
bic: Option<NexinetsBIC>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsAsyncDetails {
pub success_url: Option<String>,
pub cancel_url: Option<String>,
pub failure_url: Option<String>,
}
#[derive(Debug, Serialize)]
pub enum NexinetsBIC {
#[serde(rename = "ABNANL2A")]
AbnAmro,
#[serde(rename = "ASNBNL21")]
AsnBank,
#[serde(rename = "BUNQNL2A")]
Bunq,
#[serde(rename = "INGBNL2A")]
Ing,
#[serde(rename = "KNABNL2H")]
Knab,
#[serde(rename = "RABONL2U")]
Rabobank,
#[serde(rename = "RBRBNL21")]
Regiobank,
#[serde(rename = "SNSBNL2A")]
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_-7524950471884079166_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets/transformers.rs
SnsBank,
#[serde(rename = "TRIONL2U")]
TriodosBank,
#[serde(rename = "FVLBNL22")]
VanLanschot,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum NexinetsWalletDetails {
ApplePayToken(Box<ApplePayDetails>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayDetails {
payment_data: serde_json::Value,
payment_method: ApplepayPaymentMethod,
transaction_identifier: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentMethod {
display_name: String,
network: String,
#[serde(rename = "type")]
token_type: String,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
NexinetsRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for NexinetsPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: NexinetsRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let return_url = item.router_data.resource_common_data.return_url.clone();
let nexinets_async = NexinetsAsyncDetails {
success_url: return_url.clone(),
cancel_url: return_url.clone(),
failure_url: return_url,
};
let (payment, product) = get_payment_details_and_product(&item.router_data)?;
let merchant_order_id = match item.router_data.resource_common_data.payment_method {
// Merchant order id is sent only in case of card payment
enums::PaymentMethod::Card => Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
_ => None,
};
Ok(Self {
initial_amount: item.router_data.request.amount,
currency: item.router_data.request.currency,
channel: NexinetsChannel::Ecom,
product,
payment,
nexinets_async,
merchant_order_id,
})
}
}
// Auth Struct
pub struct NexinetsAuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NexinetsAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => {
let auth_key = format!("{}:{}", key1.peek(), api_key.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(Self {
api_key: Secret::new(auth_header),
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
// PaymentsResponse
#[derive(Debug, Deserialize, Clone, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsPaymentStatus {
Success,
Pending,
Ok,
Failure,
Declined,
InProgress,
Expired,
Aborted,
}
fn get_status(status: NexinetsPaymentStatus, method: NexinetsTransactionType) -> AttemptStatus {
match status {
NexinetsPaymentStatus::Success => match method {
NexinetsTransactionType::Preauth => AttemptStatus::Authorized,
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
AttemptStatus::Charged
}
NexinetsTransactionType::Cancel => AttemptStatus::Voided,
},
NexinetsPaymentStatus::Declined
| NexinetsPaymentStatus::Failure
| NexinetsPaymentStatus::Expired
| NexinetsPaymentStatus::Aborted => match method {
NexinetsTransactionType::Preauth => AttemptStatus::AuthorizationFailed,
NexinetsTransactionType::Debit | NexinetsTransactionType::Capture => {
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_-7524950471884079166_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets/transformers.rs
AttemptStatus::CaptureFailed
}
NexinetsTransactionType::Cancel => AttemptStatus::VoidFailed,
},
NexinetsPaymentStatus::Ok => match method {
NexinetsTransactionType::Preauth => AttemptStatus::Authorized,
_ => AttemptStatus::Pending,
},
NexinetsPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
NexinetsPaymentStatus::InProgress => AttemptStatus::Pending,
}
}
impl TryFrom<&enums::BankNames> for NexinetsBIC {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(bank: &enums::BankNames) -> Result<Self, Self::Error> {
match bank {
enums::BankNames::AbnAmro => Ok(Self::AbnAmro),
enums::BankNames::AsnBank => Ok(Self::AsnBank),
enums::BankNames::Bunq => Ok(Self::Bunq),
enums::BankNames::Ing => Ok(Self::Ing),
enums::BankNames::Knab => Ok(Self::Knab),
enums::BankNames::Rabobank => Ok(Self::Rabobank),
enums::BankNames::Regiobank => Ok(Self::Regiobank),
enums::BankNames::SnsBank => Ok(Self::SnsBank),
enums::BankNames::TriodosBank => Ok(Self::TriodosBank),
enums::BankNames::VanLanschot => Ok(Self::VanLanschot),
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: bank.to_string(),
connector: "Nexinets".to_string(),
}
.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPreAuthOrDebitResponse {
order_id: String,
transaction_type: NexinetsTransactionType,
transactions: Vec<NexinetsTransaction>,
payment_instrument: PaymentInstrument,
redirect_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsTransaction {
pub transaction_id: String,
#[serde(rename = "type")]
pub transaction_type: NexinetsTransactionType,
pub currency: enums::Currency,
pub status: NexinetsPaymentStatus,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum NexinetsTransactionType {
Preauth,
Debit,
Capture,
Cancel,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NexinetsPaymentsMetadata {
pub transaction_id: Option<String>,
pub order_id: Option<String>,
pub psync_flow: NexinetsTransactionType,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<ResponseRouterData<NexinetsPreAuthOrDebitResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<NexinetsPreAuthOrDebitResponse, Self>,
) -> Result<Self, Self::Error> {
let transaction = match item.response.transactions.first() {
Some(order) => order,
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let nexinets_metadata = NexinetsPaymentsMetadata {
transaction_id: Some(transaction.transaction_id.clone()),
order_id: Some(item.response.order_id.clone()),
psync_flow: item.response.transaction_type.clone(),
};
let connector_metadata = serde_json::to_value(&nexinets_metadata)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let redirection_data = item
.response
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)));
let resource_id = match item.response.transaction_type.clone() {
NexinetsTransactionType::Preauth
| NexinetsTransactionType::Debit
| NexinetsTransactionType::Capture => {
ResponseId::ConnectorTransactionId(transaction.transaction_id.clone())
}
_ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
let mandate_reference = item
.response
.payment_instrument
.payment_instrument_id
.map(|id| MandateReference {
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_-7524950471884079166_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets/transformers.rs
connector_mandate_id: Some(id.expose()),
payment_method_id: None,
});
Ok(Self {
resource_common_data: PaymentFlowData {
status: get_status(transaction.status.clone(), item.response.transaction_type),
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: redirection_data.map(Box::new),
mandate_reference: mandate_reference.map(Box::new),
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsCaptureOrVoidRequest {
pub initial_amount: i64,
pub currency: enums::Currency,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsOrder {
pub order_id: String,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
NexinetsRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for NexinetsCaptureOrVoidRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: NexinetsRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.router_data.request.amount_to_capture,
currency: item.router_data.request.currency,
})
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsPaymentResponse {
pub transaction_id: String,
pub status: NexinetsPaymentStatus,
pub order: NexinetsOrder,
#[serde(rename = "type")]
pub transaction_type: NexinetsTransactionType,
}
impl<F, T> TryFrom<ResponseRouterData<NexinetsPaymentResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<NexinetsPaymentResponse, Self>,
) -> Result<Self, Self::Error> {
let transaction_id = Some(item.response.transaction_id.clone());
let connector_metadata = serde_json::to_value(NexinetsPaymentsMetadata {
transaction_id,
order_id: Some(item.response.order.order_id.clone()),
psync_flow: item.response.transaction_type.clone(),
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let resource_id = match item.response.transaction_type.clone() {
NexinetsTransactionType::Preauth
| NexinetsTransactionType::Debit
| NexinetsTransactionType::Capture => {
ResponseId::ConnectorTransactionId(item.response.transaction_id)
}
_ => ResponseId::NoResponseId,
};
Ok(Self {
resource_common_data: PaymentFlowData {
status: get_status(item.response.status, item.response.transaction_type),
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: None,
mandate_reference: None,
connector_metadata: Some(connector_metadata),
network_txn_id: None,
connector_response_reference_id: Some(item.response.order.order_id),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
..item.router_data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsRefundRequest {
pub initial_amount: i64,
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_-7524950471884079166_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets/transformers.rs
pub currency: enums::Currency,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
NexinetsRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>,
> for NexinetsRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: NexinetsRouterData<
RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
initial_amount: item.router_data.request.refund_amount,
currency: item.router_data.request.currency,
})
}
}
// Type definition for Refund Response
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NexinetsRefundResponse {
pub transaction_id: String,
pub status: RefundStatus,
pub order: NexinetsOrder,
#[serde(rename = "type")]
pub transaction_type: RefundType,
}
#[allow(dead_code)]
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
Success,
Ok,
Failure,
Declined,
InProgress,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundType {
Refund,
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Failure | RefundStatus::Declined => Self::Failure,
RefundStatus::InProgress | RefundStatus::Ok => Self::Pending,
}
}
}
impl<F> TryFrom<ResponseRouterData<NexinetsRefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<NexinetsRefundResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
status_code: item.http_code,
}),
..item.router_data
})
}
}
impl<F> TryFrom<ResponseRouterData<NexinetsRefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<NexinetsRefundResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id,
refund_status: enums::RefundStatus::from(item.response.status),
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct NexinetsErrorResponse {
pub status: u16,
pub code: u16,
pub message: String,
pub errors: Vec<OrderErrorDetails>,
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct OrderErrorDetails {
pub code: u16,
pub message: String,
pub field: Option<String>,
}
fn get_payment_details_and_product<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
item: &RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
) -> Result<
(Option<NexinetsPaymentDetails<T>>, NexinetsProduct),
error_stack::Report<errors::ConnectorError>,
> {
match &item.request.payment_method_data {
PaymentMethodData::Card(card) => Ok((
Some(get_card_data(item, card)?),
NexinetsProduct::Creditcard,
)),
PaymentMethodData::Wallet(wallet) => Ok(get_wallet_details(wallet)?),
PaymentMethodData::BankRedirect(bank_redirect) => match bank_redirect {
BankRedirectData::Eps { .. } => Ok((None, NexinetsProduct::Eps)),
BankRedirectData::Giropay { .. } => Ok((None, NexinetsProduct::Giropay)),
BankRedirectData::Ideal { bank_name, .. } => Ok((
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_-7524950471884079166_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets/transformers.rs
Some(NexinetsPaymentDetails::BankRedirects(Box::new(
NexinetsBankRedirects {
bic: bank_name
.map(|bank_name| NexinetsBIC::try_from(&bank_name))
.transpose()?,
},
))),
NexinetsProduct::Ideal,
)),
BankRedirectData::Sofort { .. } => Ok((None, NexinetsProduct::Sofort)),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?
}
},
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?
}
}
}
fn get_card_data<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
item: &RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
card: &Card<T>,
) -> Result<NexinetsPaymentDetails<T>, errors::ConnectorError> {
let (card_data, cof_contract) = match is_mandate_payment(&item.request) {
true => {
let card_data = match item.request.off_session {
Some(true) => CardDataDetails::PaymentInstrument(Box::new(PaymentInstrument {
payment_instrument_id: item.request.connector_mandate_id().map(Secret::new),
})),
_ => CardDataDetails::CardDetails(Box::new(get_card_details(card)?)),
};
let cof_contract = Some(CofContract {
recurring_type: RecurringType::Unscheduled,
});
(card_data, cof_contract)
}
false => (
CardDataDetails::CardDetails(Box::new(get_card_details(card)?)),
None,
),
};
Ok(NexinetsPaymentDetails::Card(Box::new(NexiCardDetails {
card_data,
cof_contract,
})))
}
fn get_applepay_details(
wallet_data: &WalletData,
applepay_data: &ApplePayWalletData,
) -> CustomResult<ApplePayDetails, errors::ConnectorError> {
let payment_data = WalletData::get_wallet_token_as_json(wallet_data, "Apple Pay".to_string())?;
Ok(ApplePayDetails {
payment_data,
payment_method: ApplepayPaymentMethod {
display_name: applepay_data.payment_method.display_name.to_owned(),
network: applepay_data.payment_method.network.to_owned(),
token_type: applepay_data.payment_method.pm_type.to_owned(),
},
transaction_identifier: applepay_data.transaction_identifier.to_owned(),
})
}
fn get_card_details<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_-7524950471884079166_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets/transformers.rs
+ std::marker::Send
+ 'static
+ Serialize,
>(
req_card: &Card<T>,
) -> Result<CardDetails<T>, errors::ConnectorError> {
Ok(CardDetails {
card_number: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.card_exp_year.clone(),
verification: req_card.card_cvc.clone(),
})
}
fn get_wallet_details<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
wallet: &WalletData,
) -> Result<
(Option<NexinetsPaymentDetails<T>>, NexinetsProduct),
error_stack::Report<errors::ConnectorError>,
> {
match wallet {
WalletData::PaypalRedirect(_) => Ok((None, NexinetsProduct::Paypal)),
WalletData::ApplePay(applepay_data) => Ok((
Some(NexinetsPaymentDetails::Wallet(Box::new(
NexinetsWalletDetails::ApplePayToken(Box::new(get_applepay_details(
wallet,
applepay_data,
)?)),
))),
NexinetsProduct::Applepay,
)),
WalletData::AliPayQr(_)
| WalletData::BluecodeRedirect { .. }
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect { .. }
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect { .. }
| WalletData::VippsRedirect { .. }
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nexinets"),
))?,
}
}
pub fn get_order_id(
meta: &NexinetsPaymentsMetadata,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let order_id = meta.order_id.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "order_id".to_string(),
},
)?;
Ok(order_id)
}
pub fn get_transaction_id(
meta: &NexinetsPaymentsMetadata,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let transaction_id = meta.transaction_id.clone().ok_or(
errors::ConnectorError::MissingConnectorRelatedTransactionID {
id: "transaction_id".to_string(),
},
)?;
Ok(transaction_id)
}
fn is_mandate_payment<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
item: &PaymentsAuthorizeData<T>,
) -> bool {
(item.setup_future_usage == Some(common_enums::enums::FutureUsage::OffSession))
|| item
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
| {
"chunk": 6,
"crate": "connector-integration",
"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_connector-integration_7699459339071947392_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashfree/test.rs
// Test file placeholder for Cashfree connector
// Tests will be implemented once the basic connector is working
#[cfg(test)]
mod tests {
use domain_types::payment_method_data::DefaultPCIHolder;
use interfaces::api::ConnectorCommon;
use crate::connectors;
#[test]
fn test_cashfree_connector_creation() {
// Basic test to ensure connector can be created
let connector: &connectors::cashfree::Cashfree<DefaultPCIHolder> =
super::super::Cashfree::new();
assert_eq!(connector.id(), "cashfree");
}
}
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_1646928881711498853_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashfree/transformers.rs
use common_enums;
use domain_types::{
connector_flow::{Authorize, CreateOrder},
connector_types::{
PaymentCreateOrderData, PaymentCreateOrderResponse, PaymentFlowData, PaymentsAuthorizeData,
PaymentsResponseData, ResponseId,
},
errors::ConnectorError,
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes},
router_data::ConnectorAuthType,
router_data_v2::RouterDataV2,
};
use error_stack::report;
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::types::ResponseRouterData;
// ============================================================================
// Authentication
// ============================================================================
#[derive(Debug, Clone)]
pub struct CashfreeAuthType {
pub app_id: Secret<String>, // X-Client-Id
pub secret_key: Secret<String>, // X-Client-Secret
}
impl TryFrom<&ConnectorAuthType> for CashfreeAuthType {
type Error = error_stack::Report<ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
app_id: key1.to_owned(),
secret_key: api_key.to_owned(),
}),
ConnectorAuthType::SignatureKey {
api_key: _,
key1,
api_secret,
} => Ok(Self {
app_id: key1.to_owned(),
secret_key: api_secret.to_owned(),
}),
_ => Err(report!(ConnectorError::FailedToObtainAuthType)),
}
}
}
// ============================================================================
// Error Response
// ============================================================================
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CashfreeErrorResponse {
pub message: String,
pub code: String,
#[serde(rename = "type")]
pub error_type: String,
}
// ============================================================================
// Order Creation (Phase 1)
// ============================================================================
#[derive(Debug, Serialize)]
pub struct CashfreeOrderCreateRequest {
pub order_id: String,
pub order_amount: f64,
pub order_currency: String,
pub customer_details: CashfreeCustomerDetails,
pub order_meta: CashfreeOrderMeta,
pub order_note: Option<String>,
pub order_expiry_time: Option<String>,
}
// Supporting types for Order Response (missing from original implementation)
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreeOrderCreateUrlResponse {
pub url: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreeOrderTagsType {
pub metadata1: Option<String>,
pub metadata2: Option<String>,
pub metadata3: Option<String>,
pub metadata4: Option<String>,
pub metadata5: Option<String>,
pub metadata6: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreeOrderSplitsType {
pub vendor_id: String,
pub amount: f64,
pub percentage: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreeCustomerDetails {
pub customer_id: String,
pub customer_email: Option<String>,
pub customer_phone: Secret<String>,
pub customer_name: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreeOrderMeta {
pub return_url: String,
pub notify_url: String,
pub payment_methods: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreeOrderCreateResponse {
pub payment_session_id: String, // KEY: Used in Authorize flow
pub cf_order_id: i64,
pub order_id: String,
pub entity: String, // ADDED: Missing field from Haskell
pub order_amount: f64,
pub order_currency: String,
pub order_status: String,
pub order_expiry_time: String, // ADDED: Missing field from Haskell
pub order_note: Option<String>, // ADDED: Missing optional field from Haskell
pub customer_details: CashfreeCustomerDetails,
pub order_meta: CashfreeOrderMeta,
pub payments: CashfreeOrderCreateUrlResponse, // ADDED: Missing field from Haskell
pub settlements: CashfreeOrderCreateUrlResponse, // ADDED: Missing field from Haskell
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_1646928881711498853_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashfree/transformers.rs
pub refunds: CashfreeOrderCreateUrlResponse, // ADDED: Missing field from Haskell
pub order_tags: Option<CashfreeOrderTagsType>, // ADDED: Missing optional field from Haskell
pub order_splits: Option<Vec<CashfreeOrderSplitsType>>, // ADDED: Missing optional field from Haskell
}
// ADDED: Union type for handling success/failure responses (matches Haskell pattern)
// #[derive(Debug, Deserialize)]
// #[serde(untagged)]
// pub enum CashfreeOrderCreateResponseWrapper {
// Success(CashfreeOrderCreateResponse),
// Error(CashfreeErrorResponse),
// }
// ============================================================================
// Payment Authorization (Phase 2)
// ============================================================================
#[derive(Debug, Serialize)]
pub struct CashfreePaymentRequest {
pub payment_session_id: String, // From order creation response
pub payment_method: CashfreePaymentMethod,
pub payment_surcharge: Option<CashfreePaymentSurcharge>,
}
#[derive(Debug, Serialize)]
pub struct CashfreePaymentMethod {
pub upi: Option<CashfreeUpiDetails>,
// ADDED: All other payment methods (set to None for UPI-only implementation)
// This matches Haskell CashfreePaymentMethodType structure exactly
#[serde(skip_serializing_if = "Option::is_none")]
pub app: Option<()>, // CashFreeAPPType - None for UPI-only
#[serde(skip_serializing_if = "Option::is_none")]
pub netbanking: Option<()>, // CashFreeNBType - None for UPI-only
#[serde(skip_serializing_if = "Option::is_none")]
pub card: Option<()>, // CashFreeCARDType - None for UPI-only
#[serde(skip_serializing_if = "Option::is_none")]
pub emi: Option<()>, // CashfreeEmiType - None for UPI-only
#[serde(skip_serializing_if = "Option::is_none")]
pub paypal: Option<()>, // CashfreePaypalType - None for UPI-only
#[serde(skip_serializing_if = "Option::is_none")]
pub paylater: Option<()>, // CashFreePaylaterType - None for UPI-only
#[serde(skip_serializing_if = "Option::is_none")]
pub cardless_emi: Option<()>, // CashFreeCardlessEmiType - None for UPI-only
}
fn secret_is_empty(secret: &Secret<String>) -> bool {
secret.peek().is_empty()
}
#[derive(Debug, Serialize)]
pub struct CashfreeUpiDetails {
pub channel: String, // "link" for Intent, "collect" for Collect
#[serde(skip_serializing_if = "secret_is_empty")]
pub upi_id: Secret<String>, // VPA for collect, empty for intent
}
#[derive(Debug, Serialize)]
pub struct CashfreePaymentSurcharge {
pub surcharge_amount: f64,
pub surcharge_percentage: f64,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreePaymentResponse {
pub payment_method: String,
pub channel: String,
pub action: String,
pub data: CashfreeResponseData,
pub cf_payment_id: Option<serde_json::Value>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreeResponseData {
pub url: Option<String>,
pub payload: Option<CashfreePayloadData>,
pub content_type: Option<String>,
pub method: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CashfreePayloadData {
#[serde(rename = "default")]
pub default_link: String, // Universal deep link for Intent
pub gpay: Option<String>,
pub phonepe: Option<String>,
pub paytm: Option<String>,
pub bhim: Option<String>,
}
// ============================================================================
// Helper Functions
// ============================================================================
fn get_cashfree_payment_method_data<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>(
payment_method_data: &PaymentMethodData<T>,
) -> Result<CashfreePaymentMethod, ConnectorError> {
match payment_method_data {
PaymentMethodData::Upi(upi_data) => {
match upi_data {
domain_types::payment_method_data::UpiData::UpiCollect(collect_data) => {
// Extract VPA for collect flow - maps to upi_id field in Cashfree
let vpa = collect_data
.vpa_id
.as_ref()
.map(|vpa| vpa.peek().to_string())
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_1646928881711498853_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashfree/transformers.rs
.unwrap_or_default();
if vpa.is_empty() {
return Err(ConnectorError::MissingRequiredField {
field_name: "vpa_id for UPI collect",
});
}
Ok(CashfreePaymentMethod {
upi: Some(CashfreeUpiDetails {
channel: "collect".to_string(),
upi_id: Secret::new(vpa),
}),
app: None,
netbanking: None,
card: None,
emi: None,
paypal: None,
paylater: None,
cardless_emi: None,
})
}
domain_types::payment_method_data::UpiData::UpiIntent(_)
| domain_types::payment_method_data::UpiData::UpiQr(_) => {
// Intent flow: channel = "link", no UPI ID needed
Ok(CashfreePaymentMethod {
upi: Some(CashfreeUpiDetails {
channel: "link".to_string(),
upi_id: Secret::new("".to_string()),
}),
app: None,
netbanking: None,
card: None,
emi: None,
paypal: None,
paylater: None,
cardless_emi: None,
})
}
}
}
_ => Err(ConnectorError::NotSupported {
message: "Only UPI payment methods are supported for Cashfree V3".to_string(),
connector: "Cashfree",
}),
}
}
// ============================================================================
// Request Transformations
// ============================================================================
// TryFrom implementation for macro-generated CashfreeRouterData wrapper
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
crate::connectors::cashfree::CashfreeRouterData<
RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
T,
>,
> for CashfreeOrderCreateRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
wrapper: crate::connectors::cashfree::CashfreeRouterData<
RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
T,
>,
) -> Result<Self, Self::Error> {
// Convert MinorUnit to FloatMajorUnit properly
let amount_i64 = wrapper.router_data.request.amount.get_amount_as_i64();
let converted_amount = common_utils::types::FloatMajorUnit(amount_i64 as f64 / 100.0);
Self::try_from((converted_amount, &wrapper.router_data))
}
}
// Keep the original TryFrom for backward compatibility
impl
TryFrom<
&RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
> for CashfreeOrderCreateRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
) -> Result<Self, Self::Error> {
// Convert MinorUnit to FloatMajorUnit properly
let amount_i64 = item.request.amount.get_amount_as_i64();
let converted_amount = common_utils::types::FloatMajorUnit(amount_i64 as f64 / 100.0);
Self::try_from((converted_amount, item))
}
}
impl
TryFrom<(
common_utils::types::FloatMajorUnit,
&RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
)> for CashfreeOrderCreateRequest
{
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_1646928881711498853_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashfree/transformers.rs
type Error = error_stack::Report<ConnectorError>;
fn try_from(
(converted_amount, item): (
common_utils::types::FloatMajorUnit,
&RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
),
) -> Result<Self, Self::Error> {
let billing = item
.resource_common_data
.address
.get_payment_method_billing()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "billing_address",
})?;
// Build customer details
let customer_details = CashfreeCustomerDetails {
customer_id: item
.resource_common_data
.customer_id
.as_ref()
.map(|id| id.get_string_repr().to_string())
.unwrap_or_else(|| "guest".to_string()),
customer_email: billing.email.as_ref().map(|e| e.peek().to_string()),
customer_phone: Secret::new(
billing
.phone
.as_ref()
.and_then(|phone| phone.number.as_ref())
.map(|number| number.peek().to_string())
.unwrap_or_else(|| "9999999999".to_string()),
),
customer_name: billing.get_optional_full_name().map(|name| name.expose()),
};
// Build order meta with return and notify URLs
let return_url = item.resource_common_data.return_url.clone().ok_or(
ConnectorError::MissingRequiredField {
field_name: "return_url",
},
)?;
// Get webhook URL from request - required for Cashfree V3
let notify_url =
item.request
.webhook_url
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "webhook_url",
})?;
let order_meta = CashfreeOrderMeta {
return_url,
notify_url,
payment_methods: Some("upi".to_string()),
};
Ok(Self {
order_id: item
.resource_common_data
.connector_request_reference_id
.clone(), // FIXED: Use payment_id not connector_request_reference_id
order_amount: converted_amount.0,
order_currency: item.request.currency.to_string(),
customer_details,
order_meta,
order_note: item.resource_common_data.description.clone(),
order_expiry_time: None,
})
}
}
// TryFrom implementation for macro-generated CashfreeRouterData wrapper
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
crate::connectors::cashfree::CashfreeRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for CashfreePaymentRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
wrapper: crate::connectors::cashfree::CashfreeRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
Self::try_from(&wrapper.router_data)
}
}
// Keep original TryFrom implementation for backward compatibility
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
&RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
> for CashfreePaymentRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: &RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_1646928881711498853_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashfree/transformers.rs
// Extract payment_session_id from reference_id (set by CreateOrder response)
let payment_session_id = item.resource_common_data.reference_id.clone().ok_or(
ConnectorError::MissingRequiredField {
field_name: "payment_session_id",
},
)?;
// Get Cashfree payment method data directly
let payment_method = get_cashfree_payment_method_data(&item.request.payment_method_data)?;
Ok(Self {
payment_session_id,
payment_method,
payment_surcharge: None, // TODO: Add surcharge logic if needed
})
}
}
// ============================================================================
// Response Transformations
// ============================================================================
impl TryFrom<CashfreeOrderCreateResponse> for PaymentCreateOrderResponse {
type Error = error_stack::Report<ConnectorError>;
fn try_from(response: CashfreeOrderCreateResponse) -> Result<Self, Self::Error> {
Ok(Self {
order_id: response.payment_session_id,
})
}
}
// Add the missing TryFrom implementation for macro compatibility
impl
TryFrom<
ResponseRouterData<
CashfreeOrderCreateResponse,
RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
>,
>
for RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
CashfreeOrderCreateResponse,
RouterDataV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>,
>,
) -> Result<Self, Self::Error> {
let response = item.response;
let order_response = PaymentCreateOrderResponse::try_from(response)?;
// Extract order_id before moving order_response
let order_id = order_response.order_id.clone();
Ok(Self {
response: Ok(order_response),
resource_common_data: PaymentFlowData {
// Update status to indicate successful order creation
status: common_enums::AttemptStatus::Pending,
// Set reference_id to the payment_session_id for use in authorize flow
reference_id: Some(order_id),
..item.router_data.resource_common_data
},
..item.router_data
})
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
ResponseRouterData<
CashfreePaymentResponse,
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
> for RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
CashfreePaymentResponse,
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
) -> Result<Self, Self::Error> {
let response = item.response;
let (status, redirection_data) = match response.channel.as_str() {
"link" => {
// Intent flow - extract deep link from payload._default
let deep_link = response.data.payload.map(|p| p.default_link).ok_or(
ConnectorError::MissingRequiredField {
field_name: "intent_link",
},
)?;
// Trim deep link at "?" as per Haskell: truncateIntentLink "?" link
let trimmed_link = if let Some(pos) = deep_link.find('?') {
&deep_link[(pos + 1)..]
} else {
&deep_link
};
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_1646928881711498853_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/cashfree/transformers.rs
// Create UPI intent redirection
let redirection_data = Some(Box::new(Some(
domain_types::router_response_types::RedirectForm::Uri {
uri: trimmed_link.to_string(),
},
)));
(
common_enums::AttemptStatus::AuthenticationPending,
redirection_data,
)
}
"collect" => {
// Collect flow - return without redirection, status Pending
(common_enums::AttemptStatus::Pending, None)
}
_ => (common_enums::AttemptStatus::Failure, None),
};
Ok(Self {
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
response
.cf_payment_id
.as_ref()
.map(|id| id.to_string())
.unwrap_or_default(),
),
redirection_data: redirection_data.and_then(|data| *data).map(Box::new),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: response.cf_payment_id.map(|id| id.to_string()),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
..item.router_data
})
}
}
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_3298345365791435089_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/dlocal/transformers.rs
use common_utils::{pii, request::Method, types::MinorUnit};
use domain_types::{
connector_flow::{self, Authorize, PSync, RSync, Void},
connector_types::{
PaymentFlowData, PaymentVoidData, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData,
RefundsResponseData, ResponseId,
},
errors::{self, ConnectorError},
payment_address::AddressDetails,
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, RawCardNumber},
router_data::ConnectorAuthType,
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
utils,
};
use error_stack::ResultExt;
use hyperswitch_masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{connectors::dlocal::DlocalRouterData, types::ResponseRouterData};
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct Payer {
pub name: Option<Secret<String>>,
pub email: Option<pii::Email>,
pub document: Secret<String>,
}
#[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)]
pub struct Card<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub holder_name: Secret<String>,
pub number: RawCardNumber<T>,
pub cvv: Secret<String>,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub capture: String,
pub installments_id: Option<String>,
pub installments: Option<String>,
}
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct ThreeDSecureReqData {
pub force: bool,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaymentMethodId {
#[default]
Card,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum PaymentMethodFlow {
#[default]
Direct,
ReDirect,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DlocalPaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub amount: MinorUnit,
pub currency: common_enums::Currency,
pub country: String,
pub payment_method_id: PaymentMethodId,
pub payment_method_flow: PaymentMethodFlow,
pub payer: Payer,
pub card: Option<Card<T>>,
pub order_id: String,
pub three_dsecure: Option<ThreeDSecureReqData>,
pub callback_url: Option<String>,
pub description: Option<String>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
DlocalRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for DlocalPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: DlocalRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let email = item.router_data.request.email.clone();
let address = item
.router_data
.resource_common_data
.get_billing_address()?;
let country = address.get_country()?;
let name = get_payer_name(address);
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
let should_capture = matches!(
item.router_data.request.capture_method,
Some(common_enums::CaptureMethod::Automatic)
| Some(common_enums::CaptureMethod::SequentialAutomatic)
);
let amount = utils::convert_amount(
item.connector.amount_converter,
item.router_data.request.minor_amount,
item.router_data.request.currency,
)?;
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_3298345365791435089_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/dlocal/transformers.rs
let payment_request = Self {
amount,
currency: item.router_data.request.currency,
payment_method_id: PaymentMethodId::Card,
payment_method_flow: PaymentMethodFlow::Direct,
country: country.to_string(),
payer: Payer {
name,
email,
// [#589]: Allow securely collecting PII from customer in payments request
document: get_doc_from_currency(country.to_string()),
},
card: Some(Card {
holder_name: item
.router_data
.resource_common_data
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
number: ccard.card_number.clone(),
cvv: ccard.card_cvc.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.card_exp_year.clone(),
capture: should_capture.to_string(),
installments_id: item
.router_data
.request
.mandate_id
.as_ref()
.and_then(|ids| ids.mandate_id.clone()),
// [#595[FEATURE] Pass Mandate history information in payment flows/request]
installments: item
.router_data
.request
.mandate_id
.clone()
.map(|_| "1".to_string()),
}),
order_id: item
.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
three_dsecure: match item.router_data.resource_common_data.auth_type {
common_enums::AuthenticationType::ThreeDs => {
Some(ThreeDSecureReqData { force: true })
}
common_enums::AuthenticationType::NoThreeDs => None,
},
callback_url: Some(item.router_data.request.get_router_return_url()?),
description: item.router_data.resource_common_data.description.clone(),
};
Ok(payment_request)
}
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
crate::utils::get_unimplemented_payment_method_error_message("Dlocal"),
))?
}
}
}
}
fn get_payer_name(address: &AddressDetails) -> Option<Secret<String>> {
let first_name = address
.first_name
.clone()
.map_or("".to_string(), |first_name| first_name.peek().to_string());
let last_name = address
.last_name
.clone()
.map_or("".to_string(), |last_name| last_name.peek().to_string());
let name: String = format!("{first_name} {last_name}").trim().to_string();
if !name.is_empty() {
Some(Secret::new(name))
} else {
None
}
}
pub struct DlocalPaymentsSyncRequest {
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_3298345365791435089_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/dlocal/transformers.rs
pub authz_id: String,
}
impl TryFrom<&RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>>
for DlocalPaymentsSyncRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
authz_id: (item
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?),
})
}
}
pub struct DlocalPaymentsCancelRequest {
pub cancel_id: String,
}
impl TryFrom<&RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>>
for DlocalPaymentsCancelRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterDataV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
cancel_id: item.request.connector_transaction_id.clone(),
})
}
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DlocalPaymentsCaptureRequest {
pub authorization_id: Secret<String>,
pub amount: i64,
pub currency: String,
pub order_id: String,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
DlocalRouterData<
RouterDataV2<
connector_flow::Capture,
PaymentFlowData,
PaymentsCaptureData,
PaymentsResponseData,
>,
T,
>,
> for DlocalPaymentsCaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: DlocalRouterData<
RouterDataV2<
connector_flow::Capture,
PaymentFlowData,
PaymentsCaptureData,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
authorization_id: Secret::new(
item.router_data
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
),
amount: item.router_data.request.amount_to_capture,
currency: item.router_data.request.currency.to_string(),
order_id: item
.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
})
}
}
// Auth Struct
pub struct DlocalAuthType {
pub(super) x_login: Secret<String>,
pub(super) x_trans_key: Secret<String>,
pub(super) secret: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for DlocalAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} = auth_type
{
Ok(Self {
x_login: api_key.to_owned(),
x_trans_key: key1.to_owned(),
secret: api_secret.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Clone, Eq, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DlocalPaymentStatus {
Authorized,
Paid,
Verified,
Cancelled,
#[default]
Pending,
Rejected,
}
impl From<DlocalPaymentStatus> for common_enums::AttemptStatus {
fn from(item: DlocalPaymentStatus) -> Self {
match item {
DlocalPaymentStatus::Authorized => Self::Authorized,
DlocalPaymentStatus::Verified => Self::Authorized,
DlocalPaymentStatus::Paid => Self::Charged,
DlocalPaymentStatus::Pending => Self::AuthenticationPending,
DlocalPaymentStatus::Cancelled => Self::Voided,
DlocalPaymentStatus::Rejected => Self::AuthenticationFailed,
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_3298345365791435089_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/dlocal/transformers.rs
}
}
}
#[derive(Eq, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ThreeDSecureResData {
pub redirect_url: Option<url::Url>,
}
#[derive(Debug, Default, Eq, Clone, PartialEq, Serialize, Deserialize)]
pub struct DlocalPaymentsResponse {
status: DlocalPaymentStatus,
id: String,
three_dsecure: Option<ThreeDSecureResData>,
order_id: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<DlocalPaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<DlocalPaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.three_dsecure
.and_then(|three_secure_data| three_secure_data.redirect_url)
.map(|redirect_url| RedirectForm::from((redirect_url, Method::Get)));
let response = PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: redirection_data.map(Box::new),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
status_code: item.http_code,
};
Ok(Self {
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::from(item.response.status),
..item.router_data.resource_common_data
},
response: Ok(response),
..item.router_data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DlocalPaymentsSyncResponse {
status: DlocalPaymentStatus,
id: String,
order_id: Option<String>,
}
impl<F> TryFrom<ResponseRouterData<DlocalPaymentsSyncResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<DlocalPaymentsSyncResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::from(item.response.status),
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DlocalPaymentsCaptureResponse {
status: DlocalPaymentStatus,
id: String,
order_id: Option<String>,
}
impl<F> TryFrom<ResponseRouterData<DlocalPaymentsCaptureResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<DlocalPaymentsCaptureResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::from(item.response.status),
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: item.response.order_id.clone(),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_3298345365791435089_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/dlocal/transformers.rs
..item.router_data
})
}
}
pub struct DlocalPaymentsCancelResponse {
status: DlocalPaymentStatus,
order_id: String,
}
impl<F> TryFrom<ResponseRouterData<DlocalPaymentsCancelResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentVoidData, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<DlocalPaymentsCancelResponse, Self>,
) -> Result<Self, Self::Error> {
Ok(Self {
resource_common_data: PaymentFlowData {
status: common_enums::AttemptStatus::from(item.response.status),
..item.router_data.resource_common_data
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order_id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.order_id.clone()),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
..item.router_data
})
}
}
// REFUND :
#[derive(Default, Debug, Serialize)]
pub struct DlocalRefundRequest {
pub amount: String,
pub payment_id: String,
pub currency: common_enums::Currency,
pub id: String,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<DlocalRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>>
for DlocalRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: DlocalRouterData<
RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let amount_to_refund = item.router_data.request.refund_amount.to_string();
Ok(Self {
amount: amount_to_refund,
payment_id: item.router_data.request.connector_transaction_id.clone(),
currency: item.router_data.request.currency,
id: item.router_data.request.refund_id.clone(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum RefundStatus {
Success,
#[default]
Pending,
Rejected,
Cancelled,
}
impl From<RefundStatus> for common_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Success => Self::Success,
RefundStatus::Pending => Self::Pending,
RefundStatus::Rejected => Self::ManualReview,
RefundStatus::Cancelled => Self::Failure,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub status: RefundStatus,
}
impl<F> TryFrom<ResponseRouterData<RefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundResponse, Self>) -> Result<Self, Self::Error> {
let refund_status = common_enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct DlocalRefundsSyncRequest {
pub refund_id: String,
}
impl TryFrom<&RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>>
for DlocalRefundsSyncRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let refund_id = item.request.connector_refund_id.clone();
Ok(Self {
refund_id: (refund_id),
})
}
}
impl<F> TryFrom<ResponseRouterData<RefundResponse, Self>>
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_3298345365791435089_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/dlocal/transformers.rs
for RouterDataV2<F, RefundFlowData, RefundSyncData, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundResponse, Self>) -> Result<Self, Self::Error> {
let refund_status = common_enums::RefundStatus::from(item.response.status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.id,
refund_status,
status_code: item.http_code,
}),
..item.router_data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct DlocalErrorResponse {
pub code: i32,
pub message: String,
pub param: Option<String>,
}
fn get_doc_from_currency(country: String) -> Secret<String> {
let doc = match country.as_str() {
"BR" => "91483309223",
"ZA" => "2001014800086",
"BD" | "GT" | "HN" | "PK" | "SN" | "TH" => "1234567890001",
"CR" | "SV" | "VN" => "123456789",
"DO" | "NG" => "12345678901",
"EG" => "12345678901112",
"GH" | "ID" | "RW" | "UG" => "1234567890111123",
"IN" => "NHSTP6374G",
"CI" => "CA124356789",
"JP" | "MY" | "PH" => "123456789012",
"NI" => "1234567890111A",
"TZ" => "12345678912345678900",
_ => "12345678",
};
Secret::new(doc.to_string())
}
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_771969805810783188_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/rapyd/transformers.rs
use common_utils::{ext_traits::OptionExt, request::Method, FloatMajorUnit};
use domain_types::{
connector_flow::{Authorize, Capture},
connector_types::{
PaymentFlowData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsResponseData,
RefundFlowData, RefundsData, RefundsResponseData, ResponseId,
},
errors::{self, ConnectorError},
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, RawCardNumber, WalletData},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
};
use error_stack;
use error_stack::ResultExt;
use hyperswitch_masking::Secret;
use serde::Deserialize;
use serde::Serialize;
use std::fmt::Debug;
use url::Url;
use super::RapydRouterData;
use crate::types::ResponseRouterData;
impl<F, T>
TryFrom<
ResponseRouterData<
RapydPaymentsResponse,
RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>,
>,
> for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<
RapydPaymentsResponse,
RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let (status, response) = match &item.response.data {
Some(data) => {
let attempt_status =
get_status(data.status.to_owned(), data.next_action.to_owned());
match attempt_status {
common_enums::AttemptStatus::Failure => (
common_enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: data
.failure_code
.to_owned()
.unwrap_or(item.response.status.error_code),
status_code: item.http_code,
message: item.response.status.status.unwrap_or_default(),
reason: data.failure_message.to_owned(),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
),
_ => {
let redirection_url = data
.redirect_url
.as_ref()
.filter(|redirect_str| !redirect_str.is_empty())
.map(|url| {
Url::parse(url).change_context(
errors::ConnectorError::FailedToObtainIntegrationUrl,
)
})
.transpose()?;
let redirection_data =
redirection_url.map(|url| RedirectForm::from((url, Method::Get)));
(
attempt_status,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(data.id.to_owned()), //transaction_id is also the field but this id is used to initiate a refund
redirection_data: redirection_data.map(Box::new),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: data
.merchant_reference_id
.to_owned(),
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
)
}
}
}
None => (
common_enums::AttemptStatus::Failure,
Err(ErrorResponse {
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_771969805810783188_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/rapyd/transformers.rs
code: item.response.status.error_code,
status_code: item.http_code,
message: item.response.status.status.unwrap_or_default(),
reason: item.response.status.message,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
),
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..item.router_data.resource_common_data
},
response,
..item.router_data
})
}
}
#[derive(Debug, Serialize)]
pub struct EmptyRequest;
// RapydRouterData is now generated by the macro in rapyd.rs
#[derive(Debug, Serialize)]
pub struct RapydAuthType {
pub(super) access_key: Secret<String>,
pub(super) secret_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for RapydAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
access_key: api_key.to_owned(),
secret_key: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
}
#[derive(Default, Debug, Serialize)]
pub struct RapydPaymentsRequest<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub amount: FloatMajorUnit,
pub currency: common_enums::Currency,
pub payment_method: PaymentMethod<T>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method_options: Option<PaymentMethodOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_reference_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub complete_payment_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error_payment_url: Option<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentMethodOptions {
#[serde(rename = "3d_required")]
pub three_ds: bool,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentMethod<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
#[serde(rename = "type")]
pub pm_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub fields: Option<PaymentFields<T>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub address: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
pub digital_wallet: Option<RapydWallet>,
}
#[derive(Default, Debug, Serialize)]
pub struct PaymentFields<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> {
pub number: RawCardNumber<T>,
pub expiration_month: Secret<String>,
pub expiration_year: Secret<String>,
pub name: Secret<String>,
pub cvv: Secret<String>,
}
#[derive(Default, Debug, Serialize)]
pub struct Address {
name: Secret<String>,
line_1: Secret<String>,
line_2: Option<Secret<String>>,
line_3: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
country: Option<String>,
zip: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RapydWallet {
#[serde(rename = "type")]
payment_type: String,
#[serde(rename = "details")]
token: Option<Secret<String>>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
RapydRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_771969805810783188_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/rapyd/transformers.rs
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for RapydPaymentsRequest<T>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RapydRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let (capture, payment_method_options) =
match item.router_data.resource_common_data.payment_method {
common_enums::PaymentMethod::Card => {
let three_ds_enabled = matches!(
item.router_data.resource_common_data.auth_type,
common_enums::AuthenticationType::ThreeDs
);
let payment_method_options = PaymentMethodOptions {
three_ds: three_ds_enabled,
};
(
Some(matches!(
item.router_data.request.capture_method,
Some(common_enums::CaptureMethod::Automatic)
| Some(common_enums::CaptureMethod::SequentialAutomatic)
| None
)),
Some(payment_method_options),
)
}
_ => (None, None),
};
let payment_method = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
Some(PaymentMethod {
pm_type: "in_amex_card".to_owned(), //[#369] Map payment method type based on country
fields: Some(PaymentFields {
number: ccard.card_number.to_owned(),
expiration_month: ccard.card_exp_month.to_owned(),
expiration_year: ccard.card_exp_year.to_owned(),
name: item
.router_data
.resource_common_data
.get_optional_billing_full_name()
.to_owned()
.unwrap_or(Secret::new("".to_string())),
cvv: ccard.card_cvc.to_owned(),
}),
address: None,
digital_wallet: None,
})
}
PaymentMethodData::Wallet(ref wallet_data) => {
let digital_wallet = match wallet_data {
WalletData::GooglePay(data) => Some(RapydWallet {
payment_type: "google_pay".to_string(),
token: Some(Secret::new(
data.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.to_owned(),
)),
}),
WalletData::ApplePay(data) => {
let apple_pay_encrypted_data = data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
Some(RapydWallet {
payment_type: "apple_pay".to_string(),
token: Some(Secret::new(apple_pay_encrypted_data.to_string())),
})
}
_ => None,
};
Some(PaymentMethod {
pm_type: "by_visa_card".to_string(), //[#369]
fields: None,
address: None,
digital_wallet,
})
}
_ => None,
}
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_771969805810783188_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/rapyd/transformers.rs
.get_required_value("payment_method not implemented")
.change_context(errors::ConnectorError::NotImplemented(
"payment_method".to_owned(),
))?;
let return_url = item.router_data.request.get_router_return_url()?;
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount,
item.router_data.request.currency,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
amount,
currency: item.router_data.request.currency,
payment_method,
capture,
payment_method_options,
merchant_reference_id: Some(
item.router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
description: None,
error_payment_url: Some(return_url.clone()),
complete_payment_url: Some(return_url),
})
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[allow(clippy::upper_case_acronyms)]
pub enum RapydPaymentStatus {
#[serde(rename = "ACT")]
Active,
#[serde(rename = "CAN")]
CanceledByClientOrBank,
#[serde(rename = "CLO")]
Closed,
#[serde(rename = "ERR")]
Error,
#[serde(rename = "EXP")]
Expired,
#[serde(rename = "REV")]
ReversedByRapyd,
#[default]
#[serde(rename = "NEW")]
New,
}
fn get_status(status: RapydPaymentStatus, next_action: NextAction) -> common_enums::AttemptStatus {
match (status, next_action) {
(RapydPaymentStatus::Closed, _) => common_enums::AttemptStatus::Charged,
(
RapydPaymentStatus::Active,
NextAction::ThreedsVerification | NextAction::PendingConfirmation,
) => common_enums::AttemptStatus::AuthenticationPending,
(RapydPaymentStatus::Active, NextAction::PendingCapture | NextAction::NotApplicable) => {
common_enums::AttemptStatus::Authorized
}
(
RapydPaymentStatus::CanceledByClientOrBank
| RapydPaymentStatus::Expired
| RapydPaymentStatus::ReversedByRapyd,
_,
) => common_enums::AttemptStatus::Voided,
(RapydPaymentStatus::Error, _) => common_enums::AttemptStatus::Failure,
(RapydPaymentStatus::New, _) => common_enums::AttemptStatus::Authorizing,
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RapydPaymentsResponse {
pub status: Status,
pub data: Option<ResponseData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Status {
pub error_code: String,
pub status: Option<String>,
pub message: Option<String>,
pub response_code: Option<String>,
pub operation_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum NextAction {
#[serde(rename = "3d_verification")]
ThreedsVerification,
#[serde(rename = "pending_capture")]
PendingCapture,
#[serde(rename = "not_applicable")]
NotApplicable,
#[serde(rename = "pending_confirmation")]
PendingConfirmation,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResponseData {
pub id: String,
pub amount: FloatMajorUnit,
pub status: RapydPaymentStatus,
pub next_action: NextAction,
pub redirect_url: Option<String>,
pub original_amount: Option<FloatMajorUnit>,
pub is_partial: Option<bool>,
pub currency_code: Option<common_enums::Currency>,
pub country_code: Option<String>,
pub captured: Option<bool>,
pub transaction_id: String,
pub merchant_reference_id: Option<String>,
pub paid: Option<bool>,
pub failure_code: Option<String>,
pub failure_message: Option<String>,
}
// Capture Request
#[derive(Debug, Serialize, Clone)]
pub struct CaptureRequest {
amount: Option<FloatMajorUnit>,
receipt_email: Option<Secret<String>>,
statement_descriptor: Option<String>,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
RapydRouterData<
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_771969805810783188_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/rapyd/transformers.rs
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
> for CaptureRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: RapydRouterData<
RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount_to_capture,
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
Ok(Self {
amount: Some(amount),
receipt_email: None,
statement_descriptor: None,
})
}
}
// Refund Request
#[derive(Default, Debug, Serialize)]
pub struct RapydRefundRequest {
pub payment: String,
pub amount: Option<FloatMajorUnit>,
pub currency: Option<common_enums::Currency>,
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
> TryFrom<RapydRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>>
for RapydRefundRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RapydRouterData<RouterDataV2<F, RefundFlowData, RefundsData, RefundsResponseData>, T>,
) -> Result<Self, Self::Error> {
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_refund_amount,
item.router_data.request.currency,
)
.change_context(ConnectorError::AmountConversionFailed)?;
Ok(Self {
payment: item
.router_data
.request
.connector_transaction_id
.to_string(),
amount: Some(amount),
currency: Some(item.router_data.request.currency),
})
}
}
// Refund Response
#[allow(dead_code)]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub enum RefundStatus {
Completed,
Error,
Rejected,
#[default]
Pending,
}
impl From<RefundStatus> for common_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Completed => Self::Success,
RefundStatus::Error | RefundStatus::Rejected => Self::Failure,
RefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub status: Status,
pub data: Option<RefundResponseData>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RefundResponseData {
pub id: String,
pub payment: String,
pub amount: FloatMajorUnit,
pub currency: common_enums::Currency,
pub status: RefundStatus,
pub created_at: Option<i64>,
pub failure_reason: Option<String>,
}
impl<F, T> TryFrom<ResponseRouterData<RefundResponse, Self>>
for RouterDataV2<F, RefundFlowData, T, RefundsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(item: ResponseRouterData<RefundResponse, Self>) -> Result<Self, Self::Error> {
let (connector_refund_id, refund_status) = match item.response.data {
Some(data) => (data.id, common_enums::RefundStatus::from(data.status)),
None => (
item.response.status.error_code,
common_enums::RefundStatus::Failure,
),
};
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id,
refund_status,
status_code: item.http_code,
}),
..item.router_data
})
}
}
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
use std::{
cmp,
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use aes::{Aes128, Aes192, Aes256};
// PayTM API Constants
pub mod constants {
// PayTM API versions and identifiers
pub const API_VERSION: &str = "v2";
pub const CHANNEL_ID: &str = "WEB";
// Request types
pub const REQUEST_TYPE_PAYMENT: &str = "Payment";
pub const REQUEST_TYPE_NATIVE: &str = "NATIVE";
// UPI specific constants
pub const PAYMENT_MODE_UPI: &str = "UPI";
pub const UPI_CHANNEL_UPIPUSH: &str = "UPIPUSH";
pub const PAYMENT_FLOW_NONE: &str = "NONE";
pub const AUTH_MODE_DEBIT_PIN: &str = "DEBIT_PIN";
pub const AUTH_MODE_OTP: &str = "otp";
// Response codes
pub const SUCCESS_CODE: &str = "0000";
pub const DUPLICATE_CODE: &str = "0002";
pub const QR_SUCCESS_CODE: &str = "QR_0001";
// PSync specific constants
pub const TXN_SUCCESS_CODE: &str = "01";
pub const TXN_FAILURE_CODE: &str = "227";
pub const WALLET_INSUFFICIENT_CODE: &str = "235";
pub const INVALID_UPI_CODE: &str = "295";
pub const NO_RECORD_FOUND_CODE: &str = "331";
pub const INVALID_ORDER_ID_CODE: &str = "334";
pub const INVALID_MID_CODE: &str = "335";
pub const PENDING_CODE: &str = "400";
pub const BANK_DECLINED_CODE: &str = "401";
pub const PENDING_BANK_CONFIRM_CODE: &str = "402";
pub const SERVER_DOWN_CODE: &str = "501";
pub const TXN_FAILED_CODE: &str = "810";
pub const ACCOUNT_BLOCKED_CODE: &str = "843";
pub const MOBILE_CHANGED_CODE: &str = "820";
pub const MANDATE_GAP_CODE: &str = "267";
// Transaction types for PSync
pub const TXN_TYPE_PREAUTH: &str = "PREAUTH";
pub const TXN_TYPE_CAPTURE: &str = "CAPTURE";
pub const TXN_TYPE_RELEASE: &str = "RELEASE";
pub const TXN_TYPE_WITHDRAW: &str = "WITHDRAW";
// Default values
pub const DEFAULT_CUSTOMER_ID: &str = "guest";
pub const DEFAULT_CALLBACK_URL: &str = "https://default-callback.com";
// Error messages
pub const ERROR_INVALID_VPA: &str = "Invalid UPI VPA format";
pub const ERROR_SALT_GENERATION: &str = "Failed to generate random salt";
pub const ERROR_AES_128_ENCRYPTION: &str = "AES-128 encryption failed";
pub const ERROR_AES_192_ENCRYPTION: &str = "AES-192 encryption failed";
pub const ERROR_AES_256_ENCRYPTION: &str = "AES-256 encryption failed";
// HTTP constants
pub const CONTENT_TYPE_JSON: &str = "application/json";
pub const CONTENT_TYPE_HEADER: &str = "Content-Type";
// AES encryption constants (from PayTM Haskell implementation)
pub const PAYTM_IV: &[u8; 16] = b"@@@@&&&&####$$$$";
pub const SALT_LENGTH: usize = 3;
pub const AES_BUFFER_PADDING: usize = 16;
pub const AES_128_KEY_LENGTH: usize = 16;
pub const AES_192_KEY_LENGTH: usize = 24;
pub const AES_256_KEY_LENGTH: usize = 32;
}
use base64::{engine::general_purpose, Engine};
use cbc::{
cipher::{block_padding::Pkcs7, BlockEncryptMut, KeyIvInit},
Encryptor,
};
use common_enums::{AttemptStatus, Currency};
use common_utils::{
errors::CustomResult,
request::Method,
types::{AmountConvertor, StringMajorUnit},
Email,
};
use domain_types::{
connector_flow::{Authorize, CreateSessionToken, PSync},
connector_types::{
PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData, PaymentsSyncData, ResponseId,
SessionTokenRequestData, SessionTokenResponseData,
},
errors,
payment_method_data::{PaymentMethodData, UpiData},
router_data::ConnectorAuthType,
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret};
use ring::{
digest,
rand::{SecureRandom, SystemRandom},
};
use serde::{Deserialize, Serialize};
use serde_json;
use url::Url;
use crate::{
connectors::paytm::PaytmRouterData as MacroPaytmRouterData, types::ResponseRouterData,
};
#[derive(Debug, Clone)]
pub struct PaytmAuthType {
pub merchant_id: Secret<String>, // From api_key
pub merchant_key: Secret<String>, // From key1
pub website: Secret<String>, // From api_secret
pub channel_id: String, // Hardcoded "WEB"
pub client_id: Option<Secret<String>>, // None as specified
}
impl TryFrom<&ConnectorAuthType> for PaytmAuthType {
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => {
Ok(Self {
merchant_id: api_key.to_owned(), // merchant_id
merchant_key: key1.to_owned(), // signing key
website: api_secret.to_owned(), // website name
channel_id: constants::CHANNEL_ID.to_string(),
client_id: None, // None as specified
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone)]
pub enum UpiFlowType {
Intent,
Collect,
}
pub fn determine_upi_flow<T: domain_types::payment_method_data::PaymentMethodDataTypes>(
payment_method_data: &PaymentMethodData<T>,
) -> CustomResult<UpiFlowType, errors::ConnectorError> {
match payment_method_data {
PaymentMethodData::Upi(upi_data) => {
match upi_data {
UpiData::UpiCollect(collect_data) => {
// If VPA is provided, it's a collect flow
if collect_data.vpa_id.is_some() {
Ok(UpiFlowType::Collect)
} else {
// If no VPA provided, default to Intent
Ok(UpiFlowType::Intent)
}
}
UpiData::UpiIntent(_) | UpiData::UpiQr(_) => Ok(UpiFlowType::Intent),
}
}
_ => {
// Default to Intent for non-UPI specific payment methods
Ok(UpiFlowType::Intent)
}
}
}
// Request structures for CreateSessionToken flow (Paytm initiate)
#[derive(Debug, Serialize)]
pub struct PaytmInitiateTxnRequest {
pub head: PaytmRequestHeader,
pub body: PaytmInitiateReqBody,
}
#[derive(Debug, Serialize)]
pub struct PaytmRequestHeader {
#[serde(rename = "clientId")]
pub client_id: Option<Secret<String>>, // None
pub version: String, // "v2"
#[serde(rename = "requestTimestamp")]
pub request_timestamp: String,
#[serde(rename = "channelId")]
pub channel_id: String, // "WEB"
pub signature: Secret<String>,
}
#[derive(Debug, Serialize)]
pub struct PaytmInitiateReqBody {
#[serde(rename = "requestType")]
pub request_type: String, // "Payment"
pub mid: Secret<String>, // Merchant ID
#[serde(rename = "orderId")]
pub order_id: String, // Payment ID
#[serde(rename = "websiteName")]
pub website_name: Secret<String>, // From api_secret
#[serde(rename = "txnAmount")]
pub txn_amount: PaytmAmount,
#[serde(rename = "userInfo")]
pub user_info: PaytmUserInfo,
#[serde(rename = "enablePaymentMode")]
pub enable_payment_mode: Vec<PaytmEnableMethod>,
#[serde(rename = "callbackUrl")]
pub callback_url: String,
}
#[derive(Debug, Serialize)]
pub struct PaytmAmount {
pub value: StringMajorUnit, // Decimal amount (e.g., "10.50")
pub currency: Currency, // INR
}
#[derive(Debug, Serialize)]
pub struct PaytmUserInfo {
#[serde(rename = "custId")]
pub cust_id: String,
pub mobile: Option<Secret<String>>,
pub email: Option<Email>,
#[serde(rename = "firstName")]
pub first_name: Option<Secret<String>>,
#[serde(rename = "lastName")]
pub last_name: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct PaytmEnableMethod {
pub mode: String, // "UPI"
pub channels: Option<Vec<String>>, // ["UPIPUSH"] for Intent/Collect
}
// Response structures for CreateSessionToken flow
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmInitiateTxnResponse {
pub head: PaytmRespHead,
pub body: PaytmResBodyTypes,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaytmResBodyTypes {
SuccessBody(PaytmRespBody),
FailureBody(PaytmErrorBody),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmRespBody {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
#[serde(rename = "txnToken")]
pub txn_token: Secret<String>, // This will be stored as session_token
}
#[derive(Debug, Deserialize, Serialize)]
| {
"chunk": 1,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
pub struct PaytmResultInfo {
#[serde(rename = "resultStatus")]
pub result_status: String,
#[serde(rename = "resultCode")]
pub result_code: String, // "0000" for success, "0002" for duplicate
#[serde(rename = "resultMsg")]
pub result_msg: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmRespHead {
#[serde(rename = "responseTimestamp")]
pub response_timestamp: Option<String>,
pub version: String,
#[serde(rename = "clientId")]
pub client_id: Option<Secret<String>>,
pub signature: Option<Secret<String>>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmErrorBody {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
}
// Error response structure
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmErrorResponse {
#[serde(rename = "errorCode")]
pub error_code: Option<String>,
#[serde(rename = "errorMessage")]
pub error_message: Option<String>,
#[serde(rename = "errorDescription")]
pub error_description: Option<String>,
#[serde(rename = "transactionId")]
pub transaction_id: Option<String>,
}
// Transaction info structure used in multiple response types
// Supports both lowercase (txnId) and uppercase (TXNID) field name variants
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmTxnInfo {
#[serde(rename = "txnId", alias = "TXNID")]
pub txn_id: Option<String>,
#[serde(rename = "orderId", alias = "ORDERID")]
pub order_id: Option<String>,
#[serde(rename = "bankTxnId", alias = "BANKTXNID")]
pub bank_txn_id: Option<String>,
#[serde(alias = "STATUS")]
pub status: Option<String>,
#[serde(rename = "respCode", alias = "RESPCODE")]
pub resp_code: Option<String>,
#[serde(rename = "respMsg", alias = "RESPMSG")]
pub resp_msg: Option<String>,
// Additional callback-specific fields
#[serde(alias = "CHECKSUMHASH")]
pub checksum_hash: Option<String>,
#[serde(alias = "CURRENCY")]
pub currency: Option<Currency>,
#[serde(alias = "GATEWAYNAME")]
pub gateway_name: Option<String>,
#[serde(alias = "MID")]
pub mid: Option<String>,
#[serde(alias = "PAYMENTMODE")]
pub payment_mode: Option<String>,
#[serde(alias = "TXNAMOUNT")]
pub txn_amount: Option<StringMajorUnit>,
#[serde(alias = "TXNDATE")]
pub txn_date: Option<String>,
}
// Alternative error response structure for callback URL format
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmCallbackErrorResponse {
pub head: PaytmRespHead,
pub body: PaytmCallbackErrorBody,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmCallbackErrorBody {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
#[serde(rename = "txnInfo")]
pub txn_info: PaytmTxnInfo,
}
// Authorize flow request structures
// Enum to handle both UPI Intent and UPI Collect request types
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum PaytmAuthorizeRequest {
Intent(PaytmProcessTxnRequest),
Collect(PaytmNativeProcessTxnRequest),
}
#[derive(Debug, Serialize)]
pub struct PaytmProcessTxnRequest {
pub head: PaytmProcessHeadTypes,
pub body: PaytmProcessBodyTypes,
}
#[derive(Debug, Serialize)]
pub struct PaytmProcessHeadTypes {
pub version: String, // "v2"
#[serde(rename = "requestTimestamp")]
pub request_timestamp: String,
#[serde(rename = "channelId")]
pub channel_id: String, // "WEB"
#[serde(rename = "txnToken")]
pub txn_token: Secret<String>, // From CreateSessionToken
}
#[derive(Debug, Serialize)]
pub struct PaytmProcessBodyTypes {
pub mid: Secret<String>,
#[serde(rename = "orderId")]
pub order_id: String,
#[serde(rename = "requestType")]
pub request_type: String, // "Payment"
#[serde(rename = "paymentMode")]
pub payment_mode: String, // "UPI"
#[serde(rename = "paymentFlow")]
pub payment_flow: Option<String>, // "NONE"
}
// UPI Collect Native Process Request
#[derive(Debug, Serialize)]
pub struct PaytmNativeProcessTxnRequest {
pub head: PaytmTxnTokenType,
pub body: PaytmNativeProcessRequestBody,
}
#[derive(Debug, Serialize)]
pub struct PaytmTxnTokenType {
#[serde(rename = "txnToken")]
pub txn_token: Secret<String>, // From CreateSessionToken
}
#[derive(Debug, Serialize)]
pub struct PaytmNativeProcessRequestBody {
#[serde(rename = "requestType")]
| {
"chunk": 2,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
pub request_type: String, // "NATIVE"
pub mid: Secret<String>,
#[serde(rename = "orderId")]
pub order_id: String,
#[serde(rename = "paymentMode")]
pub payment_mode: String, // "UPI"
#[serde(rename = "payerAccount")]
pub payer_account: Option<String>, // UPI VPA for collect
#[serde(rename = "channelCode")]
pub channel_code: Option<String>, // Gateway code
#[serde(rename = "channelId")]
pub channel_id: String, // "WEB"
#[serde(rename = "txnToken")]
pub txn_token: Secret<String>, // From CreateSessionToken
#[serde(rename = "authMode")]
pub auth_mode: Option<String>, // "DEBIT_PIN"
}
// Authorize flow response structures
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmProcessTxnResponse {
pub head: PaytmProcessHead,
pub body: PaytmProcessRespBodyTypes,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmProcessHead {
pub version: Option<String>,
#[serde(rename = "responseTimestamp")]
pub response_timestamp: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaytmProcessRespBodyTypes {
SuccessBody(Box<PaytmProcessSuccessResp>),
FailureBody(PaytmProcessFailureResp),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmProcessSuccessResp {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
#[serde(rename = "deepLinkInfo", skip_serializing_if = "Option::is_none")]
pub deep_link_info: Option<PaytmDeepLinkInfo>,
#[serde(rename = "bankForm", skip_serializing_if = "Option::is_none")]
pub bank_form: Option<serde_json::Value>,
#[serde(rename = "upiDirectForm", skip_serializing_if = "Option::is_none")]
pub upi_direct_form: Option<serde_json::Value>,
#[serde(rename = "displayField", skip_serializing_if = "Option::is_none")]
pub display_field: Option<serde_json::Value>,
#[serde(rename = "riskContent", skip_serializing_if = "Option::is_none")]
pub risk_content: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmDeepLinkInfo {
#[serde(rename = "deepLink")]
pub deep_link: String, // UPI intent URL
#[serde(rename = "orderId")]
pub order_id: String,
#[serde(rename = "cashierRequestId")]
pub cashier_request_id: String,
#[serde(rename = "transId")]
pub trans_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmProcessFailureResp {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
}
// UPI Collect Native Process Response
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmNativeProcessTxnResponse {
pub head: PaytmProcessHead,
pub body: PaytmNativeProcessRespBodyTypes,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaytmNativeProcessRespBodyTypes {
SuccessBody(PaytmNativeProcessSuccessResp),
FailureBody(PaytmNativeProcessFailureResp),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmNativeProcessSuccessResp {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
#[serde(rename = "transId")]
pub trans_id: String,
#[serde(rename = "orderId")]
pub order_id: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmNativeProcessFailureResp {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
}
// Helper function for UPI VPA extraction
pub fn extract_upi_vpa<T: domain_types::payment_method_data::PaymentMethodDataTypes>(
payment_method_data: &PaymentMethodData<T>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
match payment_method_data {
PaymentMethodData::Upi(UpiData::UpiCollect(collect_data)) => {
if let Some(vpa_id) = &collect_data.vpa_id {
let vpa = vpa_id.peek().to_string();
if vpa.contains('@') && vpa.len() > 3 {
Ok(Some(vpa))
} else {
Err(errors::ConnectorError::RequestEncodingFailedWithReason(
constants::ERROR_INVALID_VPA.to_string(),
)
.into())
}
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "vpa_id",
}
.into())
}
}
| {
"chunk": 3,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
_ => Ok(None),
}
}
// Paytm signature generation algorithm implementation
// Following exact PayTM v2 algorithm from Haskell codebase
pub fn generate_paytm_signature(
payload: &str,
merchant_key: &str,
) -> CustomResult<String, errors::ConnectorError> {
// Step 1: Generate random salt bytes using ring (same logic, different implementation)
let rng = SystemRandom::new();
let mut salt_bytes = [0u8; constants::SALT_LENGTH];
rng.fill(&mut salt_bytes).map_err(|_| {
errors::ConnectorError::RequestEncodingFailedWithReason(
constants::ERROR_SALT_GENERATION.to_string(),
)
})?;
// Step 2: Convert salt to Base64 (same logic)
let salt_b64 = general_purpose::STANDARD.encode(salt_bytes);
// Step 3: Create hash input: payload + "|" + base64_salt (same logic)
let hash_input = format!("{payload}|{salt_b64}");
// Step 4: SHA-256 hash using ring (same logic, different implementation)
let hash_digest = digest::digest(&digest::SHA256, hash_input.as_bytes());
let sha256_hash = hex::encode(hash_digest.as_ref());
// Step 5: Create checksum: sha256_hash + base64_salt (same logic)
let checksum = format!("{sha256_hash}{salt_b64}");
// Step 6: AES encrypt checksum with merchant key (same logic)
let signature = aes_encrypt(&checksum, merchant_key)?;
Ok(signature)
}
// AES-CBC encryption implementation for PayTM v2
// This follows the exact PayTMv1 encrypt function used by PayTMv2:
// - Fixed IV: "@@@@&&&&####$$$$" (16 bytes) - exact value from Haskell code
// - Key length determines AES variant: 16→AES-128, 24→AES-192, other→AES-256
// - Mode: CBC with PKCS7 padding (16-byte blocks)
// - Output: Base64 encoded encrypted data
fn aes_encrypt(data: &str, key: &str) -> CustomResult<String, errors::ConnectorError> {
// PayTM uses fixed IV as specified in PayTMv1 implementation
let iv = get_paytm_iv();
let key_bytes = key.as_bytes();
let data_bytes = data.as_bytes();
// Determine AES variant based on key length (following PayTMv1 Haskell implementation)
match key_bytes.len() {
constants::AES_128_KEY_LENGTH => {
// AES-128-CBC with PKCS7 padding
type Aes128CbcEnc = Encryptor<Aes128>;
let mut key_array = [0u8; constants::AES_128_KEY_LENGTH];
key_array.copy_from_slice(key_bytes);
let encryptor = Aes128CbcEnc::new(&key_array.into(), &iv.into());
// Encrypt with proper buffer management
let mut buffer = Vec::with_capacity(data_bytes.len() + constants::AES_BUFFER_PADDING);
buffer.extend_from_slice(data_bytes);
buffer.resize(buffer.len() + constants::AES_BUFFER_PADDING, 0);
let encrypted_len = encryptor
.encrypt_padded_mut::<Pkcs7>(&mut buffer, data_bytes.len())
.map_err(|_| {
errors::ConnectorError::RequestEncodingFailedWithReason(
constants::ERROR_AES_128_ENCRYPTION.to_string(),
)
})?
.len();
buffer.truncate(encrypted_len);
Ok(general_purpose::STANDARD.encode(&buffer))
}
constants::AES_192_KEY_LENGTH => {
// AES-192-CBC with PKCS7 padding
type Aes192CbcEnc = Encryptor<Aes192>;
let mut key_array = [0u8; constants::AES_192_KEY_LENGTH];
key_array.copy_from_slice(key_bytes);
let encryptor = Aes192CbcEnc::new(&key_array.into(), &iv.into());
let mut buffer = Vec::with_capacity(data_bytes.len() + constants::AES_BUFFER_PADDING);
buffer.extend_from_slice(data_bytes);
buffer.resize(buffer.len() + constants::AES_BUFFER_PADDING, 0);
let encrypted_len = encryptor
.encrypt_padded_mut::<Pkcs7>(&mut buffer, data_bytes.len())
.map_err(|_| {
errors::ConnectorError::RequestEncodingFailedWithReason(
constants::ERROR_AES_192_ENCRYPTION.to_string(),
)
})?
.len();
buffer.truncate(encrypted_len);
Ok(general_purpose::STANDARD.encode(&buffer))
}
_ => {
| {
"chunk": 4,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_5 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
// Default to AES-256-CBC with PKCS7 padding (for any other key length)
type Aes256CbcEnc = Encryptor<Aes256>;
// For AES-256, we need exactly 32 bytes, so pad or truncate the key
let mut aes256_key = [0u8; constants::AES_256_KEY_LENGTH];
let copy_len = cmp::min(key_bytes.len(), constants::AES_256_KEY_LENGTH);
aes256_key[..copy_len].copy_from_slice(&key_bytes[..copy_len]);
let encryptor = Aes256CbcEnc::new(&aes256_key.into(), &iv.into());
let mut buffer = Vec::with_capacity(data_bytes.len() + constants::AES_BUFFER_PADDING);
buffer.extend_from_slice(data_bytes);
buffer.resize(buffer.len() + constants::AES_BUFFER_PADDING, 0);
let encrypted_len = encryptor
.encrypt_padded_mut::<Pkcs7>(&mut buffer, data_bytes.len())
.map_err(|_| {
errors::ConnectorError::RequestEncodingFailedWithReason(
constants::ERROR_AES_256_ENCRYPTION.to_string(),
)
})?
.len();
buffer.truncate(encrypted_len);
Ok(general_purpose::STANDARD.encode(&buffer))
}
}
}
// Fixed IV for Paytm AES encryption (from PayTM v2 Haskell implementation)
// IV value: "@@@@&&&&####$$$$" (16 characters) - exact value from Haskell codebase
fn get_paytm_iv() -> [u8; 16] {
// This is the exact IV used by PayTM v2 as found in the Haskell codebase
*constants::PAYTM_IV
}
pub fn create_paytm_header(
request_body: &impl serde::Serialize,
auth: &PaytmAuthType,
) -> CustomResult<PaytmRequestHeader, errors::ConnectorError> {
let _payload = serde_json::to_string(request_body)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let signature = generate_paytm_signature(&_payload, auth.merchant_key.peek())?;
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
.to_string();
Ok(PaytmRequestHeader {
client_id: auth.client_id.clone(), // None
version: constants::API_VERSION.to_string(),
request_timestamp: timestamp,
channel_id: auth.channel_id.clone(), // "WEB"
signature: Secret::new(signature),
})
}
// Helper struct for RouterData transformation
#[derive(Debug, Clone)]
pub struct PaytmRouterData {
pub amount: StringMajorUnit,
pub currency: Currency,
pub payment_id: String,
pub customer_id: Option<String>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub return_url: Option<String>,
}
// Helper struct for Authorize flow RouterData transformation
#[derive(Debug, Clone)]
pub struct PaytmAuthorizeRouterData<T: domain_types::payment_method_data::PaymentMethodDataTypes> {
pub amount: StringMajorUnit,
pub currency: Currency,
pub payment_id: String,
pub session_token: Secret<String>,
pub payment_method_data: PaymentMethodData<T>,
pub customer_id: Option<String>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub return_url: Option<String>,
}
// Request transformation for CreateSessionToken flow
impl PaytmRouterData {
pub fn try_from_with_converter(
item: &RouterDataV2<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
>,
amount_converter: &dyn AmountConvertor<Output = StringMajorUnit>,
) -> Result<Self, error_stack::Report<errors::ConnectorError>> {
let amount = amount_converter
.convert(item.request.amount, item.request.currency)
.change_context(errors::ConnectorError::AmountConversionFailed)?;
let customer_id = item
.resource_common_data
.get_customer_id()
.ok()
.map(|id| id.get_string_repr().to_string());
let email = item.resource_common_data.get_optional_billing_email();
let phone = item
.resource_common_data
.get_optional_billing_phone_number();
| {
"chunk": 5,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_6 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
let first_name = item.resource_common_data.get_optional_billing_first_name();
let last_name = item.resource_common_data.get_optional_billing_last_name();
Ok(Self {
amount,
currency: item.request.currency,
payment_id: item
.resource_common_data
.connector_request_reference_id
.clone(),
customer_id,
email,
phone,
first_name,
last_name,
return_url: item.resource_common_data.get_return_url(),
})
}
}
// Request body transformation for PayTM initiate transaction
impl PaytmInitiateTxnRequest {
pub fn try_from_with_auth(
item: &PaytmRouterData,
auth: &PaytmAuthType,
) -> CustomResult<Self, errors::ConnectorError> {
let body = PaytmInitiateReqBody {
request_type: constants::REQUEST_TYPE_PAYMENT.to_string(),
mid: Secret::new(auth.merchant_id.peek().to_string()),
order_id: item.payment_id.clone(),
website_name: Secret::new(auth.website.peek().to_string()),
txn_amount: PaytmAmount {
value: item.amount.clone(),
currency: item.currency,
},
user_info: PaytmUserInfo {
cust_id: item
.customer_id
.clone()
.unwrap_or_else(|| constants::DEFAULT_CUSTOMER_ID.to_string()),
mobile: item.phone.clone(),
email: item.email.clone(),
first_name: item.first_name.clone(),
last_name: item.last_name.clone(),
},
enable_payment_mode: vec![PaytmEnableMethod {
mode: constants::PAYMENT_MODE_UPI.to_string(),
channels: Some(vec![
constants::UPI_CHANNEL_UPIPUSH.to_string(),
constants::PAYMENT_MODE_UPI.to_string(),
]),
}],
callback_url: item
.return_url
.clone()
.unwrap_or_else(|| constants::DEFAULT_CALLBACK_URL.to_string()),
};
// Create header with actual signature
let head = create_paytm_header(&body, auth)?;
Ok(Self { head, body })
}
}
// Request transformation for Authorize flow
impl<T: domain_types::payment_method_data::PaymentMethodDataTypes> PaytmAuthorizeRouterData<T> {
pub fn try_from_with_converter(
item: &RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
amount_converter: &dyn AmountConvertor<Output = StringMajorUnit>,
) -> Result<Self, error_stack::Report<errors::ConnectorError>> {
let amount = amount_converter
.convert(item.request.minor_amount, item.request.currency)
.change_context(errors::ConnectorError::AmountConversionFailed)?;
let customer_id = item
.resource_common_data
.get_customer_id()
.ok()
.map(|id| id.get_string_repr().to_string());
let email = item.resource_common_data.get_optional_billing_email();
let phone = item
.resource_common_data
.get_optional_billing_phone_number();
let first_name = item.resource_common_data.get_optional_billing_first_name();
let last_name = item.resource_common_data.get_optional_billing_last_name();
// Extract session token from previous session token response
let session_token = item.resource_common_data.get_session_token()?;
Ok(Self {
amount,
currency: item.request.currency,
payment_id: item
.resource_common_data
.connector_request_reference_id
.clone(),
session_token: Secret::new(session_token),
payment_method_data: item.request.payment_method_data.clone(),
customer_id,
email,
phone,
first_name,
last_name,
return_url: item.resource_common_data.get_return_url(),
})
}
}
// Request transformation for PayTM UPI Intent flow (ProcessTxnRequest)
impl PaytmProcessTxnRequest {
| {
"chunk": 6,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_7 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
pub fn try_from_with_auth<T: domain_types::payment_method_data::PaymentMethodDataTypes>(
item: &PaytmAuthorizeRouterData<T>,
auth: &PaytmAuthType,
) -> CustomResult<Self, errors::ConnectorError> {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
.to_string();
let head = PaytmProcessHeadTypes {
version: constants::API_VERSION.to_string(),
request_timestamp: timestamp,
channel_id: auth.channel_id.clone(),
txn_token: item.session_token.clone(),
};
let body = PaytmProcessBodyTypes {
mid: Secret::new(auth.merchant_id.peek().to_string()),
order_id: item.payment_id.clone(),
request_type: constants::REQUEST_TYPE_PAYMENT.to_string(),
payment_mode: format!("{}_{}", constants::PAYMENT_MODE_UPI, "INTENT"), // "UPI_INTENT" for intent
payment_flow: Some(constants::PAYMENT_FLOW_NONE.to_string()),
};
Ok(Self { head, body })
}
}
// Request transformation for PayTM UPI Collect flow (NativeProcessTxnRequest)
impl PaytmNativeProcessTxnRequest {
pub fn try_from_with_auth<T: domain_types::payment_method_data::PaymentMethodDataTypes>(
item: &PaytmAuthorizeRouterData<T>,
auth: &PaytmAuthType,
) -> CustomResult<Self, errors::ConnectorError> {
// Extract UPI VPA for collect flow
let vpa = extract_upi_vpa(&item.payment_method_data)?.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "vpa_id",
},
)?;
let head = PaytmTxnTokenType {
txn_token: item.session_token.clone(),
};
let body = PaytmNativeProcessRequestBody {
request_type: constants::REQUEST_TYPE_NATIVE.to_string(),
mid: Secret::new(auth.merchant_id.peek().to_string()),
order_id: item.payment_id.clone(),
payment_mode: constants::PAYMENT_MODE_UPI.to_string(),
payer_account: Some(vpa),
channel_code: Some("collect".to_string()), // Gateway code if needed
channel_id: auth.channel_id.clone(),
txn_token: item.session_token.clone(),
auth_mode: None,
};
Ok(Self { head, body })
}
}
// PSync (Payment Sync) flow request structures
#[derive(Debug, Serialize)]
pub struct PaytmTransactionStatusRequest {
pub head: PaytmRequestHeader,
pub body: PaytmTransactionStatusReqBody,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaytmTransactionStatusReqBody {
pub mid: Secret<String>, // Merchant ID
pub order_id: String, // Order ID
#[serde(skip_serializing_if = "Option::is_none")]
pub txn_type: Option<String>, // PREAUTH, CAPTURE, RELEASE, WITHDRAW
}
// PSync (Payment Sync) flow response structures
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmTransactionStatusResponse {
pub head: PaytmRespHead,
pub body: PaytmTransactionStatusRespBodyTypes,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PaytmTransactionStatusRespBodyTypes {
SuccessBody(Box<PaytmTransactionStatusRespBody>),
FailureBody(PaytmErrorBody),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaytmTransactionStatusRespBody {
pub result_info: PaytmResultInfo,
pub txn_id: Option<String>,
pub bank_txn_id: Option<String>,
pub order_id: Option<String>,
pub txn_amount: Option<StringMajorUnit>,
pub txn_type: Option<String>,
pub gateway_name: Option<String>,
pub mid: Option<String>,
pub payment_mode: Option<String>,
pub refund_amt: Option<String>,
pub txn_date: Option<String>,
}
// Helper struct for PSync RouterData transformation
#[derive(Debug, Clone)]
pub struct PaytmSyncRouterData {
pub payment_id: String,
pub connector_transaction_id: Option<String>,
pub txn_type: Option<String>,
}
// Request transformation for PSync flow
impl TryFrom<&RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>>
for PaytmSyncRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
| {
"chunk": 7,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_8 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
item: &RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Use connector transaction ID if available, otherwise fall back to payment ID
let transaction_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.unwrap_or_else(|_| {
item.resource_common_data
.connector_request_reference_id
.clone()
});
let connector_transaction_id = item
.request
.connector_transaction_id
.get_connector_transaction_id()
.map_err(|_| {
error_stack::Report::new(errors::ConnectorError::MissingConnectorTransactionID)
})?;
Ok(Self {
payment_id: transaction_id,
connector_transaction_id: Some(connector_transaction_id),
txn_type: None,
})
}
}
// Request body transformation for PayTM transaction status
impl PaytmTransactionStatusRequest {
pub fn try_from_with_auth(
item: &PaytmSyncRouterData,
auth: &PaytmAuthType,
) -> CustomResult<Self, errors::ConnectorError> {
let body = PaytmTransactionStatusReqBody {
mid: Secret::new(auth.merchant_id.peek().to_string()),
order_id: item.payment_id.clone(),
txn_type: item.txn_type.clone(),
};
// Create header with actual signature
let head = create_paytm_header(&body, auth)?;
Ok(Self { head, body })
}
}
// Status mapping function for Paytm result codes
pub fn map_paytm_status_to_attempt_status(result_code: &str) -> AttemptStatus {
match result_code {
// Success
"01" => AttemptStatus::Charged, // TXN_SUCCESS
"0000" => AttemptStatus::AuthenticationPending, // Success - waiting for authentication
// Pending cases
"400" | "402" => AttemptStatus::Pending, // PENDING, PENDING_BANK_CONFIRM
"331" => AttemptStatus::Pending, // NO_RECORD_FOUND
// Failure cases
"227" | "235" | "295" | "334" | "335" | "401" | "501" | "810" | "843" | "820" | "267" => {
AttemptStatus::Failure
}
// Default to failure for unknown codes (WILL NEVER HAPPEN)
_ => AttemptStatus::Pending,
}
}
// Additional response structures needed for compilation
// Session token error response structure
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmSessionTokenErrorResponse {
pub head: PaytmRespHead,
pub body: PaytmSessionTokenErrorBody,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmSessionTokenErrorBody {
#[serde(rename = "extraParamsMap")]
pub extra_params_map: Option<serde_json::Value>, // This field must be present (even if null) to distinguish from other types
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
}
// Success transaction response structure (handles both callback and standard formats)
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmSuccessTransactionResponse {
pub head: PaytmRespHead,
pub body: PaytmSuccessTransactionBody,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmSuccessTransactionBody {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
#[serde(rename = "txnInfo")]
pub txn_info: PaytmTxnInfo,
#[serde(rename = "callBackUrl")]
pub callback_url: Option<String>,
}
// Bank form response structure
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmBankFormResponse {
pub head: PaytmRespHead,
pub body: PaytmBankFormBody,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmBankFormBody {
#[serde(rename = "resultInfo")]
pub result_info: PaytmResultInfo,
#[serde(rename = "bankForm")]
pub bank_form: PaytmBankForm,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmBankForm {
#[serde(rename = "redirectForm")]
pub redirect_form: PaytmRedirectForm,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct PaytmRedirectForm {
#[serde(rename = "actionUrl")]
pub action_url: String,
pub method: String,
pub content: HashMap<String, String>,
}
// TryFrom implementations required by the macro framework
| {
"chunk": 8,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_9 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
// The macro expects TryFrom implementations that work with its generated PaytmRouterData<RouterDataV2<...>>
// Since the macro generates PaytmRouterData<T> but our existing PaytmRouterData is not generic,
// we need to implement TryFrom for the exact RouterDataV2 types the macro expects
// PaytmInitiateTxnRequest TryFrom CreateSessionToken RouterData
// Using the macro-generated PaytmRouterData type from the paytm module
impl<
T: domain_types::payment_method_data::PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ serde::Serialize,
>
TryFrom<
MacroPaytmRouterData<
RouterDataV2<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
>,
T,
>,
> for PaytmInitiateTxnRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: MacroPaytmRouterData<
RouterDataV2<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = PaytmAuthType::try_from(&item.router_data.connector_auth_type)?;
let intermediate_router_data = PaytmRouterData::try_from_with_converter(
&item.router_data,
item.connector.amount_converter,
)?;
PaytmInitiateTxnRequest::try_from_with_auth(&intermediate_router_data, &auth)
}
}
// PaytmAuthorizeRequest TryFrom Authorize RouterData
impl<
T: domain_types::payment_method_data::PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ serde::Serialize,
>
TryFrom<
MacroPaytmRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for PaytmAuthorizeRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: MacroPaytmRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = PaytmAuthType::try_from(&item.router_data.connector_auth_type)?;
let intermediate_authorize_router_data = PaytmAuthorizeRouterData::try_from_with_converter(
&item.router_data,
item.connector.amount_converter,
)?;
// Determine the UPI flow type based on payment method data
let upi_flow = determine_upi_flow(&item.router_data.request.payment_method_data)?;
match upi_flow {
UpiFlowType::Intent => {
// UPI Intent flow - use PaytmProcessTxnRequest
let intent_request = PaytmProcessTxnRequest::try_from_with_auth(
&intermediate_authorize_router_data,
&auth,
)?;
Ok(PaytmAuthorizeRequest::Intent(intent_request))
}
UpiFlowType::Collect => {
// UPI Collect flow - use PaytmNativeProcessTxnRequest
let collect_request = PaytmNativeProcessTxnRequest::try_from_with_auth(
&intermediate_authorize_router_data,
&auth,
)?;
Ok(PaytmAuthorizeRequest::Collect(collect_request))
}
}
}
}
// PaytmTransactionStatusRequest TryFrom PSync RouterData
impl<
T: domain_types::payment_method_data::PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ serde::Serialize,
>
TryFrom<
MacroPaytmRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
> for PaytmTransactionStatusRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
| {
"chunk": 9,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_10 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
item: MacroPaytmRouterData<
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
T,
>,
) -> Result<Self, Self::Error> {
let auth = PaytmAuthType::try_from(&item.router_data.connector_auth_type)?;
let intermediate_sync_router_data = PaytmSyncRouterData::try_from(&item.router_data)?;
PaytmTransactionStatusRequest::try_from_with_auth(&intermediate_sync_router_data, &auth)
}
}
// ResponseRouterData TryFrom implementations required by the macro framework
// CreateSessionToken response transformation
impl
TryFrom<
ResponseRouterData<
PaytmInitiateTxnResponse,
RouterDataV2<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
>,
>,
>
for RouterDataV2<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PaytmInitiateTxnResponse,
RouterDataV2<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
>,
>,
) -> Result<Self, Self::Error> {
let response = &item.response;
let mut router_data = item.router_data;
// Handle both success and failure cases from the enum body
let session_token = match &response.body {
PaytmResBodyTypes::SuccessBody(success_body) => Some(success_body.txn_token.clone()),
PaytmResBodyTypes::FailureBody(_failure_body) => None,
};
router_data.response = Ok(SessionTokenResponseData {
session_token: session_token.unwrap_or_default().expose(),
});
Ok(router_data)
}
}
// Authorize response transformation
impl<
T: domain_types::payment_method_data::PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ serde::Serialize,
>
TryFrom<
ResponseRouterData<
PaytmProcessTxnResponse,
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
> for RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PaytmProcessTxnResponse,
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
>,
) -> Result<Self, Self::Error> {
let response = &item.response;
let mut router_data = item.router_data;
// Handle both success and failure cases from the enum body
let (redirection_data, resource_id, connector_txn_id) = match &response.body {
PaytmProcessRespBodyTypes::SuccessBody(success_body) => {
// Extract redirection URL if present
let redirection_data = if let Some(deep_link_info) = &success_body.deep_link_info {
if !deep_link_info.deep_link.is_empty() {
// Check if it's a UPI deep link (starts with upi://) or regular URL
if deep_link_info.deep_link.starts_with("upi://") {
// For UPI deep links, use them as-is
Some(Box::new(RedirectForm::Uri {
uri: deep_link_info.deep_link.clone(),
}))
} else {
// For regular URLs, parse and convert
let url = Url::parse(&deep_link_info.deep_link).change_context(
errors::ConnectorError::ResponseDeserializationFailed,
)?;
Some(Box::new(RedirectForm::from((url, Method::Get))))
}
| {
"chunk": 10,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_11 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
} else {
None
}
} else {
None
};
// Extract transaction IDs from deep_link_info or use fallback
let (resource_id, connector_txn_id) =
if let Some(deep_link_info) = &success_body.deep_link_info {
let resource_id =
ResponseId::ConnectorTransactionId(deep_link_info.order_id.clone());
let connector_txn_id = Some(deep_link_info.trans_id.clone());
(resource_id, connector_txn_id)
} else {
// Fallback when deep_link_info is not present
let resource_id = ResponseId::ConnectorTransactionId(
router_data
.resource_common_data
.connector_request_reference_id
.clone(),
);
(resource_id, None)
};
(redirection_data, resource_id, connector_txn_id)
}
PaytmProcessRespBodyTypes::FailureBody(_failure_body) => {
let resource_id = ResponseId::ConnectorTransactionId(
router_data
.resource_common_data
.connector_request_reference_id
.clone(),
);
(None, resource_id, None)
}
};
// Get result code for status mapping
let result_code = match &response.body {
PaytmProcessRespBodyTypes::SuccessBody(success_body) => {
&success_body.result_info.result_code
}
PaytmProcessRespBodyTypes::FailureBody(failure_body) => {
&failure_body.result_info.result_code
}
};
// Map status using the result code
let attempt_status = map_paytm_status_to_attempt_status(result_code);
router_data.resource_common_data.set_status(attempt_status);
router_data.response = Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: connector_txn_id,
incremental_authorization_allowed: None,
status_code: item.http_code,
});
Ok(router_data)
}
}
// PSync response transformation
impl
TryFrom<
ResponseRouterData<
PaytmTransactionStatusResponse,
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
>,
> for RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
PaytmTransactionStatusResponse,
RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
>,
) -> Result<Self, Self::Error> {
let response = &item.response;
let mut router_data = item.router_data;
// Handle both success and failure cases from the enum body
let (resource_id, connector_txn_id) = match &response.body {
PaytmTransactionStatusRespBodyTypes::SuccessBody(success_body) => {
let order_id = success_body.order_id.clone().unwrap_or_else(|| {
router_data
.resource_common_data
.connector_request_reference_id
.clone()
});
let resource_id = ResponseId::ConnectorTransactionId(order_id);
let connector_txn_id = success_body.txn_id.clone();
(resource_id, connector_txn_id)
}
PaytmTransactionStatusRespBodyTypes::FailureBody(_failure_body) => {
let resource_id = ResponseId::ConnectorTransactionId(
router_data
.resource_common_data
.connector_request_reference_id
.clone(),
| {
"chunk": 11,
"crate": "connector-integration",
"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_connector-integration_-7010937598925635194_12 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/paytm/transformers.rs
);
(resource_id, None)
}
};
// Get result code for status mapping
let result_code = match &response.body {
PaytmTransactionStatusRespBodyTypes::SuccessBody(success_body) => {
&success_body.result_info.result_code
}
PaytmTransactionStatusRespBodyTypes::FailureBody(failure_body) => {
&failure_body.result_info.result_code
}
};
// Map status and set response accordingly
let attempt_status = map_paytm_status_to_attempt_status(result_code);
// Update the status using the new setter function
router_data.resource_common_data.set_status(attempt_status);
router_data.response = match attempt_status {
AttemptStatus::Failure => Err(domain_types::router_data::ErrorResponse {
code: result_code.clone(),
message: match &response.body {
PaytmTransactionStatusRespBodyTypes::SuccessBody(body) => {
body.result_info.result_msg.clone()
}
PaytmTransactionStatusRespBodyTypes::FailureBody(body) => {
body.result_info.result_msg.clone()
}
},
reason: None,
status_code: item.http_code,
attempt_status: Some(attempt_status),
connector_transaction_id: connector_txn_id.clone(),
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
_ => Ok(PaymentsResponseData::TransactionResponse {
resource_id,
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: connector_txn_id,
incremental_authorization_allowed: None,
status_code: item.http_code,
}),
};
Ok(router_data)
}
}
| {
"chunk": 12,
"crate": "connector-integration",
"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_connector-integration_-4518715165494810008_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/mifinity/transformers.rs
use common_enums::{enums, Currency};
use common_utils::{
pii::{self, Email},
types::StringMajorUnit,
};
use domain_types::{
connector_flow::Authorize,
connector_types::{
PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData, PaymentsSyncData, ResponseId,
},
errors::ConnectorError,
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, WalletData},
router_data::ConnectorAuthType,
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::Date;
use super::MifinityRouterData;
use crate::{types::ResponseRouterData, utils};
pub mod auth_headers {
pub const API_VERSION: &str = "api-version";
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct MifinityConnectorMetadataObject {
pub brand_id: Secret<String>,
pub destination_account_number: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for MifinityConnectorMetadataObject {
type Error = error_stack::Report<ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
.change_context(ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
Ok(metadata)
}
}
#[derive(Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MifinityPaymentsRequest {
money: Money,
client: MifinityClient,
address: MifinityAddress,
validation_key: String,
client_reference: common_utils::id_type::CustomerId,
trace_id: String,
description: String,
destination_account_number: Secret<String>,
brand_id: Secret<String>,
return_url: String,
#[serde(skip_serializing_if = "Option::is_none")]
language_preference: Option<String>,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct Money {
amount: StringMajorUnit,
currency: Currency,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MifinityClient {
first_name: Secret<String>,
last_name: Secret<String>,
phone: Secret<String>,
dialing_code: String,
nationality: enums::CountryAlpha2,
email_address: Email,
dob: Secret<Date>,
}
#[derive(Default, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MifinityAddress {
address_line1: Secret<String>,
country_code: enums::CountryAlpha2,
city: String,
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
MifinityRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for MifinityPaymentsRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: MifinityRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let metadata: MifinityConnectorMetadataObject = utils::to_connector_meta_from_secret(
item.router_data
.resource_common_data
.connector_meta_data
.clone(),
)
.change_context(ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?;
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::Mifinity(data) => {
let money = Money {
amount: item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount,
item.router_data.request.currency,
)
| {
"chunk": 0,
"crate": "connector-integration",
"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_connector-integration_-4518715165494810008_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/mifinity/transformers.rs
.change_context(ConnectorError::RequestEncodingFailed)?,
currency: item.router_data.request.currency,
};
let phone_details =
item.router_data.resource_common_data.get_billing_phone()?;
let billing_country = item
.router_data
.resource_common_data
.get_billing_country()?;
let client = MifinityClient {
first_name: item
.router_data
.resource_common_data
.get_billing_first_name()?,
last_name: item
.router_data
.resource_common_data
.get_billing_last_name()?,
phone: phone_details.get_number()?,
dialing_code: phone_details.get_country_code()?,
nationality: billing_country,
email_address: item.router_data.resource_common_data.get_billing_email()?,
dob: data.date_of_birth.clone(),
};
let address = MifinityAddress {
address_line1: item.router_data.resource_common_data.get_billing_line1()?,
country_code: billing_country,
city: item.router_data.resource_common_data.get_billing_city()?,
};
let validation_key = format!(
"payment_validation_key_{}_{}",
item.router_data
.resource_common_data
.merchant_id
.get_string_repr(),
item.router_data
.resource_common_data
.connector_request_reference_id
.clone()
);
let client_reference = item.router_data.request.customer_id.clone().ok_or(
ConnectorError::MissingRequiredField {
field_name: "client_reference",
},
)?;
let destination_account_number = metadata.destination_account_number;
let trace_id = item
.router_data
.resource_common_data
.connector_request_reference_id
.clone();
let brand_id = metadata.brand_id;
let language_preference = data.language_preference;
Ok(Self {
money,
client,
address,
validation_key,
client_reference,
trace_id: trace_id.clone(),
description: trace_id.clone(), //Connector recommend to use the traceId for a better experience in the BackOffice application later.
destination_account_number,
brand_id,
return_url: item.router_data.request.get_router_return_url()?,
language_preference,
})
}
WalletData::AliPayQr(_)
| WalletData::BluecodeRedirect {}
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePay(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| {
"chunk": 1,
"crate": "connector-integration",
"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.