Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(connector): [Paypal] implement vaulting for paypal wallet and cards while purchasing (#5323)
Kiran Kumar22ba2dbb2870
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rsindex d20ac148b7..344eb632f4 100644--- a/crates/hyperswitch_domain_models/src/router_request_types.rs+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs@@ -88,6 +88,8 @@ pub struct PaymentsPostSessionTokensData {/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.pub merchant_order_reference_id: Option<String>,pub shipping_cost: Option<MinorUnit>,+ pub setup_future_usage: Option<storage_enums::FutureUsage>,+ pub router_return_url: Option<String>,}#[derive(Debug, Clone, PartialEq)]diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rsindex 24899a2c7d..48a35c78cc 100644--- a/crates/router/src/connector/paypal.rs+++ b/crates/router/src/connector/paypal.rs@@ -17,7 +17,8 @@ use transformers as paypal;use self::transformers::{auth_headers, PaypalAuthResponse, PaypalMeta, PaypalWebhookEventType};use super::utils::{- ConnectorErrorType, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,+ ConnectorErrorType, PaymentMethodDataType, PaymentsAuthorizeRequestData,+ PaymentsCompleteAuthorizeRequestData,};use crate::{configs::settings,@@ -332,6 +333,18 @@ impl ConnectorValidation for Paypal {),}}+ fn validate_mandate_payment(+ &self,+ pm_type: Option<types::storage::enums::PaymentMethodType>,+ pm_data: domain::PaymentMethodData,+ ) -> CustomResult<(), errors::ConnectorError> {+ let mandate_supported_pmd = std::collections::HashSet::from([+ PaymentMethodDataType::Card,+ PaymentMethodDataType::PaypalRedirect,+ PaymentMethodDataType::PaypalSdk,+ ]);+ connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())+ }}impldiff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rsindex 24b1c0a2fc..3e01c614e8 100644--- a/crates/router/src/connector/paypal/transformers.rs+++ b/crates/router/src/connector/paypal/transformers.rs@@ -4,6 +4,7 @@ use base64::Engine;use common_utils::pii::Email;use common_utils::{errors::CustomResult, types::StringMajorUnit};use error_stack::ResultExt;+use hyperswitch_domain_models::router_response_types::MandateReference;use masking::{ExposeInterface, Secret};use serde::{Deserialize, Serialize};use time::PrimitiveDateTime;@@ -11,8 +12,8 @@ use url::Url;use crate::{connector::utils::{- self, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData, CardData,- PaymentsAuthorizeRequestData, PaymentsPostSessionTokensRequestData, RouterData,+ self, missing_field_err, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData,+ CardData, PaymentsAuthorizeRequestData, PaymentsPostSessionTokensRequestData, RouterData,},consts,core::errors,@@ -296,7 +297,7 @@ impl TryFrom<&PaypalRouterData<&types::SdkSessionUpdateRouterData>> for ItemDeta}}-#[derive(Default, Debug, Serialize, Eq, PartialEq)]+#[derive(Default, Debug, Serialize, Eq, PartialEq, Deserialize)]pub struct Address {address_line_1: Option<Secret<String>>,postal_code: Option<Secret<String>>,@@ -380,18 +381,30 @@ pub struct ShippingName {}#[derive(Debug, Serialize)]-pub struct CardRequest {+pub struct CardRequestStruct {billing_address: Option<Address>,expiry: Option<Secret<String>>,- name: Secret<String>,+ name: Option<Secret<String>>,number: Option<cards::CardNumber>,security_code: Option<Secret<String>>,- attributes: Option<ThreeDsSetting>,+ attributes: Option<CardRequestAttributes>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct VaultStruct {+ vault_id: Secret<String>,}#[derive(Debug, Serialize)]-pub struct ThreeDsSetting {- verification: ThreeDsMethod,+#[serde(untagged)]+pub enum CardRequest {+ CardRequestStruct(CardRequestStruct),+ CardVaultStruct(VaultStruct),+}+#[derive(Debug, Serialize)]+pub struct CardRequestAttributes {+ vault: Option<PaypalVault>,+ verification: Option<ThreeDsMethod>,}#[derive(Debug, Serialize)]@@ -435,8 +448,55 @@ pub enum ShippingPreference {}#[derive(Debug, Serialize)]-pub struct PaypalRedirectionRequest {+#[serde(untagged)]+pub enum PaypalRedirectionRequest {+ PaypalRedirectionStruct(PaypalRedirectionStruct),+ PaypalVaultStruct(VaultStruct),+}++#[derive(Debug, Serialize)]+pub struct PaypalRedirectionStruct {experience_context: ContextStruct,+ attributes: Option<Attributes>,+}+#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct Attributes {+ vault: PaypalVault,+}++#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct PaypalRedirectionResponse {+ attributes: Option<AttributeResponse>,+}++#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct AttributeResponse {+ vault: PaypalVaultResponse,+}+#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct PaypalVault {+ store_in_vault: StoreInVault,+ usage_type: UsageType,+}+#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct PaypalVaultResponse {+ id: String,+ status: String,+ customer: CustomerId,+}+#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct CustomerId {+ id: String,+}+#[derive(Debug, Serialize, Deserialize, Clone)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum StoreInVault {+ OnSuccess,+}+#[derive(Debug, Serialize, Deserialize, Clone)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum UsageType {+ Merchant,}#[derive(Debug, Serialize)]@@ -449,6 +509,16 @@ pub enum PaymentSourceItem {Giropay(RedirectRequest),Sofort(RedirectRequest),}+#[derive(Debug, Serialize, Deserialize, Clone)]+pub struct CardVaultResponse {+ attributes: Option<AttributeResponse>,+}+#[derive(Debug, Serialize, Deserialize, Clone)]+#[serde(rename_all = "lowercase")]+pub enum PaymentSourceItemResponse {+ Card(CardVaultResponse),+ Paypal(PaypalRedirectionResponse),+}#[derive(Debug, Serialize)]pub struct PaypalPaymentsRequest {@@ -607,14 +677,28 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>>shipping: Some(shipping_address),items: item_details,}];- let payment_source = Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest {- experience_context: ContextStruct {- return_url: None,- cancel_url: None,- shipping_preference: ShippingPreference::GetFromFile,- user_action: Some(UserAction::PayNow),- },- }));+ let payment_source = Some(PaymentSourceItem::Paypal(+ PaypalRedirectionRequest::PaypalRedirectionStruct(PaypalRedirectionStruct {+ experience_context: ContextStruct {+ return_url: item.router_data.request.router_return_url.clone(),+ cancel_url: item.router_data.request.router_return_url.clone(),+ shipping_preference: ShippingPreference::GetFromFile,+ user_action: Some(UserAction::PayNow),+ },+ attributes: match item.router_data.request.setup_future_usage {+ Some(setup_future_usage) => match setup_future_usage {+ enums::FutureUsage::OffSession => Some(Attributes {+ vault: PaypalVault {+ store_in_vault: StoreInVault::OnSuccess,+ usage_type: UsageType::Merchant,+ },+ }),+ enums::FutureUsage::OnSession => None,+ },+ None => None,+ },+ }),+ ));Ok(Self {intent,@@ -695,26 +779,36 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalPlet card = item.router_data.request.get_card()?;let expiry = Some(card.get_expiry_date_as_yyyymm("-"));- let attributes = match item.router_data.auth_type {- enums::AuthenticationType::ThreeDs => Some(ThreeDsSetting {- verification: ThreeDsMethod {- method: ThreeDsType::ScaAlways,- },+ let verification = match item.router_data.auth_type {+ enums::AuthenticationType::ThreeDs => Some(ThreeDsMethod {+ method: ThreeDsType::ScaAlways,}),enums::AuthenticationType::NoThreeDs => None,};- let payment_source = Some(PaymentSourceItem::Card(CardRequest {- billing_address: get_address_info(item.router_data.get_optional_billing()),- expiry,- name: item- .router_data- .get_optional_billing_full_name()- .unwrap_or(Secret::new("".to_string())),- number: Some(ccard.card_number.clone()),- security_code: Some(ccard.card_cvc.clone()),- attributes,- }));+ let payment_source = Some(PaymentSourceItem::Card(CardRequest::CardRequestStruct(+ CardRequestStruct {+ billing_address: get_address_info(item.router_data.get_optional_billing()),+ expiry,+ name: item.router_data.get_optional_billing_full_name(),+ number: Some(ccard.card_number.clone()),+ security_code: Some(ccard.card_cvc.clone()),+ attributes: Some(CardRequestAttributes {+ vault: match item.router_data.request.setup_future_usage {+ Some(setup_future_usage) => match setup_future_usage {+ enums::FutureUsage::OffSession => Some(PaypalVault {+ store_in_vault: StoreInVault::OnSuccess,+ usage_type: UsageType::Merchant,+ }),++ enums::FutureUsage::OnSession => None,+ },+ None => None,+ },+ verification,+ }),+ },+ )));Ok(Self {intent,@@ -724,23 +818,46 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP}domain::PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {domain::WalletData::PaypalRedirect(_) => {- let payment_source =- Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest {- experience_context: ContextStruct {- return_url: item.router_data.request.complete_authorize_url.clone(),- cancel_url: item.router_data.request.complete_authorize_url.clone(),- shipping_preference: if item- .router_data- .get_optional_shipping_country()- .is_some()- {- ShippingPreference::SetProvidedAddress- } else {- ShippingPreference::GetFromFile+ let payment_source = Some(PaymentSourceItem::Paypal(+ PaypalRedirectionRequest::PaypalRedirectionStruct(+ PaypalRedirectionStruct {+ experience_context: ContextStruct {+ return_url: item+ .router_data+ .request+ .complete_authorize_url+ .clone(),+ cancel_url: item+ .router_data+ .request+ .complete_authorize_url+ .clone(),+ shipping_preference: if item+ .router_data+ .get_optional_shipping()+ .is_some()+ {+ ShippingPreference::SetProvidedAddress+ } else {+ ShippingPreference::GetFromFile+ },+ user_action: Some(UserAction::PayNow),+ },+ attributes: match item.router_data.request.setup_future_usage {+ Some(setup_future_usage) => match setup_future_usage {+ enums::FutureUsage::OffSession => Some(Attributes {+ vault: PaypalVault {+ store_in_vault: StoreInVault::OnSuccess,+ usage_type: UsageType::Merchant,+ },+ }),+ enums::FutureUsage::OnSession => None,+ },+ None => None,},- user_action: Some(UserAction::PayNow),},- }));+ ),+ ));Ok(Self {intent,@@ -749,15 +866,30 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP})}domain::WalletData::PaypalSdk(_) => {- let payment_source =- Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest {- experience_context: ContextStruct {- return_url: None,- cancel_url: None,- shipping_preference: ShippingPreference::GetFromFile,- user_action: Some(UserAction::PayNow),+ let payment_source = Some(PaymentSourceItem::Paypal(+ PaypalRedirectionRequest::PaypalRedirectionStruct(+ PaypalRedirectionStruct {+ experience_context: ContextStruct {+ return_url: None,+ cancel_url: None,+ shipping_preference: ShippingPreference::GetFromFile,+ user_action: Some(UserAction::PayNow),+ },+ attributes: match item.router_data.request.setup_future_usage {+ Some(setup_future_usage) => match setup_future_usage {+ enums::FutureUsage::OffSession => Some(Attributes {+ vault: PaypalVault {+ store_in_vault: StoreInVault::OnSuccess,+ usage_type: UsageType::Merchant,+ },+ }),+ enums::FutureUsage::OnSession => None,+ },+ None => None,+ },},- }));+ ),+ ));Ok(Self {intent,@@ -828,10 +960,132 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalPSelf::try_from(giftcard_data.as_ref())}domain::PaymentMethodData::MandatePayment => {- Err(errors::ConnectorError::NotImplemented(- utils::get_unimplemented_payment_method_error_message("Paypal"),- )- .into())+ let payment_method_type = item+ .router_data+ .get_recurring_mandate_payment_data()?+ .payment_method_type+ .ok_or_else(missing_field_err("payment_method_type"))?;++ let connector_mandate_id = item.router_data.request.connector_mandate_id().ok_or(+ errors::ConnectorError::MissingRequiredField {+ field_name: "connector_mandate_id",+ },+ )?;++ let payment_source = match payment_method_type {+ enums::PaymentMethodType::Credit => Ok(Some(PaymentSourceItem::Card(+ CardRequest::CardVaultStruct(VaultStruct {+ vault_id: connector_mandate_id.into(),+ }),+ ))),+ enums::PaymentMethodType::Paypal => Ok(Some(PaymentSourceItem::Paypal(+ PaypalRedirectionRequest::PaypalVaultStruct(VaultStruct {+ vault_id: connector_mandate_id.into(),+ }),+ ))),+ enums::PaymentMethodType::Ach+ | enums::PaymentMethodType::Affirm+ | enums::PaymentMethodType::AfterpayClearpay+ | enums::PaymentMethodType::Alfamart+ | enums::PaymentMethodType::AliPay+ | enums::PaymentMethodType::AliPayHk+ | enums::PaymentMethodType::Alma+ | enums::PaymentMethodType::ApplePay+ | enums::PaymentMethodType::Atome+ | enums::PaymentMethodType::Bacs+ | enums::PaymentMethodType::BancontactCard+ | enums::PaymentMethodType::Becs+ | enums::PaymentMethodType::Benefit+ | enums::PaymentMethodType::Bizum+ | enums::PaymentMethodType::Blik+ | enums::PaymentMethodType::Boleto+ | enums::PaymentMethodType::BcaBankTransfer+ | enums::PaymentMethodType::BniVa+ | enums::PaymentMethodType::BriVa+ | enums::PaymentMethodType::CardRedirect+ | enums::PaymentMethodType::CimbVa+ | enums::PaymentMethodType::ClassicReward+ | enums::PaymentMethodType::CryptoCurrency+ | enums::PaymentMethodType::Cashapp+ | enums::PaymentMethodType::Dana+ | enums::PaymentMethodType::DanamonVa+ | enums::PaymentMethodType::Debit+ | enums::PaymentMethodType::DuitNow+ | enums::PaymentMethodType::Efecty+ | enums::PaymentMethodType::Eps+ | enums::PaymentMethodType::Fps+ | enums::PaymentMethodType::Evoucher+ | enums::PaymentMethodType::Giropay+ | enums::PaymentMethodType::Givex+ | enums::PaymentMethodType::GooglePay+ | enums::PaymentMethodType::GoPay+ | enums::PaymentMethodType::Gcash+ | enums::PaymentMethodType::Ideal+ | enums::PaymentMethodType::Interac+ | enums::PaymentMethodType::Indomaret+ | enums::PaymentMethodType::Klarna+ | enums::PaymentMethodType::KakaoPay+ | enums::PaymentMethodType::LocalBankRedirect+ | enums::PaymentMethodType::MandiriVa+ | enums::PaymentMethodType::Knet+ | enums::PaymentMethodType::MbWay+ | enums::PaymentMethodType::MobilePay+ | enums::PaymentMethodType::Momo+ | enums::PaymentMethodType::MomoAtm+ | enums::PaymentMethodType::Multibanco+ | enums::PaymentMethodType::OnlineBankingThailand+ | enums::PaymentMethodType::OnlineBankingCzechRepublic+ | enums::PaymentMethodType::OnlineBankingFinland+ | enums::PaymentMethodType::OnlineBankingFpx+ | enums::PaymentMethodType::OnlineBankingPoland+ | enums::PaymentMethodType::OnlineBankingSlovakia+ | enums::PaymentMethodType::OpenBankingPIS+ | enums::PaymentMethodType::Oxxo+ | enums::PaymentMethodType::PagoEfectivo+ | enums::PaymentMethodType::PermataBankTransfer+ | enums::PaymentMethodType::OpenBankingUk+ | enums::PaymentMethodType::PayBright+ | enums::PaymentMethodType::Pix+ | enums::PaymentMethodType::PaySafeCard+ | enums::PaymentMethodType::Przelewy24+ | enums::PaymentMethodType::PromptPay+ | enums::PaymentMethodType::Pse+ | enums::PaymentMethodType::RedCompra+ | enums::PaymentMethodType::RedPagos+ | enums::PaymentMethodType::SamsungPay+ | enums::PaymentMethodType::Sepa+ | enums::PaymentMethodType::Sofort+ | enums::PaymentMethodType::Swish+ | enums::PaymentMethodType::TouchNGo+ | enums::PaymentMethodType::Trustly+ | enums::PaymentMethodType::Twint+ | enums::PaymentMethodType::UpiCollect+ | enums::PaymentMethodType::UpiIntent+ | enums::PaymentMethodType::Vipps+ | enums::PaymentMethodType::VietQr+ | enums::PaymentMethodType::Venmo+ | enums::PaymentMethodType::Walley+ | enums::PaymentMethodType::WeChatPay+ | enums::PaymentMethodType::SevenEleven+ | enums::PaymentMethodType::Lawson+ | enums::PaymentMethodType::MiniStop+ | enums::PaymentMethodType::FamilyMart+ | enums::PaymentMethodType::Seicomart+ | enums::PaymentMethodType::PayEasy+ | enums::PaymentMethodType::LocalBankTransfer+ | enums::PaymentMethodType::Mifinity+ | enums::PaymentMethodType::Paze => {+ Err(errors::ConnectorError::NotImplemented(+ utils::get_unimplemented_payment_method_error_message("paypal"),+ ))+ }+ };++ Ok(Self {+ intent,+ purchase_units,+ payment_source: payment_source?,+ })}domain::PaymentMethodData::Reward| domain::PaymentMethodData::RealTimePayment(_)@@ -1257,6 +1511,7 @@ pub struct PaypalOrdersResponse {intent: PaypalPaymentIntent,status: PaypalOrderStatus,purchase_units: Vec<PurchaseUnitItem>,+ payment_source: Option<PaymentSourceItemResponse>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -1277,6 +1532,7 @@ pub struct PaypalRedirectResponse {status: PaypalOrderStatus,purchase_units: Vec<RedirectPurchaseUnitItem>,links: Vec<PaypalLinks>,+ payment_source: Option<PaymentSourceItemResponse>,}// Note: Don't change order of deserialization of variant, priority is in descending order@@ -1431,7 +1687,22 @@ impl<F, T>response: Ok(types::PaymentsResponseData::TransactionResponse {resource_id: order_id,redirection_data: Box::new(None),- mandate_reference: Box::new(None),+ mandate_reference: Box::new(Some(MandateReference {+ connector_mandate_id: match item.response.payment_source.clone() {+ Some(paypal_source) => match paypal_source {+ PaymentSourceItemResponse::Paypal(paypal_source) => {+ paypal_source.attributes.map(|attr| attr.vault.id)+ }+ PaymentSourceItemResponse::Card(card) => {+ card.attributes.map(|attr| attr.vault.id)+ }+ },+ None => None,+ },+ payment_method_id: None,+ mandate_metadata: None,+ connector_mandate_request_reference_id: None,+ })),connector_metadata: Some(connector_meta),network_txn_id: None,connector_response_reference_id: purchase_units@@ -2094,6 +2365,7 @@ pub struct PaypalCaptureResponse {amount: Option<OrderAmount>,invoice_id: Option<String>,final_capture: bool,+ payment_source: Option<PaymentSourceItemResponse>,}impl From<PaypalPaymentStatus> for storage_enums::AttemptStatus {@@ -2647,6 +2919,7 @@ impl TryFrom<(PaypalRedirectsWebhooks, PaypalWebhookEventType)> for PaypalOrdersintent: webhook_body.intent,status: PaypalOrderStatus::try_from(webhook_event)?,purchase_units: webhook_body.purchase_units,+ payment_source: None,})}}diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rsindex 95d114d3d6..38b475590f 100644--- a/crates/router/src/core/payments/transformers.rs+++ b/crates/router/src/core/payments/transformers.rs@@ -2609,6 +2609,15 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSess.payment_intent.merchant_order_reference_id.clone();+ let router_base_url = &additional_data.router_base_url;+ let connector_name = &additional_data.connector_name;+ let attempt = &payment_data.payment_attempt;+ let router_return_url = Some(helpers::create_redirect_url(+ router_base_url,+ attempt,+ connector_name,+ payment_data.creds_identifier.as_deref(),+ ));Ok(Self {amount, //need to change after we move to connector moduleorder_amount: payment_data.payment_intent.amount,@@ -2616,6 +2625,8 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessmerchant_order_reference_id,capture_method: payment_data.payment_attempt.capture_method,shipping_cost: payment_data.payment_intent.shipping_cost,+ setup_future_usage: payment_data.payment_intent.setup_future_usage,+ router_return_url,})}}