text
stringlengths
65
57.3k
file_path
stringlengths
22
92
module
stringclasses
38 values
type
stringclasses
7 values
struct_name
stringlengths
3
60
impl_count
int64
0
60
traits
listlengths
0
59
tokens
int64
16
8.19k
function_name
stringlengths
3
85
type_name
stringlengths
1
67
trait_name
stringclasses
573 values
method_count
int64
0
31
public_method_count
int64
0
19
submodule_count
int64
0
56
export_count
int64
0
9
// File: crates/common_utils/src/crypto.rs // Module: common_utils // Public functions: 10 // Public structs: 14 //! Utilities for cryptographic algorithms use std::ops::Deref; use base64::Engine; use error_stack::ResultExt; use masking::{ExposeInterface, Secret}; use md5; use pem; use ring::{ aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey}, hmac, rand as ring_rand, signature::{RsaKeyPair, RSA_PSS_SHA256}, }; #[cfg(feature = "logs")] use router_env::logger; use rsa::{pkcs8::DecodePublicKey, signature::Verifier}; use crate::{ consts::BASE64_ENGINE, errors::{self, CustomResult}, pii::{self, EncryptionStrategy}, }; #[derive(Clone, Debug)] struct NonceSequence(u128); impl NonceSequence { /// Byte index at which sequence number starts in a 16-byte (128-bit) sequence. /// This byte index considers the big endian order used while encoding and decoding the nonce /// to/from a 128-bit unsigned integer. const SEQUENCE_NUMBER_START_INDEX: usize = 4; /// Generate a random nonce sequence. fn new() -> Result<Self, ring::error::Unspecified> { use ring::rand::{SecureRandom, SystemRandom}; let rng = SystemRandom::new(); // 96-bit sequence number, stored in a 128-bit unsigned integer in big-endian order let mut sequence_number = [0_u8; 128 / 8]; rng.fill(&mut sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..])?; let sequence_number = u128::from_be_bytes(sequence_number); Ok(Self(sequence_number)) } /// Returns the current nonce value as bytes. fn current(&self) -> [u8; aead::NONCE_LEN] { let mut nonce = [0_u8; aead::NONCE_LEN]; nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]); nonce } /// Constructs a nonce sequence from bytes fn from_bytes(bytes: [u8; aead::NONCE_LEN]) -> Self { let mut sequence_number = [0_u8; 128 / 8]; sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..].copy_from_slice(&bytes); let sequence_number = u128::from_be_bytes(sequence_number); Self(sequence_number) } } impl aead::NonceSequence for NonceSequence { fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> { let mut nonce = [0_u8; aead::NONCE_LEN]; nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]); // Increment sequence number self.0 = self.0.wrapping_add(1); // Return previous sequence number as bytes Ok(aead::Nonce::assume_unique_for_key(nonce)) } } /// Trait for cryptographically signing messages pub trait SignMessage { /// Takes in a secret and a message and returns the calculated signature as bytes fn sign_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Trait for cryptographically verifying a message against a signature pub trait VerifySignature { /// Takes in a secret, the signature and the message and verifies the message /// against the signature fn verify_signature( &self, _secret: &[u8], _signature: &[u8], _msg: &[u8], ) -> CustomResult<bool, errors::CryptoError>; } /// Trait for cryptographically encoding a message pub trait EncodeMessage { /// Takes in a secret and the message and encodes it, returning bytes fn encode_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Trait for cryptographically decoding a message pub trait DecodeMessage { /// Takes in a secret, an encoded messages and attempts to decode it, returning bytes fn decode_message( &self, _secret: &[u8], _msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError>; } /// Represents no cryptographic algorithm. /// Implements all crypto traits and acts like a Nop #[derive(Debug)] pub struct NoAlgorithm; impl SignMessage for NoAlgorithm { fn sign_message( &self, _secret: &[u8], _msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(Vec::new()) } } impl VerifySignature for NoAlgorithm { fn verify_signature( &self, _secret: &[u8], _signature: &[u8], _msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { Ok(true) } } impl EncodeMessage for NoAlgorithm { fn encode_message( &self, _secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(msg.to_vec()) } } impl DecodeMessage for NoAlgorithm { fn decode_message( &self, _secret: &[u8], msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError> { Ok(msg.expose()) } } /// Represents the HMAC-SHA-1 algorithm #[derive(Debug)] pub struct HmacSha1; impl SignMessage for HmacSha1 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha1 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Represents the HMAC-SHA-256 algorithm #[derive(Debug)] pub struct HmacSha256; impl SignMessage for HmacSha256 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA256, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha256 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA256, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Represents the HMAC-SHA-512 algorithm #[derive(Debug)] pub struct HmacSha512; impl SignMessage for HmacSha512 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA512, secret); Ok(hmac::sign(&key, msg).as_ref().to_vec()) } } impl VerifySignature for HmacSha512 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = hmac::Key::new(hmac::HMAC_SHA512, secret); Ok(hmac::verify(&key, msg, signature).is_ok()) } } /// Blake3 #[derive(Debug)] pub struct Blake3(String); impl Blake3 { /// Create a new instance of Blake3 with a key pub fn new(key: impl Into<String>) -> Self { Self(key.into()) } } impl SignMessage for Blake3 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let key = blake3::derive_key(&self.0, secret); let output = blake3::keyed_hash(&key, msg).as_bytes().to_vec(); Ok(output) } } impl VerifySignature for Blake3 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let key = blake3::derive_key(&self.0, secret); let output = blake3::keyed_hash(&key, msg); Ok(output.as_bytes() == signature) } } /// Represents the GCM-AES-256 algorithm #[derive(Debug)] pub struct GcmAes256; impl EncodeMessage for GcmAes256 { fn encode_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let nonce_sequence = NonceSequence::new().change_context(errors::CryptoError::EncodingFailed)?; let current_nonce = nonce_sequence.current(); let key = UnboundKey::new(&aead::AES_256_GCM, secret) .change_context(errors::CryptoError::EncodingFailed)?; let mut key = SealingKey::new(key, nonce_sequence); let mut in_out = msg.to_vec(); key.seal_in_place_append_tag(aead::Aad::empty(), &mut in_out) .change_context(errors::CryptoError::EncodingFailed)?; in_out.splice(0..0, current_nonce); Ok(in_out) } } impl DecodeMessage for GcmAes256 { fn decode_message( &self, secret: &[u8], msg: Secret<Vec<u8>, EncryptionStrategy>, ) -> CustomResult<Vec<u8>, errors::CryptoError> { let msg = msg.expose(); let key = UnboundKey::new(&aead::AES_256_GCM, secret) .change_context(errors::CryptoError::DecodingFailed)?; let nonce_sequence = NonceSequence::from_bytes( <[u8; aead::NONCE_LEN]>::try_from( msg.get(..aead::NONCE_LEN) .ok_or(errors::CryptoError::DecodingFailed) .attach_printable("Failed to read the nonce form the encrypted ciphertext")?, ) .change_context(errors::CryptoError::DecodingFailed)?, ); let mut key = OpeningKey::new(key, nonce_sequence); let mut binding = msg; let output = binding.as_mut_slice(); let result = key .open_within(aead::Aad::empty(), output, aead::NONCE_LEN..) .change_context(errors::CryptoError::DecodingFailed)?; Ok(result.to_vec()) } } /// Represents the ED25519 signature verification algorithm #[derive(Debug)] pub struct Ed25519; impl Ed25519 { /// ED25519 algorithm constants const ED25519_PUBLIC_KEY_LEN: usize = 32; const ED25519_SIGNATURE_LEN: usize = 64; /// Validates ED25519 inputs (public key and signature lengths) fn validate_inputs( public_key: &[u8], signature: &[u8], ) -> CustomResult<(), errors::CryptoError> { // Validate public key length if public_key.len() != Self::ED25519_PUBLIC_KEY_LEN { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 public key length: expected {} bytes, got {}", Self::ED25519_PUBLIC_KEY_LEN, public_key.len() )); } // Validate signature length if signature.len() != Self::ED25519_SIGNATURE_LEN { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 signature length: expected {} bytes, got {}", Self::ED25519_SIGNATURE_LEN, signature.len() )); } Ok(()) } } impl VerifySignature for Ed25519 { fn verify_signature( &self, public_key: &[u8], signature: &[u8], // ED25519 signature bytes (must be 64 bytes) msg: &[u8], // Message that was signed ) -> CustomResult<bool, errors::CryptoError> { // Validate inputs first Self::validate_inputs(public_key, signature)?; // Create unparsed public key let ring_public_key = ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key); // Perform verification match ring_public_key.verify(msg, signature) { Ok(()) => Ok(true), Err(_err) => { #[cfg(feature = "logs")] logger::error!("ED25519 signature verification failed: {:?}", _err); Err(errors::CryptoError::SignatureVerificationFailed) .attach_printable("ED25519 signature verification failed") } } } } impl SignMessage for Ed25519 { fn sign_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { if secret.len() != 32 { return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Invalid ED25519 private key length: expected 32 bytes, got {}", secret.len() )); } let key_pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(secret) .change_context(errors::CryptoError::MessageSigningFailed) .attach_printable("Failed to create ED25519 key pair from seed")?; let signature = key_pair.sign(msg); Ok(signature.as_ref().to_vec()) } } /// Secure Hash Algorithm 512 #[derive(Debug)] pub struct Sha512; /// Secure Hash Algorithm 256 #[derive(Debug)] pub struct Sha256; /// Trait for generating a digest for SHA pub trait GenerateDigest { /// takes a message and creates a digest for it fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError>; } impl GenerateDigest for Sha512 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = ring::digest::digest(&ring::digest::SHA512, message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Sha512 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let msg_str = std::str::from_utf8(msg) .change_context(errors::CryptoError::EncodingFailed)? .to_owned(); let hashed_digest = hex::encode( Self.generate_digest(msg_str.as_bytes()) .change_context(errors::CryptoError::SignatureVerificationFailed)?, ); let hashed_digest_into_bytes = hashed_digest.into_bytes(); Ok(hashed_digest_into_bytes == signature) } } /// MD5 hash function #[derive(Debug)] pub struct Md5; impl GenerateDigest for Md5 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = md5::compute(message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Md5 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let hashed_digest = Self .generate_digest(msg) .change_context(errors::CryptoError::SignatureVerificationFailed)?; Ok(hashed_digest == signature) } } impl GenerateDigest for Sha256 { fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> { let digest = ring::digest::digest(&ring::digest::SHA256, message); Ok(digest.as_ref().to_vec()) } } impl VerifySignature for Sha256 { fn verify_signature( &self, _secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { let hashed_digest = Self .generate_digest(msg) .change_context(errors::CryptoError::SignatureVerificationFailed)?; let hashed_digest_into_bytes = hashed_digest.as_slice(); Ok(hashed_digest_into_bytes == signature) } } /// Secure Hash Algorithm 256 with RSA public-key cryptosystem #[derive(Debug)] pub struct RsaSha256; impl VerifySignature for RsaSha256 { fn verify_signature( &self, secret: &[u8], signature: &[u8], msg: &[u8], ) -> CustomResult<bool, errors::CryptoError> { // create verifying key let decoded_public_key = BASE64_ENGINE .decode(secret) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("base64 decoding failed")?; let string_public_key = String::from_utf8(decoded_public_key) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("utf8 to string parsing failed")?; let rsa_public_key = rsa::RsaPublicKey::from_public_key_pem(&string_public_key) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("rsa public key transformation failed")?; let verifying_key = rsa::pkcs1v15::VerifyingKey::<rsa::sha2::Sha256>::new(rsa_public_key); // transfrom the signature let decoded_signature = BASE64_ENGINE .decode(signature) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("base64 decoding failed")?; let rsa_signature = rsa::pkcs1v15::Signature::try_from(&decoded_signature[..]) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("rsa signature transformation failed")?; // signature verification verifying_key .verify(msg, &rsa_signature) .map(|_| true) .change_context(errors::CryptoError::SignatureVerificationFailed) .attach_printable("signature verification step failed") } } /// TripleDesEde3 hash function #[derive(Debug)] #[cfg(feature = "crypto_openssl")] pub struct TripleDesEde3CBC { padding: common_enums::CryptoPadding, iv: Vec<u8>, } #[cfg(feature = "crypto_openssl")] impl TripleDesEde3CBC { const TRIPLE_DES_KEY_LENGTH: usize = 24; /// Initialization Vector (IV) length for TripleDesEde3 pub const TRIPLE_DES_IV_LENGTH: usize = 8; /// Constructor function to be used by the encryptor and decryptor to generate the data type pub fn new( padding: Option<common_enums::CryptoPadding>, iv: Vec<u8>, ) -> Result<Self, errors::CryptoError> { if iv.len() != Self::TRIPLE_DES_IV_LENGTH { Err(errors::CryptoError::InvalidIvLength)? }; let padding = padding.unwrap_or(common_enums::CryptoPadding::PKCS7); Ok(Self { iv, padding }) } } #[cfg(feature = "crypto_openssl")] impl EncodeMessage for TripleDesEde3CBC { fn encode_message( &self, secret: &[u8], msg: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { if secret.len() != Self::TRIPLE_DES_KEY_LENGTH { Err(errors::CryptoError::InvalidKeyLength)? } let mut buffer = msg.to_vec(); if let common_enums::CryptoPadding::ZeroPadding = self.padding { let pad_len = Self::TRIPLE_DES_IV_LENGTH - (buffer.len() % Self::TRIPLE_DES_IV_LENGTH); if pad_len != Self::TRIPLE_DES_IV_LENGTH { buffer.extend(vec![0u8; pad_len]); } }; let cipher = openssl::symm::Cipher::des_ede3_cbc(); openssl::symm::encrypt(cipher, secret, Some(&self.iv), &buffer) .change_context(errors::CryptoError::EncodingFailed) } } /// Generate a random string using a cryptographically secure pseudo-random number generator /// (CSPRNG). Typically used for generating (readable) keys and passwords. #[inline] pub fn generate_cryptographically_secure_random_string(length: usize) -> String { use rand::distributions::DistString; rand::distributions::Alphanumeric.sample_string(&mut rand::rngs::OsRng, length) } /// Generate an array of random bytes using a cryptographically secure pseudo-random number /// generator (CSPRNG). Typically used for generating keys. #[inline] pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; N] { use rand::RngCore; let mut bytes = [0; N]; rand::rngs::OsRng.fill_bytes(&mut bytes); bytes } /// A wrapper type to store the encrypted data for sensitive pii domain data types #[derive(Debug, Clone)] pub struct Encryptable<T: Clone> { inner: T, encrypted: Secret<Vec<u8>, EncryptionStrategy>, } impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> { /// constructor function to be used by the encryptor and decryptor to generate the data type pub fn new( masked_data: Secret<T, S>, encrypted_data: Secret<Vec<u8>, EncryptionStrategy>, ) -> Self { Self { inner: masked_data, encrypted: encrypted_data, } } } impl<T: Clone> Encryptable<T> { /// Get the inner data while consuming self #[inline] pub fn into_inner(self) -> T { self.inner } /// Get the reference to inner value #[inline] pub fn get_inner(&self) -> &T { &self.inner } /// Get the inner encrypted data while consuming self #[inline] pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> { self.encrypted } /// Deserialize inner value and return new Encryptable object pub fn deserialize_inner_value<U, F>( self, f: F, ) -> CustomResult<Encryptable<U>, errors::ParsingError> where F: FnOnce(T) -> CustomResult<U, errors::ParsingError>, U: Clone, { let inner = self.inner; let encrypted = self.encrypted; let inner = f(inner)?; Ok(Encryptable { inner, encrypted }) } /// consume self and modify the inner value pub fn map<U: Clone>(self, f: impl FnOnce(T) -> U) -> Encryptable<U> { let encrypted_data = self.encrypted; let masked_data = f(self.inner); Encryptable { inner: masked_data, encrypted: encrypted_data, } } } impl<T: Clone> Deref for Encryptable<Secret<T>> { type Target = Secret<T>; fn deref(&self) -> &Self::Target { &self.inner } } impl<T: Clone> masking::Serialize for Encryptable<T> where T: masking::Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.inner.serialize(serializer) } } impl<T: Clone> PartialEq for Encryptable<T> where T: PartialEq, { fn eq(&self, other: &Self) -> bool { self.inner.eq(&other.inner) } } /// Type alias for `Option<Encryptable<Secret<String>>>` pub type OptionalEncryptableSecretString = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `name` field pub type OptionalEncryptableName = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `email` field pub type OptionalEncryptableEmail = Option<Encryptable<Secret<String, pii::EmailStrategy>>>; /// Type alias for `Option<Encryptable<Secret<String>>>` used for `phone` field pub type OptionalEncryptablePhone = Option<Encryptable<Secret<String>>>; /// Type alias for `Option<Encryptable<Secret<serde_json::Value>>>` pub type OptionalEncryptableValue = Option<Encryptable<Secret<serde_json::Value>>>; /// Type alias for `Option<Secret<serde_json::Value>>` pub type OptionalSecretValue = Option<Secret<serde_json::Value>>; /// Type alias for `Encryptable<Secret<String>>` used for `name` field pub type EncryptableName = Encryptable<Secret<String>>; /// Type alias for `Encryptable<Secret<String>>` used for `email` field pub type EncryptableEmail = Encryptable<Secret<String, pii::EmailStrategy>>; /// Represents the RSA-PSS-SHA256 signing algorithm #[derive(Debug)] pub struct RsaPssSha256; impl SignMessage for RsaPssSha256 { fn sign_message( &self, private_key_pem_bytes: &[u8], msg_to_sign: &[u8], ) -> CustomResult<Vec<u8>, errors::CryptoError> { let parsed_pem = pem::parse(private_key_pem_bytes) .change_context(errors::CryptoError::EncodingFailed) .attach_printable("Failed to parse PEM string")?; let key_pair = match parsed_pem.tag() { "PRIVATE KEY" => RsaKeyPair::from_pkcs8(parsed_pem.contents()) .change_context(errors::CryptoError::InvalidKeyLength) .attach_printable("Failed to parse PKCS#8 DER with ring"), "RSA PRIVATE KEY" => RsaKeyPair::from_der(parsed_pem.contents()) .change_context(errors::CryptoError::InvalidKeyLength) .attach_printable("Failed to parse PKCS#1 DER (using from_der) with ring"), tag => Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!( "Unexpected PEM tag: {tag}. Expected 'PRIVATE KEY' or 'RSA PRIVATE KEY'", )), }?; let rng = ring_rand::SystemRandom::new(); let signature_len = key_pair.public().modulus_len(); let mut signature_bytes = vec![0; signature_len]; key_pair .sign(&RSA_PSS_SHA256, &rng, msg_to_sign, &mut signature_bytes) .change_context(errors::CryptoError::EncodingFailed) .attach_printable("Failed to sign data with ring")?; Ok(signature_bytes) } } #[cfg(test)] mod crypto_tests { #![allow(clippy::expect_used)] use super::{DecodeMessage, EncodeMessage, SignMessage, VerifySignature}; use crate::crypto::GenerateDigest; #[test] fn test_hmac_sha256_sign_message() { let message = r#"{"type":"payment_intent"}"#.as_bytes(); let secret = "hmac_secret_1234".as_bytes(); let right_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e") .expect("Right signature decoding"); let signature = super::HmacSha256 .sign_message(secret, message) .expect("Signature"); assert_eq!(signature, right_signature); } #[test] fn test_hmac_sha256_verify_signature() { let right_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e") .expect("Right signature decoding"); let wrong_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f") .expect("Wrong signature decoding"); let secret = "hmac_secret_1234".as_bytes(); let data = r#"{"type":"payment_intent"}"#.as_bytes(); let right_verified = super::HmacSha256 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::HmacSha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_sha256_verify_signature() { let right_signature = hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddba") .expect("Right signature decoding"); let wrong_signature = hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddbb") .expect("Wrong signature decoding"); let secret = "".as_bytes(); let data = r#"AJHFH9349JASFJHADJ9834115USD2020-11-13.13:22:34711000000021406655APPROVED12345product_id"#.as_bytes(); let right_verified = super::Sha256 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::Sha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_hmac_sha512_sign_message() { let message = r#"{"type":"payment_intent"}"#.as_bytes(); let secret = "hmac_secret_1234".as_bytes(); let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f") .expect("signature decoding"); let signature = super::HmacSha512 .sign_message(secret, message) .expect("Signature"); assert_eq!(signature, right_signature); } #[test] fn test_hmac_sha512_verify_signature() { let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f") .expect("signature decoding"); let wrong_signature = hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f") .expect("Wrong signature decoding"); let secret = "hmac_secret_1234".as_bytes(); let data = r#"{"type":"payment_intent"}"#.as_bytes(); let right_verified = super::HmacSha512 .verify_signature(secret, &right_signature, data) .expect("Right signature verification result"); assert!(right_verified); let wrong_verified = super::HmacSha256 .verify_signature(secret, &wrong_signature, data) .expect("Wrong signature verification result"); assert!(!wrong_verified); } #[test] fn test_gcm_aes_256_encode_message() { let message = r#"{"type":"PAYMENT"}"#.as_bytes(); let secret = hex::decode("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f") .expect("Secret decoding"); let algorithm = super::GcmAes256; let encoded_message = algorithm .encode_message(&secret, message) .expect("Encoded message and tag"); assert_eq!( algorithm .decode_message(&secret, encoded_message.into()) .expect("Decode Failed"), message ); } #[test] fn test_gcm_aes_256_decode_message() { // Inputs taken from AES GCM test vectors provided by NIST // https://github.com/briansmith/ring/blob/95948b3977013aed16db92ae32e6b8384496a740/tests/aead_aes_256_gcm_tests.txt#L447-L452 let right_secret = hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308") .expect("Secret decoding"); let wrong_secret = hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308309") .expect("Secret decoding"); let message =
crates/common_utils/src/crypto.rs#chunk0
common_utils
chunk
null
null
null
8,187
null
null
null
null
null
null
null
// File: crates/router/src/core/payments/operations.rs // Module: router // Public structs: 4 #[cfg(feature = "v1")] pub mod payment_approve; #[cfg(feature = "v1")] pub mod payment_cancel; #[cfg(feature = "v1")] pub mod payment_cancel_post_capture; #[cfg(feature = "v1")] pub mod payment_capture; #[cfg(feature = "v1")] pub mod payment_complete_authorize; #[cfg(feature = "v1")] pub mod payment_confirm; #[cfg(feature = "v1")] pub mod payment_create; #[cfg(feature = "v1")] pub mod payment_post_session_tokens; #[cfg(feature = "v1")] pub mod payment_reject; pub mod payment_response; #[cfg(feature = "v1")] pub mod payment_session; #[cfg(feature = "v2")] pub mod payment_session_intent; #[cfg(feature = "v1")] pub mod payment_start; #[cfg(feature = "v1")] pub mod payment_status; #[cfg(feature = "v1")] pub mod payment_update; #[cfg(feature = "v1")] pub mod payment_update_metadata; #[cfg(feature = "v1")] pub mod payments_incremental_authorization; #[cfg(feature = "v1")] pub mod tax_calculation; #[cfg(feature = "v2")] pub mod payment_attempt_list; #[cfg(feature = "v2")] pub mod payment_attempt_record; #[cfg(feature = "v2")] pub mod payment_confirm_intent; #[cfg(feature = "v2")] pub mod payment_create_intent; #[cfg(feature = "v2")] pub mod payment_get_intent; #[cfg(feature = "v2")] pub mod payment_update_intent; #[cfg(feature = "v2")] pub mod proxy_payments_intent; #[cfg(feature = "v2")] pub mod external_vault_proxy_payment_intent; #[cfg(feature = "v2")] pub mod payment_get; #[cfg(feature = "v2")] pub mod payment_capture_v2; #[cfg(feature = "v2")] pub mod payment_cancel_v2; use api_models::enums::FrmSuggestion; #[cfg(all(feature = "v1", feature = "dynamic_routing"))] use api_models::routing::RoutableConnectorChoice; use async_trait::async_trait; use error_stack::{report, ResultExt}; use router_env::{instrument, tracing}; #[cfg(feature = "v2")] pub use self::payment_attempt_list::PaymentGetListAttempts; #[cfg(feature = "v2")] pub use self::payment_get::PaymentGet; #[cfg(feature = "v2")] pub use self::payment_get_intent::PaymentGetIntent; pub use self::payment_response::PaymentResponse; #[cfg(feature = "v2")] pub use self::payment_update_intent::PaymentUpdateIntent; #[cfg(feature = "v1")] pub use self::{ payment_approve::PaymentApprove, payment_cancel::PaymentCancel, payment_cancel_post_capture::PaymentCancelPostCapture, payment_capture::PaymentCapture, payment_confirm::PaymentConfirm, payment_create::PaymentCreate, payment_post_session_tokens::PaymentPostSessionTokens, payment_reject::PaymentReject, payment_session::PaymentSession, payment_start::PaymentStart, payment_status::PaymentStatus, payment_update::PaymentUpdate, payment_update_metadata::PaymentUpdateMetadata, payments_incremental_authorization::PaymentIncrementalAuthorization, tax_calculation::PaymentSessionUpdate, }; #[cfg(feature = "v2")] pub use self::{ payment_confirm_intent::PaymentIntentConfirm, payment_create_intent::PaymentIntentCreate, payment_session_intent::PaymentSessionIntent, }; use super::{helpers, CustomerDetails, OperationSessionGetters, OperationSessionSetters}; #[cfg(feature = "v2")] use crate::core::payments; use crate::{ core::errors::{self, CustomResult, RouterResult}, routes::{app::ReqState, SessionState}, services, types::{ self, api::{self, ConnectorCallType}, domain, storage::{self, enums}, PaymentsResponseData, }, }; pub type BoxedOperation<'a, F, T, D> = Box<dyn Operation<F, T, Data = D> + Send + Sync + 'a>; pub trait Operation<F: Clone, T>: Send + std::fmt::Debug { type Data; fn to_validate_request( &self, ) -> RouterResult<&(dyn ValidateRequest<F, T, Self::Data> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("validate request interface not found for {self:?}")) } fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("get tracker interface not found for {self:?}")) } fn to_domain(&self) -> RouterResult<&dyn Domain<F, T, Self::Data>> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("domain interface not found for {self:?}")) } fn to_update_tracker( &self, ) -> RouterResult<&(dyn UpdateTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| format!("update tracker interface not found for {self:?}")) } fn to_post_update_tracker( &self, ) -> RouterResult<&(dyn PostUpdateTracker<F, Self::Data, T> + Send + Sync)> { Err(report!(errors::ApiErrorResponse::InternalServerError)).attach_printable_lazy(|| { format!("post connector update tracker not found for {self:?}") }) } } #[cfg(feature = "v1")] #[derive(Clone)] pub struct ValidateResult { pub merchant_id: common_utils::id_type::MerchantId, pub payment_id: api::PaymentIdType, pub storage_scheme: enums::MerchantStorageScheme, pub requeue: bool, } #[cfg(feature = "v2")] #[derive(Clone)] pub struct ValidateResult { pub merchant_id: common_utils::id_type::MerchantId, pub storage_scheme: enums::MerchantStorageScheme, pub requeue: bool, } #[cfg(feature = "v1")] #[allow(clippy::type_complexity)] pub trait ValidateRequest<F, R, D> { fn validate_request<'b>( &'b self, request: &R, merchant_context: &domain::MerchantContext, ) -> RouterResult<(BoxedOperation<'b, F, R, D>, ValidateResult)>; } #[cfg(feature = "v2")] pub trait ValidateRequest<F, R, D> { fn validate_request( &self, request: &R, merchant_context: &domain::MerchantContext, ) -> RouterResult<ValidateResult>; } #[cfg(feature = "v2")] pub struct GetTrackerResponse<D> { pub payment_data: D, } #[cfg(feature = "v1")] pub struct GetTrackerResponse<'a, F: Clone, R, D> { pub operation: BoxedOperation<'a, F, R, D>, pub customer_details: Option<CustomerDetails>, pub payment_data: D, pub business_profile: domain::Profile, pub mandate_type: Option<api::MandateTransactionType>, } /// This trait is used to fetch / create all the tracker related information for a payment /// This functions returns the session data that is used by subsequent functions #[async_trait] pub trait GetTracker<F: Clone, D, R>: Send { #[cfg(feature = "v1")] #[allow(clippy::too_many_arguments)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &R, merchant_context: &domain::MerchantContext, auth_flow: services::AuthFlow, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<GetTrackerResponse<'a, F, R, D>>; #[cfg(feature = "v2")] #[allow(clippy::too_many_arguments)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &common_utils::id_type::GlobalPaymentId, request: &R, merchant_context: &domain::MerchantContext, profile: &domain::Profile, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<GetTrackerResponse<D>>; async fn validate_request_with_state( &self, _state: &SessionState, _request: &R, _payment_data: &mut D, _business_profile: &domain::Profile, ) -> RouterResult<()> { Ok(()) } } #[async_trait] pub trait Domain<F: Clone, R, D>: Send + Sync { #[cfg(feature = "v1")] /// This will fetch customer details, (this operation is flow specific) async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>; #[cfg(feature = "v2")] /// This will fetch customer details, (this operation is flow specific) async fn get_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>; #[cfg(feature = "v2")] /// This will run the decision manager for the payment async fn run_decision_manager<'a>( &'a self, state: &SessionState, payment_data: &mut D, business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn make_pm_data<'a>( &'a self, state: &'a SessionState, payment_data: &mut D, storage_scheme: enums::MerchantStorageScheme, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, R, D>, Option<domain::PaymentMethodData>, Option<String>, )>; async fn add_task_to_process_tracker<'a>( &'a self, _db: &'a SessionState, _payment_attempt: &storage::PaymentAttempt, _requeue: bool, _schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[cfg(feature = "v1")] async fn get_connector<'a>( &'a self, merchant_context: &domain::MerchantContext, state: &SessionState, request: &R, payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse>; #[cfg(feature = "v2")] async fn get_connector_from_request<'a>( &'a self, state: &SessionState, request: &R, payment_data: &mut D, ) -> CustomResult<api::ConnectorData, errors::ApiErrorResponse> { Err(report!(errors::ApiErrorResponse::InternalServerError)) .attach_printable_lazy(|| "get connector for tunnel not implemented".to_string()) } #[cfg(feature = "v2")] async fn perform_routing<'a>( &'a self, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, state: &SessionState, // TODO: do not take the whole payment data here payment_data: &mut D, ) -> CustomResult<ConnectorCallType, errors::ApiErrorResponse>; async fn populate_payment_data<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_context: &domain::MerchantContext, _business_profile: &domain::Profile, _connector_data: &api::ConnectorData, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn call_external_three_ds_authentication_if_eligible<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _should_continue_confirm_transaction: &mut bool, _connector_call_type: &ConnectorCallType, _business_profile: &domain::Profile, _key_store: &domain::MerchantKeyStore, _mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn call_unified_authentication_service_if_eligible<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _should_continue_confirm_transaction: &mut bool, _connector_call_type: &ConnectorCallType, _business_profile: &domain::Profile, _key_store: &domain::MerchantKeyStore, _mandate_type: Option<api_models::payments::MandateTransactionType>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[allow(clippy::too_many_arguments)] async fn payments_dynamic_tax_calculation<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _connector_call_type: &ConnectorCallType, _business_profile: &domain::Profile, _merchant_context: &domain::MerchantContext, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } async fn store_extended_card_info_temporarily<'a>( &'a self, _state: &SessionState, _payment_id: &common_utils::id_type::PaymentId, _business_profile: &domain::Profile, _payment_method_data: Option<&domain::PaymentMethodData>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } #[cfg(feature = "v2")] async fn create_or_fetch_payment_method<'a>( &'a self, state: &SessionState, merchant_context: &domain::MerchantContext, business_profile: &domain::Profile, payment_data: &mut D, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } // does not propagate error to not affect the payment flow // must add debugger in case of internal error #[cfg(feature = "v2")] async fn update_payment_method<'a>( &'a self, state: &SessionState, merchant_context: &domain::MerchantContext, payment_data: &mut D, ) { } /// This function is used to apply the 3DS authentication strategy async fn apply_three_ds_authentication_strategy<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } /// Get connector tokenization action #[cfg(feature = "v2")] async fn get_connector_tokenization_action<'a>( &'a self, _state: &SessionState, _payment_data: &D, ) -> RouterResult<(payments::TokenizationAction)> { Ok(payments::TokenizationAction::SkipConnectorTokenization) } // #[cfg(feature = "v2")] // async fn call_connector<'a, RouterDataReq>( // &'a self, // _state: &SessionState, // _req_state: ReqState, // _merchant_context: &domain::MerchantContext, // _business_profile: &domain::Profile, // _payment_method_data: Option<&domain::PaymentMethodData>, // _connector: api::ConnectorData, // _customer: &Option<domain::Customer>, // _payment_data: &mut D, // _call_connector_action: common_enums::CallConnectorAction, // ) -> CustomResult< // hyperswitch_domain_models::router_data::RouterData<F, RouterDataReq, PaymentsResponseData>, // errors::ApiErrorResponse, // > { // // TODO: raise an error here // todo!(); // } } #[async_trait] #[allow(clippy::too_many_arguments)] pub trait UpdateTracker<F, D, Req>: Send { /// Update the tracker information with the new data from request or calculated by the operations performed after get trackers /// This will persist the SessionData ( PaymentData ) in the database /// /// In case we are calling a processor / connector, we persist all the data in the database and then call the connector async fn update_trackers<'b>( &'b self, db: &'b SessionState, req_state: ReqState, payment_data: D, customer: Option<domain::Customer>, storage_scheme: enums::MerchantStorageScheme, updated_customer: Option<storage::CustomerUpdate>, mechant_key_store: &domain::MerchantKeyStore, frm_suggestion: Option<FrmSuggestion>, header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(BoxedOperation<'b, F, Req, D>, D)> where F: 'b + Send; } #[cfg(feature = "v2")] #[async_trait] #[allow(clippy::too_many_arguments)] pub trait CallConnector<F, D, RouterDReq: Send>: Send { async fn call_connector<'b>( &'b self, db: &'b SessionState, req_state: ReqState, payment_data: D, key_store: &domain::MerchantKeyStore, call_connector_action: common_enums::CallConnectorAction, connector_data: api::ConnectorData, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<types::RouterData<F, RouterDReq, PaymentsResponseData>> where F: 'b + Send + Sync, D: super::flows::ConstructFlowSpecificData<F, RouterDReq, PaymentsResponseData>, types::RouterData<F, RouterDReq, PaymentsResponseData>: super::flows::Feature<F, RouterDReq> + Send; } #[async_trait] #[allow(clippy::too_many_arguments)] pub trait PostUpdateTracker<F, D, R: Send>: Send { /// Update the tracker information with the response from the connector /// The response from routerdata is used to update paymentdata and also persist this in the database #[cfg(feature = "v1")] async fn update_tracker<'b>( &'b self, db: &'b SessionState, payment_data: D, response: types::RouterData<F, R, PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, locale: &Option<String>, #[cfg(feature = "dynamic_routing")] routable_connector: Vec<RoutableConnectorChoice>, #[cfg(feature = "dynamic_routing")] business_profile: &domain::Profile, ) -> RouterResult<D> where F: 'b + Send + Sync; #[cfg(feature = "v2")] async fn update_tracker<'b>( &'b self, db: &'b SessionState, payment_data: D, response: types::RouterData<F, R, PaymentsResponseData>, key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<D> where F: 'b + Send + Sync, types::RouterData<F, R, PaymentsResponseData>: hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, R, D>; async fn save_pm_and_mandate<'b>( &self, _state: &SessionState, _resp: &types::RouterData<F, R, PaymentsResponseData>, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, _business_profile: &domain::Profile, ) -> CustomResult<(), errors::ApiErrorResponse> where F: 'b + Clone + Send + Sync, { Ok(()) } } #[cfg(feature = "v1")] #[async_trait] impl< D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRetrieveRequest, Data = D>, > Domain<F, api::PaymentsRetrieveRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsRetrieveRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { // This function is to retrieve customer details. If the customer is deleted, it returns // customer details that contains the fields as Redacted db.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsRetrieveRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCaptureRequest, Data = D>> Domain<F, api::PaymentsCaptureRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsCaptureRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { db.find_customer_optional_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { todo!() } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsCaptureRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsCancelRequest, Data = D>> Domain<F, api::PaymentsCancelRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsCancelRequest, Data = D>, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send, { #[instrument(skip_all)] #[cfg(feature = "v1")] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut D, _request: Option<CustomerDetails>, merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { let db = &*state.store; let customer = match payment_data.get_payment_intent().customer_id.as_ref() { None => None, Some(customer_id) => { db.find_customer_optional_by_customer_id_merchant_id( &state.into(), customer_id, &merchant_key_store.merchant_id, merchant_key_store, storage_scheme, ) .await? } }; if let Some(email) = customer.as_ref().and_then(|inner| inner.email.clone()) { payment_data.set_email_if_not_present(email.into()); } Ok((Box::new(self), customer)) } #[instrument(skip_all)] #[cfg(feature = "v2")] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { todo!() } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsCancelRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsCancelRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[cfg(feature = "v1")] #[async_trait] impl<D, F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsRejectRequest, Data = D>> Domain<F, api::PaymentsRejectRequest, D> for Op where for<'a> &'a Op: Operation<F, api::PaymentsRejectRequest, Data = D>, { #[cfg(feature = "v1")] #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _request: Option<CustomerDetails>, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[cfg(feature = "v2")] #[instrument(skip_all)] async fn get_customer_details<'a>( &'a self, _state: &SessionState, _payment_data: &mut D, _merchant_key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult< ( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::Customer>, ), errors::StorageError, > { Ok((Box::new(self), None)) } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, _state: &'a SessionState, _payment_data: &mut D, _storage_scheme: enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( BoxedOperation<'a, F, api::PaymentsRejectRequest, D>, Option<domain::PaymentMethodData>, Option<String>, )> { Ok((Box::new(self), None, None)) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, _request: &api::PaymentsRejectRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { helpers::get_connector_default(state, None).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut D, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } /// Validate if a particular operation can be performed for the given intent status pub trait ValidateStatusForOperation { fn validate_status_for_operation( &self, intent_status: common_enums::IntentStatus, ) -> Result<(), errors::ApiErrorResponse>; } /// Should the connector be called for this operation pub trait ShouldCallConnector { fn should_call_connector( &self, intent_status: common_enums::IntentStatus, force_sync: Option<bool>, ) -> bool; }
crates/router/src/core/payments/operations.rs
router
full_file
null
null
null
7,584
null
null
null
null
null
null
null
// Struct: NomupayErrorResponse // File: crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct NomupayErrorResponse
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
hyperswitch_connectors
struct_definition
NomupayErrorResponse
0
[]
51
null
null
null
null
null
null
null
// Struct: BusinessGenericLinkConfig // File: crates/diesel_models/src/business_profile.rs // Module: diesel_models // Implementations: 0 pub struct BusinessGenericLinkConfig
crates/diesel_models/src/business_profile.rs
diesel_models
struct_definition
BusinessGenericLinkConfig
0
[]
39
null
null
null
null
null
null
null
// Struct: GetRoleRequest // File: crates/api_models/src/user_role/role.rs // Module: api_models // Implementations: 0 pub struct GetRoleRequest
crates/api_models/src/user_role/role.rs
api_models
struct_definition
GetRoleRequest
0
[]
38
null
null
null
null
null
null
null
// Implementation: impl Capturable for for PaymentsSyncData // File: crates/router/src/types.rs // Module: router // Methods: 4 total (0 public) impl Capturable for for PaymentsSyncData
crates/router/src/types.rs
router
impl_block
null
null
null
44
null
PaymentsSyncData
Capturable for
4
0
null
null
// Implementation: impl api::PaymentToken for for Globalpay // File: crates/hyperswitch_connectors/src/connectors/globalpay.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentToken for for Globalpay
crates/hyperswitch_connectors/src/connectors/globalpay.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Globalpay
api::PaymentToken for
0
0
null
null
// Implementation: impl StaticRoutingAlgorithm // File: crates/api_models/src/routing.rs // Module: api_models // Methods: 1 total (1 public) impl StaticRoutingAlgorithm
crates/api_models/src/routing.rs
api_models
impl_block
null
null
null
39
null
StaticRoutingAlgorithm
null
1
1
null
null
// Struct: FortePaymentsRequest // File: crates/hyperswitch_connectors/src/connectors/forte/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct FortePaymentsRequest
crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
hyperswitch_connectors
struct_definition
FortePaymentsRequest
0
[]
50
null
null
null
null
null
null
null
// Function: get_decoupled_authentication_type // File: crates/hyperswitch_domain_models/src/router_request_types/authentication.rs // Module: hyperswitch_domain_models pub fn get_decoupled_authentication_type(&self) -> common_enums::DecoupledAuthenticationType
crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
hyperswitch_domain_models
function_signature
null
null
null
56
get_decoupled_authentication_type
null
null
null
null
null
null
// Struct: ElavonPaymentsResponse // File: crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ElavonPaymentsResponse
crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs
hyperswitch_connectors
struct_definition
ElavonPaymentsResponse
0
[]
52
null
null
null
null
null
null
null
// Struct: BokuPsyncRequest // File: crates/hyperswitch_connectors/src/connectors/boku/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BokuPsyncRequest
crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
hyperswitch_connectors
struct_definition
BokuPsyncRequest
0
[]
51
null
null
null
null
null
null
null
// Struct: NovalnetWebhookNotificationResponse // File: crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct NovalnetWebhookNotificationResponse
crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
hyperswitch_connectors
struct_definition
NovalnetWebhookNotificationResponse
0
[]
56
null
null
null
null
null
null
null
// Struct: ApplePayWalletData // File: crates/hyperswitch_domain_models/src/payment_method_data.rs // Module: hyperswitch_domain_models // Implementations: 1 pub struct ApplePayWalletData
crates/hyperswitch_domain_models/src/payment_method_data.rs
hyperswitch_domain_models
struct_definition
ApplePayWalletData
1
[]
45
null
null
null
null
null
null
null
// Function: get_id // File: crates/hyperswitch_domain_models/src/merchant_account.rs // Module: hyperswitch_domain_models // Documentation: Get the unique identifier of MerchantAccount pub fn get_id(&self) -> &common_utils::id_type::MerchantId
crates/hyperswitch_domain_models/src/merchant_account.rs
hyperswitch_domain_models
function_signature
null
null
null
58
get_id
null
null
null
null
null
null
// Function: get_expired_page // File: crates/router/src/routes/dummy_connector/utils.rs // Module: router pub fn get_expired_page(dummy_connector_conf: &settings::DummyConnector) -> String
crates/router/src/routes/dummy_connector/utils.rs
router
function_signature
null
null
null
42
get_expired_page
null
null
null
null
null
null
// Struct: PaymentsMandateReferenceRecord // File: crates/hyperswitch_domain_models/src/mandates.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct PaymentsMandateReferenceRecord
crates/hyperswitch_domain_models/src/mandates.rs
hyperswitch_domain_models
struct_definition
PaymentsMandateReferenceRecord
0
[]
49
null
null
null
null
null
null
null
// Struct: DebtorInformation // File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct DebtorInformation
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
struct_definition
DebtorInformation
0
[]
48
null
null
null
null
null
null
null
// Struct: Blocklist // File: crates/router/src/routes/app.rs // Module: router // Implementations: 1 pub struct Blocklist
crates/router/src/routes/app.rs
router
struct_definition
Blocklist
1
[]
32
null
null
null
null
null
null
null
&self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let aci_notification: aci::AciWebhookNotification = serde_json::from_slice(request.body) .change_context(errors::ConnectorError::WebhookResourceObjectNotFound) .attach_printable("Failed to deserialize ACI webhook notification for resource object (expected decrypted payload)")?; match aci_notification.event_type { aci::AciWebhookEventType::Payment => { let payment_payload: aci::AciPaymentWebhookPayload = serde_json::from_value(aci_notification.payload) .change_context(errors::ConnectorError::WebhookResourceObjectNotFound) .attach_printable("Failed to deserialize ACI payment webhook payload")?; Ok(Box::new(payment_payload)) } } } } static ACI_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::Manual, ]; let supported_card_networks = vec![ common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, common_enums::CardNetwork::AmericanExpress, common_enums::CardNetwork::JCB, common_enums::CardNetwork::DinersClub, common_enums::CardNetwork::Discover, common_enums::CardNetwork::UnionPay, common_enums::CardNetwork::Maestro, ]; let mut aci_supported_payment_methods = SupportedPaymentMethods::new(); aci_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::MbWay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::Wallet, enums::PaymentMethodType::AliPay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_networks.clone(), } }), ), }, ); aci_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::Supported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::Supported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_networks.clone(), } }), ), }, ); aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Eps, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Eft, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Ideal, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Giropay, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Sofort, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Interac, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Przelewy24, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::BankRedirect, enums::PaymentMethodType::Trustly, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods.add( enums::PaymentMethod::PayLater, enums::PaymentMethodType::Klarna, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); aci_supported_payment_methods }); static ACI_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "ACI", description: "ACI Payments delivers secure, real-time electronic payment solutions for businesses, banks, and governments, enabling seamless transactions across channels.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Beta, }; static ACI_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Aci { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&ACI_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*ACI_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&ACI_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/aci.rs#chunk1
hyperswitch_connectors
chunk
null
null
null
1,669
null
null
null
null
null
null
null
data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: PaypalAuthResponse = res.response .parse_struct("paypal PaypalAuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; match response { PaypalAuthResponse::PaypalOrdersResponse(response) => { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } PaypalAuthResponse::PaypalRedirectResponse(response) => { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } PaypalAuthResponse::PaypalThreeDsResponse(response) => { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.get_order_error_response(res, event_builder) } } impl PaymentIncrementalAuthorization for Paypal {} impl ConnectorIntegration< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, > for Paypal { fn get_headers( &self, req: &PaymentsIncrementalAuthorizationRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_http_method(&self) -> Method { Method::Post } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsIncrementalAuthorizationRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; let incremental_authorization_id = paypal_meta.incremental_authorization_id.ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Missing incremental authorization id".to_string(), ), )?; Ok(format!( "{}v2/payments/authorizations/{}/reauthorize", self.base_url(connectors), incremental_authorization_id )) } fn get_request_body( &self, req: &PaymentsIncrementalAuthorizationRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, MinorUnit::new(req.request.total_amount), req.request.currency, )?; let connector_router_data = paypal::PaypalRouterData::try_from((amount, None, None, None, req))?; let connector_req = paypal::PaypalIncrementalAuthRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsIncrementalAuthorizationRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&IncrementalAuthorizationType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(IncrementalAuthorizationType::get_headers( self, req, connectors, )?) .set_body(IncrementalAuthorizationType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsIncrementalAuthorizationRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult< RouterData< IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData, >, errors::ConnectorError, > { let response: PaypalIncrementalAuthResponse = res .response .parse_struct("Paypal IncrementalAuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) .change_context(errors::ConnectorError::ResponseHandlingFailed) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl api::PaymentsPreProcessing for Paypal {} impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Paypal { fn get_headers( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_url( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let order_id = req .request .connector_transaction_id .to_owned() .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?; Ok(format!( "{}v2/checkout/orders/{}?fields=payment_source", self.base_url(connectors), order_id, )) } fn build_request( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsPreProcessingType::get_url(self, req, connectors)?) .attach_default_headers() .headers(PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: paypal::PaypalPreProcessingResponse = res .response .parse_struct("paypal PaypalPreProcessingResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); match response { // if card supports 3DS check for liability paypal::PaypalPreProcessingResponse::PaypalLiabilityResponse(liability_response) => { // permutation for status to continue payment match ( liability_response .payment_source .card .authentication_result .three_d_secure .enrollment_status .as_ref(), liability_response .payment_source .card .authentication_result .three_d_secure .authentication_status .as_ref(), liability_response .payment_source .card .authentication_result .liability_shift .clone(), ) { ( Some(paypal::EnrollmentStatus::Ready), Some(paypal::AuthenticationStatus::Success), paypal::LiabilityShift::Possible, ) | ( Some(paypal::EnrollmentStatus::Ready), Some(paypal::AuthenticationStatus::Attempted), paypal::LiabilityShift::Possible, ) | (Some(paypal::EnrollmentStatus::NotReady), None, paypal::LiabilityShift::No) | (Some(paypal::EnrollmentStatus::Unavailable), None, paypal::LiabilityShift::No) | (Some(paypal::EnrollmentStatus::Bypassed), None, paypal::LiabilityShift::No) => { Ok(PaymentsPreProcessingRouterData { status: enums::AttemptStatus::AuthenticationSuccessful, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..data.clone() }) } _ => Ok(PaymentsPreProcessingRouterData { response: Err(ErrorResponse { attempt_status: Some(enums::AttemptStatus::Failure), code: NO_ERROR_CODE.to_string(), message: NO_ERROR_MESSAGE.to_string(), connector_transaction_id: None, reason: Some(format!("{} Connector Responsded with LiabilityShift: {:?}, EnrollmentStatus: {:?}, and AuthenticationStatus: {:?}", constants::CANNOT_CONTINUE_AUTH, liability_response .payment_source .card .authentication_result .liability_shift, liability_response .payment_source .card .authentication_result .three_d_secure .enrollment_status .unwrap_or(paypal::EnrollmentStatus::Null), liability_response .payment_source .card .authentication_result .three_d_secure .authentication_status .unwrap_or(paypal::AuthenticationStatus::Null), )), status_code: res.status_code, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..data.clone() }), } } // if card does not supports 3DS check for liability paypal::PaypalPreProcessingResponse::PaypalNonLiabilityResponse(_) => { Ok(PaymentsPreProcessingRouterData { status: enums::AttemptStatus::AuthenticationSuccessful, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }), ..data.clone() }) } } } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> for Paypal { fn get_headers( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let complete_authorize_url = if req.request.is_auto_capture()? { "capture".to_string() } else { "authorize".to_string() }; Ok(format!( "{}v2/checkout/orders/{}/{complete_authorize_url}", self.base_url(connectors), req.request .connector_transaction_id .clone() .ok_or(errors::ConnectorError::MissingConnectorTransactionID)? )) } fn build_request( &self, req: &PaymentsCompleteAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCompleteAuthorizeType::get_url( self, req, connectors, )?) .headers(PaymentsCompleteAuthorizeType::get_headers( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCompleteAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: paypal::PaypalOrdersResponse = res .response .parse_struct("paypal PaypalOrdersResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Paypal { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; match req.payment_method { enums::PaymentMethod::Wallet | enums::PaymentMethod::BankRedirect => Ok(format!( "{}v2/checkout/orders/{}", self.base_url(connectors), req.request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::MissingConnectorTransactionID)? )), _ => { let psync_url = match paypal_meta.psync_flow { transformers::PaypalPaymentIntent::Authorize => { let authorize_id = paypal_meta.authorize_id.ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Missing Authorize id".to_string(), ), )?; format!("v2/payments/authorizations/{authorize_id}") } transformers::PaypalPaymentIntent::Capture => { let capture_id = paypal_meta.capture_id.ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Missing Capture id".to_string(), ), )?; format!("v2/payments/captures/{capture_id}") } // only set when payment is done through card 3DS //because no authorize or capture id is generated during payment authorize call for card 3DS transformers::PaypalPaymentIntent::Authenticate => { format!( "v2/checkout/orders/{}", req.request .connector_transaction_id .get_connector_transaction_id() .change_context( errors::ConnectorError::MissingConnectorTransactionID )? ) } }; Ok(format!("{}{psync_url}", self.base_url(connectors))) } } } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&PaymentsSyncType::get_url(self, req, connectors)?) .headers(PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: paypal::PaypalSyncResponse = res .response .parse_struct("paypal SyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::foreign_try_from(( ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }, data.request.payment_experience, )) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Paypal { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; let authorize_id = paypal_meta.authorize_id.ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Missing Authorize id".to_string(), ), )?; Ok(format!( "{}v2/payments/authorizations/{}/capture", self.base_url(connectors), authorize_id )) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount_to_capture = connector_utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = paypal::PaypalRouterData::try_from((amount_to_capture, None, None, None, req))?; let connector_req = paypal::PaypalPaymentsCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&PaymentsCaptureType::get_url(self, req, connectors)?) .headers(PaymentsCaptureType::get_headers(self, req, connectors)?) .set_body(PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: paypal::PaypalCaptureResponse = res .response .parse_struct("Paypal PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paypal { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_meta.clone())?; let authorize_id = paypal_meta.authorize_id.ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Missing Authorize id".to_string(), ), )?; Ok(format!( "{}v2/payments/authorizations/{}/void", self.base_url(connectors), authorize_id, )) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&PaymentsVoidType::get_url(self, req, connectors)?) .headers(PaymentsVoidType::get_headers(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: paypal::PaypalPaymentsCancelResponse = res .response .parse_struct("PaymentCancelResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paypal { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let paypal_meta: PaypalMeta = to_connector_meta(req.request.connector_metadata.clone())?; let capture_id = paypal_meta.capture_id.ok_or( errors::ConnectorError::RequestEncodingFailedWithReason( "Missing Capture id".to_string(), ), )?; Ok(format!( "{}v2/payments/captures/{}/refund", self.base_url(connectors), capture_id, )) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = connector_utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = paypal::PaypalRouterData::try_from((amount, None, None, None, req))?; let connector_req = paypal::PaypalRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&RefundExecuteType::get_url(self, req, connectors)?) .headers(RefundExecuteType::get_headers(self, req, connectors)?) .set_body(RefundExecuteType::get_request_body(self, req, connectors)?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: paypal::RefundResponse = res.response .parse_struct("paypal RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paypal { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v2/payments/refunds/{}", self.base_url(connectors), req.request.get_connector_refund_id()? )) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&RefundSyncType::get_url(self, req, connectors)?) .headers(RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: paypal::RefundSyncResponse = res .response .parse_struct("paypal RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, > for Paypal { fn get_headers( &self, req: &RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let auth = paypal::PaypalAuthType::try_from(&req.connector_auth_type)?; let credentials = auth.get_credentials()?; let auth_val = credentials.generate_authorization_value(); Ok(vec![ ( headers::CONTENT_TYPE.to_string(), VerifyWebhookSourceType::get_content_type(self) .to_string() .into(), ), (headers::AUTHORIZATION.to_string(), auth_val.into_masked()), ]) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}v1/notifications/verify-webhook-signature", self.base_url(connectors) )) } fn build_request( &self, req: &VerifyWebhookSourceRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&VerifyWebhookSourceType::get_url(self, req, connectors)?) .headers(VerifyWebhookSourceType::get_headers(self, req, connectors)?) .set_body(VerifyWebhookSourceType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn get_request_body( &self, req: &RouterData< VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData, >, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let connector_req = paypal::PaypalSourceVerificationRequest::try_from(&req.request)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn handle_response( &self, data: &VerifyWebhookSourceRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<VerifyWebhookSourceRouterData, errors::ConnectorError> { let response: paypal::PaypalSourceVerificationResponse = res .response .parse_struct("paypal PaypalSourceVerificationResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl IncomingWebhook for Paypal { fn get_webhook_object_reference_id( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { let payload: paypal::PaypalWebhooksBody = request .body .parse_struct("PaypalWebhooksBody") .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?; match payload.resource { paypal::PaypalResource::PaypalCardWebhooks(resource) => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( resource.supplementary_data.related_ids.order_id, ), )) } paypal::PaypalResource::PaypalRedirectsWebhooks(resource) => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::PaymentAttemptId( resource .purchase_units .first() .and_then(|unit| unit.invoice_id.clone().or(unit.reference_id.clone())) .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, ), )) } paypal::PaypalResource::PaypalRefundWebhooks(resource) => { Ok(api_models::webhooks::ObjectReferenceId::RefundId( api_models::webhooks::RefundIdType::ConnectorRefundId(resource.id), )) } paypal::PaypalResource::PaypalDisputeWebhooks(resource) => { Ok(api_models::webhooks::ObjectReferenceId::PaymentId( api_models::payments::PaymentIdType::ConnectorTransactionId( resource .disputed_transactions .first() .map(|transaction| transaction.seller_transaction_id.clone()) .ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?, ), )) } #[cfg(feature = "payouts")] paypal::PaypalResource::PaypalBatchPayoutWebhooks(resource) => { Ok(api_models::webhooks::ObjectReferenceId::PayoutId( api_models::webhooks::PayoutIdType::ConnectorPayoutId( resource.batch_header.payout_batch_id, ), )) } #[cfg(feature = "payouts")] paypal::PaypalResource::PaypalItemPayoutWebhooks(resource) => { Ok(api_models::webhooks::ObjectReferenceId::PayoutId( api_models::webhooks::PayoutIdType::PayoutAttemptId(resource.sender_batch_id), )) } } } fn get_webhook_event_type( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { let payload: paypal::PaypalWebooksEventType = request .body .parse_struct("PaypalWebooksEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?; let outcome = match payload.event_type { PaypalWebhookEventType::CustomerDisputeResolved => Some( request .body .parse_struct::<paypal::DisputeOutcome>("PaypalWebooksEventType") .change_context(errors::ConnectorError::WebhookEventTypeNotFound)? .outcome_code, ), PaypalWebhookEventType::CustomerDisputeCreated | PaypalWebhookEventType::RiskDisputeCreated | PaypalWebhookEventType::CustomerDisputedUpdated | PaypalWebhookEventType::PaymentAuthorizationCreated | PaypalWebhookEventType::PaymentAuthorizationVoided | PaypalWebhookEventType::PaymentCaptureDeclined | PaypalWebhookEventType::PaymentCaptureCompleted | PaypalWebhookEventType::PaymentCapturePending | PaypalWebhookEventType::PaymentCaptureRefunded | PaypalWebhookEventType::CheckoutOrderApproved | PaypalWebhookEventType::CheckoutOrderCompleted | PaypalWebhookEventType::CheckoutOrderProcessed | PaypalWebhookEventType::Unknown => None, #[cfg(feature = "payouts")] PaypalWebhookEventType::PayoutsBatchDenied | PaypalWebhookEventType::PayoutsBatchProcessing | PaypalWebhookEventType::PayoutsBatchSuccess | PaypalWebhookEventType::PayoutsItemBlocked | PaypalWebhookEventType::PayoutsItemCanceled | PaypalWebhookEventType::PayoutsItemDenied | PaypalWebhookEventType::PayoutsItemFailed | PaypalWebhookEventType::PayoutsItemHeld | PaypalWebhookEventType::PayoutsItemRefunded | PaypalWebhookEventType::PayoutsItemReturned | PaypalWebhookEventType::PayoutsItemSuccess | PaypalWebhookEventType::PayoutsItemUnclaimed => None, }; Ok(transformers::get_payapl_webhooks_event( payload.event_type, outcome, )) } fn get_webhook_resource_object( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { let details: paypal::PaypalWebhooksBody = request .body .parse_struct("PaypalWebhooksBody") .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?; Ok(match details.resource { paypal::PaypalResource::PaypalCardWebhooks(resource) => Box::new( paypal::PaypalPaymentsSyncResponse::try_from((*resource, details.event_type))?, ),
crates/hyperswitch_connectors/src/connectors/paypal.rs#chunk1
hyperswitch_connectors
chunk
null
null
null
8,184
null
null
null
null
null
null
null
// Function: get_payment_method_type // File: crates/api_models/src/payment_methods.rs // Module: api_models pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType>
crates/api_models/src/payment_methods.rs
api_models
function_signature
null
null
null
45
get_payment_method_type
null
null
null
null
null
null
// Function: list_payment_methods // File: crates/openapi/src/routes/payments.rs // Module: openapi pub fn list_payment_methods()
crates/openapi/src/routes/payments.rs
openapi
function_signature
null
null
null
31
list_payment_methods
null
null
null
null
null
null
// File: crates/analytics/src/active_payments/metrics/active_payments.rs // Module: analytics use std::collections::HashSet; use api_models::analytics::{ active_payments::ActivePaymentsMetricsBucketIdentifier, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::ActivePaymentsMetricRow; use crate::{ query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct ActivePayments; #[async_trait::async_trait] impl<T> super::ActivePaymentsMetric<T> for ActivePayments where T: AnalyticsDataSource + super::ActivePaymentsMetricAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, time_range: &TimeRange, pool: &T, ) -> MetricsResult< HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, > { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ActivePaymentsAnalytics); query_builder .add_select_column(Aggregate::DistinctCount { field: "payment_id", alias: Some("count"), }) .switch()?; query_builder .add_custom_filter_clause( "merchant_id", format!("'{}','{}'", merchant_id.get_string_repr(), publishable_key), FilterTypes::In, ) .switch()?; query_builder .add_negative_filter_clause("payment_id", "") .switch()?; query_builder .add_custom_filter_clause( "flow_type", "'sdk', 'payment', 'payment_redirection_response'", FilterTypes::In, ) .switch()?; time_range .set_filter_clause(&mut query_builder) .attach_printable("Error filtering time range") .switch()?; query_builder .execute_query::<ActivePaymentsMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| Ok((ActivePaymentsMetricsBucketIdentifier::new(None), i))) .collect::<error_stack::Result< HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
crates/analytics/src/active_payments/metrics/active_payments.rs
analytics
full_file
null
null
null
621
null
null
null
null
null
null
null
// File: crates/router/src/core/conditional_config.rs // Module: router // Public functions: 6 #[cfg(feature = "v2")] use api_models::conditional_configs::DecisionManagerRequest; use api_models::conditional_configs::{ DecisionManager, DecisionManagerRecord, DecisionManagerResponse, }; use common_utils::ext_traits::StringExt; #[cfg(feature = "v2")] use common_utils::types::keymanager::KeyManagerState; use error_stack::ResultExt; use crate::{ core::errors::{self, RouterResponse}, routes::SessionState, services::api as service_api, types::domain, }; #[cfg(feature = "v2")] pub async fn upsert_conditional_config( state: SessionState, key_store: domain::MerchantKeyStore, request: DecisionManagerRequest, profile: domain::Profile, ) -> RouterResponse<common_types::payments::DecisionManagerRecord> { use common_utils::ext_traits::OptionExt; let key_manager_state: &KeyManagerState = &(&state).into(); let db = &*state.store; let name = request.name; let program = request.program; let timestamp = common_utils::date_time::now_unix_timestamp(); euclid::frontend::ast::lowering::lower_program(program.clone()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid Request Data".to_string(), }) .attach_printable("The Request has an Invalid Comparison")?; let decision_manager_record = common_types::payments::DecisionManagerRecord { name, program, created_at: timestamp, }; let business_profile_update = domain::ProfileUpdate::DecisionManagerRecordUpdate { three_ds_decision_manager_config: decision_manager_record, }; let updated_profile = db .update_profile_by_profile_id( key_manager_state, &key_store, profile, business_profile_update, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update decision manager record in business profile")?; Ok(service_api::ApplicationResponse::Json( updated_profile .three_ds_decision_manager_config .clone() .get_required_value("three_ds_decision_manager_config") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable( "Failed to get updated decision manager record in business profile", )?, )) } #[cfg(feature = "v1")] pub async fn upsert_conditional_config( state: SessionState, merchant_context: domain::MerchantContext, request: DecisionManager, ) -> RouterResponse<DecisionManagerRecord> { use common_utils::ext_traits::{Encode, OptionExt, ValueExt}; use diesel_models::configs; use storage_impl::redis::cache; use super::routing::helpers::update_merchant_active_algorithm_ref; let db = state.store.as_ref(); let (name, prog) = match request { DecisionManager::DecisionManagerv0(ccr) => { let name = ccr.name; let prog = ccr .algorithm .get_required_value("algorithm") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "algorithm", }) .attach_printable("Algorithm for config not given")?; (name, prog) } DecisionManager::DecisionManagerv1(dmr) => { let name = dmr.name; let prog = dmr .program .get_required_value("program") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "program", }) .attach_printable("Program for config not given")?; (name, prog) } }; let timestamp = common_utils::date_time::now_unix_timestamp(); let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_context .get_merchant_account() .routing_algorithm .clone() .map(|val| val.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the routing algorithm")? .unwrap_or_default(); let key = merchant_context .get_merchant_account() .get_id() .get_payment_config_routing_id(); let read_config_key = db.find_config_by_key(&key).await; euclid::frontend::ast::lowering::lower_program(prog.clone()) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Invalid Request Data".to_string(), }) .attach_printable("The Request has an Invalid Comparison")?; match read_config_key { Ok(config) => { let previous_record: DecisionManagerRecord = config .config .parse_struct("DecisionManagerRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Payment Config Key Not Found")?; let new_algo = DecisionManagerRecord { name: previous_record.name, program: prog, modified_at: timestamp, created_at: previous_record.created_at, }; let serialize_updated_str = new_algo .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize config to string")?; let updated_config = configs::ConfigUpdate::Update { config: Some(serialize_updated_str), }; db.update_config_by_key(&key, updated_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); update_merchant_active_algorithm_ref( &state, merchant_context.get_merchant_key_store(), config_key, algo_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; Ok(service_api::ApplicationResponse::Json(new_algo)) } Err(e) if e.current_context().is_db_not_found() => { let new_rec = DecisionManagerRecord { name: name .get_required_value("name") .change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name", }) .attach_printable("name of the config not found")?, program: prog, modified_at: timestamp, created_at: timestamp, }; let serialized_str = new_rec .encode_to_string_of_json() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error serializing the config")?; let new_config = configs::ConfigNew { key: key.clone(), config: serialized_str, }; db.insert_config(new_config) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching the config")?; algo_id.update_conditional_config_id(key.clone()); let config_key = cache::CacheKind::DecisionManager(key.into()); update_merchant_active_algorithm_ref( &state, merchant_context.get_merchant_key_store(), config_key, algo_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update routing algorithm ref")?; Ok(service_api::ApplicationResponse::Json(new_rec)) } Err(e) => Err(e) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error fetching payment config"), } } #[cfg(feature = "v2")] pub async fn delete_conditional_config( _state: SessionState, _merchant_context: domain::MerchantContext, ) -> RouterResponse<()> { todo!() } #[cfg(feature = "v1")] pub async fn delete_conditional_config( state: SessionState, merchant_context: domain::MerchantContext, ) -> RouterResponse<()> { use common_utils::ext_traits::ValueExt; use storage_impl::redis::cache; use super::routing::helpers::update_merchant_active_algorithm_ref; let db = state.store.as_ref(); let key = merchant_context .get_merchant_account() .get_id() .get_payment_config_routing_id(); let mut algo_id: api_models::routing::RoutingAlgorithmRef = merchant_context .get_merchant_account() .routing_algorithm .clone() .map(|value| value.parse_value("routing algorithm")) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not decode the conditional_config algorithm")? .unwrap_or_default(); algo_id.config_algo_id = None; let config_key = cache::CacheKind::DecisionManager(key.clone().into()); update_merchant_active_algorithm_ref( &state, merchant_context.get_merchant_key_store(), config_key, algo_id, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to update deleted algorithm ref")?; db.delete_config_by_key(&key) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to delete routing config from DB")?; Ok(service_api::ApplicationResponse::StatusOk) } #[cfg(feature = "v1")] pub async fn retrieve_conditional_config( state: SessionState, merchant_context: domain::MerchantContext, ) -> RouterResponse<DecisionManagerResponse> { let db = state.store.as_ref(); let algorithm_id = merchant_context .get_merchant_account() .get_id() .get_payment_config_routing_id(); let algo_config = db .find_config_by_key(&algorithm_id) .await .change_context(errors::ApiErrorResponse::ResourceIdNotFound) .attach_printable("The conditional config was not found in the DB")?; let record: DecisionManagerRecord = algo_config .config .parse_struct("ConditionalConfigRecord") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Conditional Config Record was not found")?; let response = DecisionManagerRecord { name: record.name, program: record.program, created_at: record.created_at, modified_at: record.modified_at, }; Ok(service_api::ApplicationResponse::Json(response)) } #[cfg(feature = "v2")] pub async fn retrieve_conditional_config( state: SessionState, key_store: domain::MerchantKeyStore, profile: domain::Profile, ) -> RouterResponse<common_types::payments::DecisionManagerResponse> { let db = state.store.as_ref(); let key_manager_state: &KeyManagerState = &(&state).into(); let profile_id = profile.get_id(); let record = profile .three_ds_decision_manager_config .clone() .ok_or(errors::ApiErrorResponse::InternalServerError) .attach_printable("The Conditional Config Record was not found")?; let response = common_types::payments::DecisionManagerRecord { name: record.name, program: record.program, created_at: record.created_at, }; Ok(service_api::ApplicationResponse::Json(response)) }
crates/router/src/core/conditional_config.rs
router
full_file
null
null
null
2,404
null
null
null
null
null
null
null
// Implementation: impl PaymentMetricAccumulator for for CountAccumulator // File: crates/analytics/src/payments/accumulator.rs // Module: analytics // Methods: 2 total (0 public) impl PaymentMetricAccumulator for for CountAccumulator
crates/analytics/src/payments/accumulator.rs
analytics
impl_block
null
null
null
56
null
CountAccumulator
PaymentMetricAccumulator for
2
0
null
null
// Implementation: impl PaymentRedirectFlow for for PaymentAuthenticateCompleteAuthorize // File: crates/router/src/core/payments.rs // Module: router // Methods: 3 total (0 public) impl PaymentRedirectFlow for for PaymentAuthenticateCompleteAuthorize
crates/router/src/core/payments.rs
router
impl_block
null
null
null
50
null
PaymentAuthenticateCompleteAuthorize
PaymentRedirectFlow for
3
0
null
null
// Function: delete_card_from_hs_locker_by_global_id // File: crates/router/src/core/payment_methods/cards.rs // Module: router pub fn delete_card_from_hs_locker_by_global_id<'a>( state: &routes::SessionState, id: &str, merchant_id: &id_type::MerchantId, card_reference: &'a str, ) -> errors::RouterResult<payment_methods::DeleteCardResp>
crates/router/src/core/payment_methods/cards.rs
router
function_signature
null
null
null
92
delete_card_from_hs_locker_by_global_id
null
null
null
null
null
null
// Implementation: impl ProcessTracker // File: crates/diesel_models/src/query/process_tracker.rs // Module: diesel_models // Methods: 6 total (0 public) impl ProcessTracker
crates/diesel_models/src/query/process_tracker.rs
diesel_models
impl_block
null
null
null
39
null
ProcessTracker
null
6
0
null
null
// Function: add_api_key // File: crates/router/src/services/authentication/decision.rs // Module: router pub fn add_api_key( state: &SessionState, api_key: Secret<String>, merchant_id: common_utils::id_type::MerchantId, key_id: common_utils::id_type::ApiKeyId, expiry: Option<u64>, ) -> CustomResult<(), ApiClientError>
crates/router/src/services/authentication/decision.rs
router
function_signature
null
null
null
87
add_api_key
null
null
null
null
null
null
// File: crates/router/tests/connectors/trustpay.rs // Module: router use std::str::FromStr; use hyperswitch_domain_models::address::{Address, AddressDetails}; use masking::Secret; use router::types::{self, api, domain, storage::enums, BrowserInformation}; use crate::{ connector_auth, utils::{self, ConnectorActions}, }; #[derive(Clone, Copy)] struct TrustpayTest; impl ConnectorActions for TrustpayTest {} impl utils::Connector for TrustpayTest { fn get_data(&self) -> api::ConnectorData { use router::connector::Trustpay; utils::construct_connector_data_old( Box::new(Trustpay::new()), types::Connector::Trustpay, api::GetToken::Connector, None, ) } fn get_auth_token(&self) -> types::ConnectorAuthType { utils::to_connector_auth_type( connector_auth::ConnectorAuthentication::new() .trustpay .expect("Missing connector authentication configuration") .into(), ) } fn get_name(&self) -> String { "trustpay".to_string() } } fn get_default_browser_info() -> BrowserInformation { BrowserInformation { color_depth: Some(24), java_enabled: Some(false), java_script_enabled: Some(true), language: Some("en-US".to_string()), screen_height: Some(1080), screen_width: Some(1920), time_zone: Some(3600), accept_header: Some("*".to_string()), user_agent: Some("none".to_string()), ip_address: None, os_type: None, os_version: None, device_model: None, accept_language: Some("en".to_string()), referer: None, } } fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> { Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), router_return_url: Some(String::from("http://localhost:8080")), ..utils::PaymentAuthorizeType::default().0 }) } fn get_default_payment_info() -> Option<utils::PaymentInfo> { Some(utils::PaymentInfo { address: Some(types::PaymentAddress::new( None, Some(Address { address: Some(AddressDetails { first_name: Some(Secret::new("first".to_string())), last_name: Some(Secret::new("last".to_string())), line1: Some(Secret::new("line1".to_string())), line2: Some(Secret::new("line2".to_string())), city: Some("city".to_string()), zip: Some(Secret::new("zip".to_string())), country: Some(api_models::enums::CountryAlpha2::IN), ..Default::default() }), phone: None, email: None, }), None, None, )), ..Default::default() }) } static CONNECTOR: TrustpayTest = TrustpayTest {}; // Cards Positive Tests // Creates a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_make_payment() { let authorize_response = CONNECTOR .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); } // Synchronizes a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_auto_captured_payment() { let authorize_response = CONNECTOR .make_payment( get_default_payment_authorize_data(), get_default_payment_info(), ) .await .unwrap(); assert_eq!(authorize_response.status, enums::AttemptStatus::Charged); let txn_id = utils::get_connector_transaction_id(authorize_response.response); assert_ne!(txn_id, None, "Empty connector transaction id"); let response = CONNECTOR .psync_retry_till_status_matches( enums::AttemptStatus::Charged, Some(types::PaymentsSyncData { connector_transaction_id: types::ResponseId::ConnectorTransactionId( txn_id.unwrap(), ), ..Default::default() }), None, ) .await .unwrap(); assert_eq!(response.status, enums::AttemptStatus::Charged,); } // Refunds a payment using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_refund_auto_captured_payment() { let response = CONNECTOR .make_payment_and_refund( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Synchronizes a refund using the automatic capture flow (Non 3DS). #[actix_web::test] async fn should_sync_refund() { let refund_response = CONNECTOR .make_payment_and_refund( get_default_payment_authorize_data(), None, get_default_payment_info(), ) .await .unwrap(); let response = CONNECTOR .rsync_retry_till_status_matches( enums::RefundStatus::Success, refund_response.response.unwrap().connector_refund_id, None, None, ) .await .unwrap(); assert_eq!( response.response.unwrap().refund_status, enums::RefundStatus::Success, ); } // Cards Negative scenarios // Creates a payment with incorrect card number. #[actix_web::test] async fn should_fail_payment_for_incorrect_card_number() { let payment_authorize_data = types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("1234567891011").unwrap(), card_exp_year: Secret::new("25".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), ..utils::PaymentAuthorizeType::default().0 }; let response = CONNECTOR .make_payment(Some(payment_authorize_data), get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Errors { code: 61, description: \"invalid payment data (country or brand)\" }".to_string(), ); } // Creates a payment with incorrect expiry year. #[actix_web::test] async fn should_fail_payment_for_incorrect_expiry_year() { let payment_authorize_data = Some(types::PaymentsAuthorizeData { payment_method_data: domain::PaymentMethodData::Card(domain::Card { card_number: cards::CardNumber::from_str("4200000000000000").unwrap(), card_exp_year: Secret::new("22".to_string()), card_cvc: Secret::new("123".to_string()), ..utils::CCardType::default().0 }), browser_info: Some(get_default_browser_info()), ..utils::PaymentAuthorizeType::default().0 }); let response = CONNECTOR .make_payment(payment_authorize_data, get_default_payment_info()) .await .unwrap(); assert_eq!( response.response.unwrap_err().message, "Errors { code: 15, description: \"the provided expiration year is not valid\" }" .to_string(), ); }
crates/router/tests/connectors/trustpay.rs
router
full_file
null
null
null
1,762
null
null
null
null
null
null
null
// File: crates/api_models/src/payouts.rs // Module: api_models // Public functions: 1 // Public structs: 28 use std::collections::HashMap; use cards::CardNumber; use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, payout_method_utils, pii::{self, Email}, transformers::ForeignFrom, types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), PayoutCreateRequest(Box<PayoutCreateRequest>), PayoutRetrieveRequest(PayoutRetrieveRequest), } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.** #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub payout_id: Option<id_type::PayoutId>, /// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.** #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported. #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 1000)] #[mandatory_in(PayoutsCreateRequest = u64)] #[remove_in(PayoutsConfirmRequest)] #[serde(default, deserialize_with = "payments::amount::deserialize_option")] pub amount: Option<payments::Amount>, /// The currency of the payout request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] #[mandatory_in(PayoutsCreateRequest = Currency)] #[remove_in(PayoutsConfirmRequest)] pub currency: Option<api_enums::Currency>, /// Specifies routing algorithm for selecting a connector #[schema(value_type = Option<StaticRoutingAlgorithm>, example = json!({ "type": "single", "data": "adyen" }))] pub routing: Option<serde_json::Value>, /// This field allows the merchant to manually select a connector with which the payout can go through. #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it. #[schema(value_type = Option<bool>, example = true, default = false)] #[remove_in(PayoutConfirmRequest)] pub confirm: Option<bool>, /// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed. #[schema(value_type = Option<PayoutType>, example = "card")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method information required for carrying out a payout #[schema(value_type = Option<PayoutMethodData>)] pub payout_method_data: Option<PayoutMethodData>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = Option<bool>, example = true, default = false)] pub auto_fulfill: Option<bool>, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<payments::CustomerDetails>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PayoutsCreateRequest)] #[mandatory_in(PayoutConfirmRequest = String)] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to, select from the given list of options #[schema(value_type = Option<PayoutEntityType>, example = "Individual")] pub entity_type: Option<api_enums::PayoutEntityType>, /// Specifies whether or not the payout request is recurring #[schema(value_type = Option<bool>, default = false)] pub recurring: Option<bool>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Provide a reference to a stored payout method, used to process the payout. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)] pub payout_token: Option<String>, /// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The send method which will be required for processing payouts, check options for better understanding. #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_. #[schema(default = false, example = true, value_type = Option<bool>)] pub payout_link: Option<bool>, /// Custom payout link config for the particular payout, if payout link is to be generated. #[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)] pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// Identifier for payout method pub payout_method_id: Option<String>, } impl PayoutCreateRequest { pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } } /// Custom payout link config for the particular payout, if payout link is to be generated. #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct PayoutCreatePayoutLinkConfig { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub payout_link_id: Option<String>, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// List of payout methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// `test_mode` allows for opening payout links without any restrictions. This removes /// - domain name validations /// - check for making sure link is accessed within an iframe #[schema(value_type = Option<bool>, example = false)] pub test_mode: Option<bool>, } /// The payout method information required for carrying out a payout #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { Card(CardPayout), Bank(Bank), Wallet(Wallet), } impl Default for PayoutMethodData { fn default() -> Self { Self::Card(CardPayout::default()) } } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardPayout { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AchBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [9 digits] Routing number - used in USA for identifying a specific bank. #[schema(value_type = String, example = "110000000")] pub bank_routing_number: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct BacsBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches. #[schema(value_type = String, example = "98-76-54")] pub bank_sort_code: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] // The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone. pub struct SepaBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer. #[schema(value_type = String, example = "DE89370400440532013000")] pub iban: Secret<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = String, example = "HSBCGB2LXXX")] pub bic: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct PixBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// Unique key for pix customer #[schema(value_type = String, example = "000123456")] pub pix_key: Secret<String>, /// Individual taxpayer identification number #[schema(value_type = Option<String>, example = "000123456")] pub tax_id: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum Wallet { Paypal(Paypal), Venmo(Venmo), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Paypal { /// Email linked with paypal account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Option<Email>, /// mobile number linked to paypal account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, /// id of the paypal account #[schema(value_type = String, example = "G83KXTJ5EHCQ2")] pub paypal_id: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Venmo { /// mobile number linked to venmo account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, } #[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")] pub merchant_id: id_type::MerchantId, /// Your unique identifier for this payout or order. This ID helps you reconcile payouts on your system. If provided, it is passed to the connector if supported. #[schema(value_type = Option<String>, max_length = 255, example = "merchant_order_ref_123")] pub merchant_order_reference_id: Option<String>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 1000)] pub amount: common_utils::types::MinorUnit, /// Recipient's currency for the payout request #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// The connector used for the payout #[schema(example = "wise")] pub connector: Option<String>, /// The payout method that is to be used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method details for the payout #[schema(value_type = Option<PayoutMethodDataResponse>, example = json!(r#"{ "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": null, "payment_checks": null, "authentication_data": null } }"#))] pub payout_method_data: Option<PayoutMethodDataResponse>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = bool, example = true, default = false)] pub auto_fulfill: bool, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetailsResponse>)] pub customer: Option<payments::CustomerDetailsResponse>, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout #[schema(example = "US", value_type = CountryAlpha2)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout #[schema(example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: api_enums::PayoutEntityType, /// Specifies whether or not the payout request is recurring #[schema(value_type = bool, default = false)] pub recurring: bool, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Unique identifier of the merchant connector account #[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Current status of the Payout #[schema(value_type = PayoutStatus, example = RequiresConfirmation)] pub status: api_enums::PayoutStatus, /// If there was an error while calling the connector the error message is received here #[schema(value_type = Option<String>, example = "Failed while verifying the card")] pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(value_type = Option<String>, example = "E0001")] pub error_code: Option<String>, /// The business profile that is associated with this payout #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Time when the payout was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Underlying processor's payout resource ID #[schema(value_type = Option<String>, example = "S3FC9G9M2MVFDXT5")] pub connector_transaction_id: Option<String>, /// Payout's send priority (if applicable) #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// List of attempts #[schema(value_type = Option<Vec<PayoutAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PayoutAttemptResponse>>, /// If payout link was requested, this contains the link's ID and the URL to render the payout widget #[schema(value_type = Option<PayoutLinkResponse>)] pub payout_link: Option<PayoutLinkResponse>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: crypto::OptionalEncryptableName, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, /// Identifier for payout method pub payout_method_id: Option<String>, } /// The payout method information for response #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodDataResponse { #[schema(value_type = CardAdditionalData)] Card(Box<payout_method_utils::CardAdditionalData>), #[schema(value_type = BankAdditionalData)] Bank(Box<payout_method_utils::BankAdditionalData>), #[schema(value_type = WalletAdditionalData)] Wallet(Box<payout_method_utils::WalletAdditionalData>), } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct PayoutAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = PayoutStatus, example = "failed")] pub status: api_enums::PayoutStatus, /// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6583)] pub amount: common_utils::types::MinorUnit, /// The currency of the amount of the payout attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<api_enums::Currency>, /// The connector used for the payout pub connector: Option<String>, /// Connector's error code in case of failures pub error_code: Option<String>, /// Connector's error message in case of failures pub error_message: Option<String>, /// The payout method that was used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payment_method: Option<api_enums::PayoutType>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "bacs")] pub payout_method_type: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payout provided by the connector pub connector_transaction_id: Option<String>, /// If the payout was cancelled the reason provided here pub cancellation_reason: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, } #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutRetrieveRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, /// `force_sync` with the connector to get payout details /// (defaults to false) #[schema(value_type = Option<bool>, default = false, example = true)] pub force_sync: Option<bool>, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Debug, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)] pub struct PayoutActionRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: id_type::PayoutId, } #[derive(Default, Debug, ToSchema, Clone, Deserialize)] pub struct PayoutVendorAccountDetails { pub vendor_details: PayoutVendorDetails, pub individual_details: PayoutIndividualDetails, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutVendorDetails { pub account_type: String, pub business_type: String, pub business_profile_mcc: Option<i32>, pub business_profile_url: Option<String>, pub business_profile_name: Option<Secret<String>>, pub company_address_line1: Option<Secret<String>>, pub company_address_line2: Option<Secret<String>>, pub company_address_postal_code: Option<Secret<String>>, pub company_address_city: Option<Secret<String>>, pub company_address_state: Option<Secret<String>>, pub company_phone: Option<Secret<String>>, pub company_tax_id: Option<Secret<String>>, pub company_owners_provided: Option<bool>, pub capabilities_card_payments: Option<bool>, pub capabilities_transfers: Option<bool>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutIndividualDetails { pub tos_acceptance_date: Option<i64>, pub tos_acceptance_ip: Option<Secret<String>>, pub individual_dob_day: Option<Secret<String>>, pub individual_dob_month: Option<Secret<String>>, pub individual_dob_year: Option<Secret<String>>, pub individual_id_number: Option<Secret<String>>, pub individual_ssn_last_4: Option<Secret<String>>, pub external_account_account_holder_type: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListConstraints { /// The identifier for customer #[schema(value_type = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub starting_after: Option<id_type::PayoutId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "payout_fafa124123", value_type = Option<String>,)] pub ending_before: Option<id_type::PayoutId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payouts_list_limit")] pub limit: u32,
crates/api_models/src/payouts.rs#chunk0
api_models
chunk
null
null
null
8,185
null
null
null
null
null
null
null
// Implementation: impl MerchantConnectorAccountUpdateInternal // File: crates/diesel_models/src/merchant_connector_account.rs // Module: diesel_models // Methods: 1 total (1 public) impl MerchantConnectorAccountUpdateInternal
crates/diesel_models/src/merchant_connector_account.rs
diesel_models
impl_block
null
null
null
46
null
MerchantConnectorAccountUpdateInternal
null
1
1
null
null
// Function: get_connector_choice // File: crates/router/src/core/payouts.rs // Module: router pub fn get_connector_choice( state: &SessionState, merchant_context: &domain::MerchantContext, connector: Option<String>, routing_algorithm: Option<serde_json::Value>, payout_data: &mut PayoutData, eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>, ) -> RouterResult<api::ConnectorCallType>
crates/router/src/core/payouts.rs
router
function_signature
null
null
null
102
get_connector_choice
null
null
null
null
null
null
// Function: reset_totp // File: crates/router/src/core/user.rs // Module: router pub fn reset_totp( state: SessionState, user_token: auth::UserFromToken, ) -> UserResponse<user_api::BeginTotpResponse>
crates/router/src/core/user.rs
router
function_signature
null
null
null
57
reset_totp
null
null
null
null
null
null
// Function: create_payout_retrieve // File: crates/router/src/core/payouts.rs // Module: router pub fn create_payout_retrieve( state: &SessionState, merchant_context: &domain::MerchantContext, connector_data: &api::ConnectorData, payout_data: &mut PayoutData, ) -> RouterResult<()>
crates/router/src/core/payouts.rs
router
function_signature
null
null
null
76
create_payout_retrieve
null
null
null
null
null
null
// Implementation: impl api::PaymentCapture for for Gpayments // File: crates/hyperswitch_connectors/src/connectors/gpayments.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentCapture for for Gpayments
crates/hyperswitch_connectors/src/connectors/gpayments.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Gpayments
api::PaymentCapture for
0
0
null
null
// Implementation: impl api::PaymentAuthorize for for Payeezy // File: crates/hyperswitch_connectors/src/connectors/payeezy.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentAuthorize for for Payeezy
crates/hyperswitch_connectors/src/connectors/payeezy.rs
hyperswitch_connectors
impl_block
null
null
null
60
null
Payeezy
api::PaymentAuthorize for
0
0
null
null
// Implementation: impl api::PaymentVoid for for Worldline // File: crates/hyperswitch_connectors/src/connectors/worldline.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentVoid for for Worldline
crates/hyperswitch_connectors/src/connectors/worldline.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Worldline
api::PaymentVoid for
0
0
null
null
// Struct: EncryptionTransferRequest // File: crates/common_utils/src/types/keymanager.rs // Module: common_utils // Implementations: 0 pub struct EncryptionTransferRequest
crates/common_utils/src/types/keymanager.rs
common_utils
struct_definition
EncryptionTransferRequest
0
[]
37
null
null
null
null
null
null
null
// File: crates/hyperswitch_domain_models/src/callback_mapper.rs // Module: hyperswitch_domain_models // Public functions: 1 // Public structs: 1 use common_enums::enums as common_enums; use common_types::callback_mapper::CallbackMapperData; #[derive(Clone, Debug, Eq, PartialEq)] pub struct CallbackMapper { pub id: String, pub callback_mapper_id_type: common_enums::CallbackMapperIdType, pub data: CallbackMapperData, pub created_at: time::PrimitiveDateTime, pub last_modified_at: time::PrimitiveDateTime, } impl CallbackMapper { pub fn new( id: String, callback_mapper_id_type: common_enums::CallbackMapperIdType, data: CallbackMapperData, created_at: time::PrimitiveDateTime, last_modified_at: time::PrimitiveDateTime, ) -> Self { Self { id, callback_mapper_id_type, data, created_at, last_modified_at, } } }
crates/hyperswitch_domain_models/src/callback_mapper.rs
hyperswitch_domain_models
full_file
null
null
null
215
null
null
null
null
null
null
null
pub fn get_webhook_object_from_body( body: &[u8], ) -> CustomResult<GetnetWebhookNotificationResponseBody, errors::ConnectorError> { let body_bytes = bytes::Bytes::copy_from_slice(body); let parsed_param: GetnetWebhookNotificationResponse = parse_url_encoded_to_struct(body_bytes) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let response_base64 = &parsed_param.response_base64.peek(); let decoded_response = BASE64_ENGINE .decode(response_base64) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; let getnet_webhook_notification_response: GetnetWebhookNotificationResponseBody = match serde_json::from_slice::<GetnetWebhookNotificationResponseBody>(&decoded_response) { Ok(response) => response, Err(_e) => { return Err(errors::ConnectorError::WebhookBodyDecodingFailed)?; } }; Ok(getnet_webhook_notification_response) } pub fn get_webhook_response( body: &[u8], ) -> CustomResult<GetnetWebhookNotificationResponse, errors::ConnectorError> { let body_bytes = bytes::Bytes::copy_from_slice(body); let parsed_param: GetnetWebhookNotificationResponse = parse_url_encoded_to_struct(body_bytes) .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?; Ok(parsed_param) } pub fn get_incoming_webhook_event( transaction_type: GetnetTransactionType, transaction_status: GetnetPaymentStatus, ) -> IncomingWebhookEvent { match transaction_type { GetnetTransactionType::Purchase => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentProcessing, }, GetnetTransactionType::Authorization => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentAuthorizationSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentAuthorizationFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentProcessing, }, GetnetTransactionType::CaptureAuthorization => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCaptureSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCaptureFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCaptureFailure, }, GetnetTransactionType::RefundPurchase => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::RefundSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::RefundFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::RefundFailure, }, GetnetTransactionType::RefundCapture => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::RefundSuccess, GetnetPaymentStatus::Failed => IncomingWebhookEvent::RefundFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::RefundFailure, }, GetnetTransactionType::VoidAuthorization => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCancelled, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCancelFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCancelFailure, }, GetnetTransactionType::VoidPurchase => match transaction_status { GetnetPaymentStatus::Success => IncomingWebhookEvent::PaymentIntentCancelled, GetnetPaymentStatus::Failed => IncomingWebhookEvent::PaymentIntentCancelFailure, GetnetPaymentStatus::InProgress => IncomingWebhookEvent::PaymentIntentCancelFailure, }, } }
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs#chunk1
hyperswitch_connectors
chunk
null
null
null
824
null
null
null
null
null
null
null
// Struct: CardInfoAdd // File: crates/router/src/core/cards_info.rs // Module: router // Implementations: 1 // Traits: State pub struct CardInfoAdd
crates/router/src/core/cards_info.rs
router
struct_definition
CardInfoAdd
1
[ "State" ]
40
null
null
null
null
null
null
null
// Implementation: impl common_utils::events::ApiEventMetric for for RelayRequest // File: crates/api_models/src/relay.rs // Module: api_models // Methods: 0 total (0 public) impl common_utils::events::ApiEventMetric for for RelayRequest
crates/api_models/src/relay.rs
api_models
impl_block
null
null
null
57
null
RelayRequest
common_utils::events::ApiEventMetric for
0
0
null
null
// Function: refund_retrieve_core_with_internal_reference_id // File: crates/router/src/core/refunds.rs // Module: router pub fn refund_retrieve_core_with_internal_reference_id( state: SessionState, merchant_context: domain::MerchantContext, profile_id: Option<common_utils::id_type::ProfileId>, refund_internal_request_id: String, force_sync: Option<bool>, ) -> RouterResult<diesel_refund::Refund>
crates/router/src/core/refunds.rs
router
function_signature
null
null
null
96
refund_retrieve_core_with_internal_reference_id
null
null
null
null
null
null
// Struct: PayoutEnabledPaymentMethodsInfo // File: crates/api_models/src/payouts.rs // Module: api_models // Implementations: 0 pub struct PayoutEnabledPaymentMethodsInfo
crates/api_models/src/payouts.rs
api_models
struct_definition
PayoutEnabledPaymentMethodsInfo
0
[]
43
null
null
null
null
null
null
null
// Struct: RefundResponse // File: crates/api_models/src/refunds.rs // Module: api_models // Implementations: 2 pub struct RefundResponse
crates/api_models/src/refunds.rs
api_models
struct_definition
RefundResponse
2
[]
36
null
null
null
null
null
null
null
// Struct: BraintreeRedirectionResponse // File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BraintreeRedirectionResponse
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
hyperswitch_connectors
struct_definition
BraintreeRedirectionResponse
0
[]
52
null
null
null
null
null
null
null
Ok((status, error, payment_response_data)) } fn handle_bank_redirects_error_response( response: ErrorResponseBankRedirect, status_code: u16, previous_attempt_status: enums::AttemptStatus, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { let status = if matches!(response.payment_result_info.result_code, 1132014 | 1132005) { previous_attempt_status } else { enums::AttemptStatus::AuthorizationFailed }; let error = Some(ErrorResponse { code: response.payment_result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: response.payment_result_info.result_code.to_string(), reason: response.payment_result_info.additional_info, status_code, attempt_status: Some(status), connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }; Ok((status, error, payment_response_data)) } fn handle_bank_redirects_sync_response( response: SyncResponseBankRedirect, status_code: u16, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { let status = enums::AttemptStatus::from(response.payment_information.status); let error = if utils::is_payment_failure(status) { let reason_info = response .payment_information .status_reason_information .unwrap_or_default(); Some(ErrorResponse { code: reason_info .reason .code .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: reason_info .reason .code .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason_info.reason.reject_reason, status_code, attempt_status: None, connector_transaction_id: Some( response .payment_information .references .payment_request_id .clone(), ), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId( response .payment_information .references .payment_request_id .clone(), ), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }; Ok((status, error, payment_response_data)) } pub fn handle_webhook_response( payment_information: WebhookPaymentInformation, status_code: u16, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { let status = enums::AttemptStatus::try_from(payment_information.status)?; let error = if utils::is_payment_failure(status) { let reason_info = payment_information .status_reason_information .unwrap_or_default(); Some(ErrorResponse { code: reason_info .reason .code .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: reason_info .reason .code .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason_info.reason.reject_reason, status_code, attempt_status: None, connector_transaction_id: payment_information.references.payment_request_id.clone(), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let payment_response_data = PaymentsResponseData::TransactionResponse { resource_id: ResponseId::NoResponseId, redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, charges: None, }; Ok((status, error, payment_response_data)) } pub fn get_trustpay_response( response: TrustpayPaymentsResponse, status_code: u16, previous_attempt_status: enums::AttemptStatus, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, > { match response { TrustpayPaymentsResponse::CardsPayments(response) => { handle_cards_response(*response, status_code) } TrustpayPaymentsResponse::BankRedirectPayments(response) => { handle_bank_redirects_response(*response) } TrustpayPaymentsResponse::BankRedirectSync(response) => { handle_bank_redirects_sync_response(*response, status_code) } TrustpayPaymentsResponse::BankRedirectError(response) => { handle_bank_redirects_error_response(*response, status_code, previous_attempt_status) } TrustpayPaymentsResponse::WebhookResponse(response) => { handle_webhook_response(*response, status_code) } } } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct TrustpayAuthUpdateRequest { pub grant_type: String, } impl TryFrom<&RefreshTokenRouterData> for TrustpayAuthUpdateRequest { type Error = Error; fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> { Ok(Self { grant_type: "client_credentials".to_string(), }) } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct ResultInfo { pub result_code: i64, pub additional_info: Option<String>, pub correlation_id: Option<String>, } #[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq)] pub struct TrustpayAuthUpdateResponse { pub access_token: Option<Secret<String>>, pub token_type: Option<String>, pub expires_in: Option<i64>, #[serde(rename = "ResultInfo")] pub result_info: ResultInfo, } #[derive(Default, Debug, Clone, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "PascalCase")] pub struct TrustpayAccessTokenErrorResponse { pub result_info: ResultInfo, } impl<F, T> TryFrom<ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessToken>> for RouterData<F, T, AccessToken> { type Error = Error; fn try_from( item: ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessToken>, ) -> Result<Self, Self::Error> { match (item.response.access_token, item.response.expires_in) { (Some(access_token), Some(expires_in)) => Ok(Self { response: Ok(AccessToken { token: access_token, expires: expires_in, }), ..item.data }), _ => Ok(Self { response: Err(ErrorResponse { code: item.response.result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: item.response.result_info.result_code.to_string(), reason: item.response.result_info.additional_info, status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }), ..item.data }), } } } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayCreateIntentRequest { pub amount: StringMajorUnit, pub currency: String, // If true, Apple Pay will be initialized pub init_apple_pay: Option<bool>, // If true, Google pay will be initialized pub init_google_pay: Option<bool>, pub reference: String, } impl TryFrom<&TrustpayRouterData<&PaymentsPreProcessingRouterData>> for TrustpayCreateIntentRequest { type Error = Error; fn try_from( item: &TrustpayRouterData<&PaymentsPreProcessingRouterData>, ) -> Result<Self, Self::Error> { let is_apple_pay = item .router_data .request .payment_method_type .as_ref() .map(|pmt| matches!(pmt, enums::PaymentMethodType::ApplePay)); let is_google_pay = item .router_data .request .payment_method_type .as_ref() .map(|pmt| matches!(pmt, enums::PaymentMethodType::GooglePay)); let currency = item.router_data.request.get_currency()?; let amount = item.amount.to_owned(); Ok(Self { amount, currency: currency.to_string(), init_apple_pay: is_apple_pay, init_google_pay: is_google_pay, reference: item.router_data.connector_request_reference_id.clone(), }) } } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayCreateIntentResponse { // TrustPay's authorization secrets used by client pub secrets: SdkSecretInfo, // Data object to be used for Apple Pay or Google Pay #[serde(flatten)] pub init_result_data: InitResultData, // Unique operation/transaction identifier pub instance_id: String, } #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub enum InitResultData { AppleInitResultData(TrustpayApplePayResponse), GoogleInitResultData(TrustpayGooglePayResponse), } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayTransactionInfo { pub country_code: api_models::enums::CountryAlpha2, pub currency_code: api_models::enums::Currency, pub total_price_status: String, pub total_price: StringMajorUnit, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayMerchantInfo { pub merchant_name: Secret<String>, pub merchant_id: Secret<String>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GooglePayAllowedPaymentMethods { #[serde(rename = "type")] pub payment_method_type: String, pub parameters: GpayAllowedMethodsParameters, pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayTokenParameters { pub gateway: String, pub gateway_merchant_id: Secret<String>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayTokenizationSpecification { #[serde(rename = "type")] pub token_specification_type: String, pub parameters: GpayTokenParameters, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct GpayAllowedMethodsParameters { pub allowed_auth_methods: Vec<String>, pub allowed_card_networks: Vec<String>, pub assurance_details_required: Option<bool>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayGooglePayResponse { pub merchant_info: GooglePayMerchantInfo, pub allowed_payment_methods: Vec<GooglePayAllowedPaymentMethods>, pub transaction_info: GooglePayTransactionInfo, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkSecretInfo { pub display: Secret<String>, pub payment: Secret<String>, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayApplePayResponse { pub country_code: api_models::enums::CountryAlpha2, pub currency_code: api_models::enums::Currency, pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub total: ApplePayTotalInfo, } #[derive(Clone, Default, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ApplePayTotalInfo { pub label: String, pub amount: StringMajorUnit, } impl<F> TryFrom< ResponseRouterData< F, TrustpayCreateIntentResponse, PaymentsPreProcessingData, PaymentsResponseData, >, > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> { type Error = Error; fn try_from( item: ResponseRouterData< F, TrustpayCreateIntentResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { let create_intent_response = item.response.init_result_data.to_owned(); let secrets = item.response.secrets.to_owned(); let instance_id = item.response.instance_id.to_owned(); let pmt = PaymentsPreProcessingData::get_payment_method_type(&item.data.request)?; match (pmt, create_intent_response) { ( enums::PaymentMethodType::ApplePay, InitResultData::AppleInitResultData(apple_pay_response), ) => get_apple_pay_session(instance_id, &secrets, apple_pay_response, item), ( enums::PaymentMethodType::GooglePay, InitResultData::GoogleInitResultData(google_pay_response), ) => get_google_pay_session(instance_id, &secrets, google_pay_response, item), _ => Err(report!(errors::ConnectorError::InvalidWallet)), } } } pub(crate) fn get_apple_pay_session<F, T>( instance_id: String, secrets: &SdkSecretInfo, apple_pay_init_result: TrustpayApplePayResponse, item: ResponseRouterData<F, TrustpayCreateIntentResponse, T, PaymentsResponseData>, ) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>> { Ok(RouterData { response: Ok(PaymentsResponseData::PreProcessingResponse { connector_metadata: None, pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(instance_id), session_token: Some(SessionToken::ApplePay(Box::new( api_models::payments::ApplepaySessionTokenResponse { session_token_data: Some( api_models::payments::ApplePaySessionResponse::ThirdPartySdk( api_models::payments::ThirdPartySdkSessionResponse { secrets: secrets.to_owned().into(), }, ), ), payment_request_data: Some(api_models::payments::ApplePayPaymentRequest { country_code: apple_pay_init_result.country_code, currency_code: apple_pay_init_result.currency_code, supported_networks: Some(apple_pay_init_result.supported_networks.clone()), merchant_capabilities: Some( apple_pay_init_result.merchant_capabilities.clone(), ), total: apple_pay_init_result.total.into(), merchant_identifier: None, required_billing_contact_fields: None, required_shipping_contact_fields: None, recurring_payment_request: None, }), connector: "trustpay".to_string(), delayed_session_token: true, sdk_next_action: { api_models::payments::SdkNextAction { next_action: api_models::payments::NextActionCall::Sync, } }, connector_reference_id: None, connector_sdk_public_key: None, connector_merchant_id: None, }, ))), connector_response_reference_id: None, }), // We don't get status from TrustPay but status should be AuthenticationPending by default for session response status: enums::AttemptStatus::AuthenticationPending, ..item.data }) } pub(crate) fn get_google_pay_session<F, T>( instance_id: String, secrets: &SdkSecretInfo, google_pay_init_result: TrustpayGooglePayResponse, item: ResponseRouterData<F, TrustpayCreateIntentResponse, T, PaymentsResponseData>, ) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>> { Ok(RouterData { response: Ok(PaymentsResponseData::PreProcessingResponse { connector_metadata: None, pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(instance_id), session_token: Some(SessionToken::GooglePay(Box::new( api_models::payments::GpaySessionTokenResponse::GooglePaySession( api_models::payments::GooglePaySessionResponse { connector: "trustpay".to_string(), delayed_session_token: true, sdk_next_action: { api_models::payments::SdkNextAction { next_action: api_models::payments::NextActionCall::Sync, } }, merchant_info: google_pay_init_result.merchant_info.into(), allowed_payment_methods: google_pay_init_result .allowed_payment_methods .into_iter() .map(Into::into) .collect(), transaction_info: google_pay_init_result.transaction_info.into(), secrets: Some((*secrets).clone().into()), shipping_address_required: false, email_required: false, shipping_address_parameters: api_models::payments::GpayShippingAddressParameters { phone_number_required: false, }, }, ), ))), connector_response_reference_id: None, }), // We don't get status from TrustPay but status should be AuthenticationPending by default for session response status: enums::AttemptStatus::AuthenticationPending, ..item.data }) } impl From<GooglePayTransactionInfo> for api_models::payments::GpayTransactionInfo { fn from(value: GooglePayTransactionInfo) -> Self { Self { country_code: value.country_code, currency_code: value.currency_code, total_price_status: value.total_price_status, total_price: value.total_price, } } } impl From<GooglePayMerchantInfo> for api_models::payments::GpayMerchantInfo { fn from(value: GooglePayMerchantInfo) -> Self { Self { merchant_id: Some(value.merchant_id.expose()), merchant_name: value.merchant_name.expose(), } } } impl From<GooglePayAllowedPaymentMethods> for api_models::payments::GpayAllowedPaymentMethods { fn from(value: GooglePayAllowedPaymentMethods) -> Self { Self { payment_method_type: value.payment_method_type, parameters: value.parameters.into(), tokenization_specification: value.tokenization_specification.into(), } } } impl From<GpayAllowedMethodsParameters> for api_models::payments::GpayAllowedMethodsParameters { fn from(value: GpayAllowedMethodsParameters) -> Self { Self { allowed_auth_methods: value.allowed_auth_methods, allowed_card_networks: value.allowed_card_networks, billing_address_required: None, billing_address_parameters: None, assurance_details_required: value.assurance_details_required, } } } impl From<GpayTokenizationSpecification> for api_models::payments::GpayTokenizationSpecification { fn from(value: GpayTokenizationSpecification) -> Self { Self { token_specification_type: value.token_specification_type, parameters: value.parameters.into(), } } } impl From<GpayTokenParameters> for api_models::payments::GpayTokenParameters { fn from(value: GpayTokenParameters) -> Self { Self { gateway: Some(value.gateway), gateway_merchant_id: Some(value.gateway_merchant_id.expose()), stripe_version: None, stripe_publishable_key: None, public_key: None, protocol_version: None, } } } impl From<SdkSecretInfo> for api_models::payments::SecretInfoToInitiateSdk { fn from(value: SdkSecretInfo) -> Self { Self { display: value.display, payment: value.payment, } } } impl From<ApplePayTotalInfo> for api_models::payments::AmountInfo { fn from(value: ApplePayTotalInfo) -> Self { Self { label: value.label, amount: value.amount, total_type: None, } } } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayRefundRequestCards { instance_id: String, amount: StringMajorUnit, currency: String, reference: String, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct TrustpayRefundRequestBankRedirect { pub merchant_identification: MerchantIdentification, pub payment_information: BankPaymentInformation, } #[derive(Debug, Serialize)] #[serde(untagged)] pub enum TrustpayRefundRequest { CardsRefund(Box<TrustpayRefundRequestCards>), BankRedirectRefund(Box<TrustpayRefundRequestBankRedirect>), } impl<F> TryFrom<&TrustpayRouterData<&RefundsRouterData<F>>> for TrustpayRefundRequest { type Error = Error; fn try_from(item: &TrustpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { let amount = item.amount.to_owned(); match item.router_data.payment_method { enums::PaymentMethod::BankRedirect => { let auth = TrustpayAuthType::try_from(&item.router_data.connector_auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(Self::BankRedirectRefund(Box::new( TrustpayRefundRequestBankRedirect { merchant_identification: MerchantIdentification { project_id: auth.project_id, }, payment_information: BankPaymentInformation { amount: Amount { amount, currency: item.router_data.request.currency.to_string(), }, references: References { merchant_reference: item.router_data.request.refund_id.clone(), }, debtor: None, }, }, ))) } _ => Ok(Self::CardsRefund(Box::new(TrustpayRefundRequestCards { instance_id: item.router_data.request.connector_transaction_id.clone(), amount, currency: item.router_data.request.currency.to_string(), reference: item.router_data.request.refund_id.clone(), }))), } } } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardsRefundResponse { pub status: i64, pub description: Option<String>, pub instance_id: String, pub payment_status: String, pub payment_description: Option<String>, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct BankRedirectRefundResponse { pub payment_request_id: i64, pub result_info: ResultInfo, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum RefundResponse { CardsRefund(Box<CardsRefundResponse>), WebhookRefund(Box<WebhookPaymentInformation>), BankRedirectRefund(Box<BankRedirectRefundResponse>), BankRedirectRefundSyncResponse(Box<SyncResponseBankRedirect>), BankRedirectError(Box<ErrorResponseBankRedirect>), } fn handle_cards_refund_response( response: CardsRefundResponse, status_code: u16, ) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> { let (refund_status, msg) = get_refund_status(&response.payment_status)?; let error = if msg.is_some() { Some(ErrorResponse { code: response.payment_status, message: msg .clone() .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), reason: msg, status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let refund_response_data = RefundsResponseData { connector_refund_id: response.instance_id, refund_status, }; Ok((error, refund_response_data)) } fn handle_webhooks_refund_response( response: WebhookPaymentInformation, status_code: u16, ) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> { let refund_status = enums::RefundStatus::try_from(response.status)?; let error = if utils::is_refund_failure(refund_status) { let reason_info = response.status_reason_information.unwrap_or_default(); Some(ErrorResponse { code: reason_info .reason .code .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: reason_info .reason .code .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason_info.reason.reject_reason, status_code, attempt_status: None, connector_transaction_id: response.references.payment_request_id.clone(), network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let refund_response_data = RefundsResponseData { connector_refund_id: response .references .payment_request_id .ok_or(errors::ConnectorError::MissingConnectorRefundID)?, refund_status, }; Ok((error, refund_response_data)) } fn handle_bank_redirects_refund_response( response: BankRedirectRefundResponse, status_code: u16, ) -> (Option<ErrorResponse>, RefundsResponseData) { let (refund_status, msg) = get_refund_status_from_result_info(response.result_info.result_code); let error = if msg.is_some() { Some(ErrorResponse { code: response.result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: response.result_info.result_code.to_string(), reason: msg.map(|message| message.to_string()), status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let refund_response_data = RefundsResponseData { connector_refund_id: response.payment_request_id.to_string(), refund_status, }; (error, refund_response_data) } fn handle_bank_redirects_refund_sync_response( response: SyncResponseBankRedirect, status_code: u16, ) -> (Option<ErrorResponse>, RefundsResponseData) { let refund_status = enums::RefundStatus::from(response.payment_information.status); let error = if utils::is_refund_failure(refund_status) { let reason_info = response .payment_information .status_reason_information .unwrap_or_default(); Some(ErrorResponse { code: reason_info .reason .code .clone() .unwrap_or(consts::NO_ERROR_CODE.to_string()), // message vary for the same code, so relying on code alone as it is unique message: reason_info .reason .code .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: reason_info.reason.reject_reason, status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }) } else { None }; let refund_response_data = RefundsResponseData { connector_refund_id: response.payment_information.references.payment_request_id, refund_status, }; (error, refund_response_data) } fn handle_bank_redirects_refund_sync_error_response( response: ErrorResponseBankRedirect, status_code: u16, ) -> (Option<ErrorResponse>, RefundsResponseData) { let error = Some(ErrorResponse { code: response.payment_result_info.result_code.to_string(), // message vary for the same code, so relying on code alone as it is unique message: response.payment_result_info.result_code.to_string(), reason: response.payment_result_info.additional_info, status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); //unreachable case as we are sending error as Some() let refund_response_data = RefundsResponseData { connector_refund_id: "".to_string(), refund_status: enums::RefundStatus::Failure, }; (error, refund_response_data) } impl<F> TryFrom<RefundsResponseRouterData<F, RefundResponse>> for RefundsRouterData<F> { type Error = Error; fn try_from(item: RefundsResponseRouterData<F, RefundResponse>) -> Result<Self, Self::Error> { let (error, response) = match item.response { RefundResponse::CardsRefund(response) => { handle_cards_refund_response(*response, item.http_code)? } RefundResponse::WebhookRefund(response) => { handle_webhooks_refund_response(*response, item.http_code)? } RefundResponse::BankRedirectRefund(response) => { handle_bank_redirects_refund_response(*response, item.http_code) } RefundResponse::BankRedirectRefundSyncResponse(response) => { handle_bank_redirects_refund_sync_response(*response, item.http_code) } RefundResponse::BankRedirectError(response) => { handle_bank_redirects_refund_sync_error_response(*response, item.http_code) } }; Ok(Self { response: error.map_or_else(|| Ok(response), Err), ..item.data }) } } fn get_refund_status( payment_status: &str, ) -> CustomResult<(enums::RefundStatus, Option<String>), errors::ConnectorError> { let (is_failed, failure_message) = is_payment_failed(payment_status); if payment_status == "000.200.000" { Ok((enums::RefundStatus::Pending, None)) } else if is_failed { Ok(( enums::RefundStatus::Failure, Some(failure_message.to_string()), )) } else if is_payment_successful(payment_status)? { Ok((enums::RefundStatus::Success, None)) } else { Ok((enums::RefundStatus::Pending, None)) } } fn get_refund_status_from_result_info( result_code: i64, ) -> (enums::RefundStatus, Option<&'static str>) { match result_code { 1001000 => (enums::RefundStatus::Success, None), 1130001 => (enums::RefundStatus::Pending, Some("MapiPending")), 1130000 => (enums::RefundStatus::Pending, Some("MapiSuccess")), 1130004 => (enums::RefundStatus::Pending, Some("MapiProcessing")), 1130002 => (enums::RefundStatus::Pending, Some("MapiAnnounced")), 1130003 => (enums::RefundStatus::Pending, Some("MapiAuthorized")), 1130005 => (enums::RefundStatus::Pending, Some("MapiAuthorizedOnly")), 1112008 => (enums::RefundStatus::Failure, Some("InvalidPaymentState")), 1112009 => (enums::RefundStatus::Failure, Some("RefundRejected")), 1122006 => ( enums::RefundStatus::Failure, Some("AccountCurrencyNotAllowed"), ), 1132000 => (enums::RefundStatus::Failure, Some("InvalidMapiRequest")), 1132001 => (enums::RefundStatus::Failure, Some("UnknownAccount")), 1132002 => ( enums::RefundStatus::Failure, Some("MerchantAccountDisabled"), ), 1132003 => (enums::RefundStatus::Failure, Some("InvalidSign")), 1132004 => (enums::RefundStatus::Failure, Some("DisposableBalance")), 1132005 => (enums::RefundStatus::Failure, Some("TransactionNotFound")), 1132006 => (enums::RefundStatus::Failure, Some("UnsupportedTransaction")), 1132007 => (enums::RefundStatus::Failure, Some("GeneralMapiError")), 1132008 => ( enums::RefundStatus::Failure, Some("UnsupportedCurrencyConversion"), ), 1132009 => (enums::RefundStatus::Failure, Some("UnknownMandate")), 1132010 => (enums::RefundStatus::Failure, Some("CanceledMandate")), 1132011 => (enums::RefundStatus::Failure, Some("MissingCid")), 1132012 => (enums::RefundStatus::Failure, Some("MandateAlreadyPaid")), 1132013 => (enums::RefundStatus::Failure, Some("AccountIsTesting")), 1132014 => (enums::RefundStatus::Failure, Some("RequestThrottled")), 1133000 => (enums::RefundStatus::Failure, Some("InvalidAuthentication")), 1133001 => (enums::RefundStatus::Failure, Some("ServiceNotAllowed")), 1133002 => (enums::RefundStatus::Failure, Some("PaymentRequestNotFound")), 1133003 => (enums::RefundStatus::Failure, Some("UnexpectedGateway")), 1133004 => (enums::RefundStatus::Failure, Some("MissingExternalId")), 1152000 => (enums::RefundStatus::Failure, Some("RiskDecline")), _ => (enums::RefundStatus::Pending, None), } } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct TrustpayRedirectResponse { pub status: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct Errors { pub code: i64, pub description: String, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct TrustpayErrorResponse { pub status: i64, pub description: Option<String>, pub errors: Option<Vec<Errors>>, pub instance_id: Option<String>, pub payment_description: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "UPPERCASE")] pub enum CreditDebitIndicator { Crdt, Dbit, } #[derive(strum::Display, Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum WebhookStatus { Paid, Rejected, Refunded, Chargebacked, #[serde(other)] Unknown, } impl TryFrom<WebhookStatus> for enums::AttemptStatus { type Error = errors::ConnectorError; fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> { match item { WebhookStatus::Paid => Ok(Self::Charged), WebhookStatus::Rejected => Ok(Self::AuthorizationFailed), _ => Err(errors::ConnectorError::WebhookEventTypeNotFound), } } } impl TryFrom<WebhookStatus> for enums::RefundStatus { type Error = errors::ConnectorError; fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> { match item { WebhookStatus::Paid => Ok(Self::Success), WebhookStatus::Refunded => Ok(Self::Success), WebhookStatus::Rejected => Ok(Self::Failure), _ => Err(errors::ConnectorError::WebhookEventTypeNotFound), } } } #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "PascalCase")] pub struct WebhookReferences { pub merchant_reference: Option<String>, pub payment_id: Option<String>, pub payment_request_id: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct WebhookAmount { pub amount: FloatMajorUnit, pub currency: enums::Currency, }
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs#chunk1
hyperswitch_connectors
chunk
null
null
null
8,183
null
null
null
null
null
null
null
// Struct: DwollaPaymentsRequest // File: crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct DwollaPaymentsRequest
crates/hyperswitch_connectors/src/connectors/dwolla/transformers.rs
hyperswitch_connectors
struct_definition
DwollaPaymentsRequest
0
[]
50
null
null
null
null
null
null
null
// Function: update // File: crates/diesel_models/src/query/address.rs // Module: diesel_models pub fn update( self, conn: &PgPooledConn, address_update_internal: AddressUpdateInternal, ) -> StorageResult<Self>
crates/diesel_models/src/query/address.rs
diesel_models
function_signature
null
null
null
55
update
null
null
null
null
null
null
// Function: get_invoice_handler // File: crates/router/src/core/subscription.rs // Module: router pub fn get_invoice_handler(&self) -> errors::RouterResult<InvoiceHandler>
crates/router/src/core/subscription.rs
router
function_signature
null
null
null
40
get_invoice_handler
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/authipay.rs // Module: hyperswitch_connectors // Public functions: 2 // Public structs: 1 pub mod transformers; use std::sync::LazyLock; use base64::Engine; use common_enums::enums; use common_utils::{ errors::CustomResult, ext_traits::BytesExt, request::{Method, Request, RequestBuilder, RequestContent}, types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector}, }; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::{ access_token_auth::AccessTokenAuth, payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void}, refunds::{Execute, RSync}, }, router_request_types::{ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::{ExposeInterface, Mask, PeekInterface}; use transformers as authipay; use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Authipay { amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync), } impl Authipay { pub fn new() -> &'static Self { &Self { amount_converter: &FloatMajorUnitForConnector, } } pub fn generate_authorization_signature( &self, auth: authipay::AuthipayAuthType, request_id: &str, payload: &str, timestamp: i128, ) -> CustomResult<String, errors::ConnectorError> { let authipay::AuthipayAuthType { api_key, api_secret, } = auth; let raw_signature = format!("{}{request_id}{timestamp}{payload}", api_key.peek()); let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, api_secret.expose().as_bytes()); let signature_value = common_utils::consts::BASE64_ENGINE .encode(ring::hmac::sign(&key, raw_signature.as_bytes()).as_ref()); Ok(signature_value) } } impl api::Payment for Authipay {} impl api::PaymentSession for Authipay {} impl api::ConnectorAccessToken for Authipay {} impl api::MandateSetup for Authipay {} impl api::PaymentAuthorize for Authipay {} impl api::PaymentSync for Authipay {} impl api::PaymentCapture for Authipay {} impl api::PaymentVoid for Authipay {} impl api::Refund for Authipay {} impl api::RefundExecute for Authipay {} impl api::RefundSync for Authipay {} impl api::PaymentToken for Authipay {} impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Authipay { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Authipay where Self: ConnectorIntegration<Flow, Request, Response>, { fn build_headers( &self, req: &RouterData<Flow, Request, Response>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let timestamp = time::OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000; let auth: authipay::AuthipayAuthType = authipay::AuthipayAuthType::try_from(&req.connector_auth_type)?; let mut auth_header = self.get_auth_header(&req.connector_auth_type)?; let authipay_req = self.get_request_body(req, connectors)?; let client_request_id = uuid::Uuid::new_v4().to_string(); let hmac = self .generate_authorization_signature( auth, &client_request_id, authipay_req.get_inner_value().peek(), timestamp, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let mut headers = vec![ ( headers::CONTENT_TYPE.to_string(), types::PaymentsAuthorizeType::get_content_type(self) .to_string() .into(), ), ("Client-Request-Id".to_string(), client_request_id.into()), ("Auth-Token-Type".to_string(), "HMAC".to_string().into()), (headers::TIMESTAMP.to_string(), timestamp.to_string().into()), ("Message-Signature".to_string(), hmac.into_masked()), ]; headers.append(&mut auth_header); Ok(headers) } } impl ConnectorCommon for Authipay { fn id(&self) -> &'static str { "authipay" } fn get_currency_unit(&self) -> api::CurrencyUnit { api::CurrencyUnit::Base } fn common_get_content_type(&self) -> &'static str { "application/json" } fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str { connectors.authipay.base_url.as_ref() } fn get_auth_header( &self, auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { let auth = authipay::AuthipayAuthType::try_from(auth_type) .change_context(errors::ConnectorError::FailedToObtainAuthType)?; Ok(vec![( headers::API_KEY.to_string(), auth.api_key.into_masked(), )]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: authipay::AuthipayErrorResponse = res .response .parse_struct("AuthipayErrorResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_error_response_body(&response)); let mut error_response = ErrorResponse::from(&response); // Set status code from the response, or 400 if error code is a "404" if let Some(error_code) = &response.error.code { if error_code == "404" { error_response.status_code = 404; } else { error_response.status_code = res.status_code; } } else { error_response.status_code = res.status_code; } Ok(error_response) } } impl ConnectorValidation for Authipay { fn validate_connector_against_payment_request( &self, capture_method: Option<enums::CaptureMethod>, _payment_method: enums::PaymentMethod, _pmt: Option<enums::PaymentMethodType>, ) -> CustomResult<(), errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); match capture_method { enums::CaptureMethod::Automatic | enums::CaptureMethod::Manual | enums::CaptureMethod::SequentialAutomatic => Ok(()), enums::CaptureMethod::Scheduled | enums::CaptureMethod::ManualMultiple => Err( utils::construct_not_implemented_error_report(capture_method, self.id()), ), } } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Authipay { //TODO: implement sessions flow } impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Authipay {} impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Authipay { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Authipay { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!("{}payments", self.base_url(connectors))) } fn get_request_body( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount, req.request.currency, )?; let connector_router_data = authipay::AuthipayRouterData::from((amount, req)); let connector_req = authipay::AuthipayPaymentsRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsAuthorizeType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsAuthorizeType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsAuthorizeRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { let response: authipay::AuthipayPaymentsResponse = res .response .parse_struct("Authipay PaymentsAuthorizeResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Authipay { fn get_headers( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_transaction_id = req .request .connector_transaction_id .get_connector_transaction_id() .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(format!( "{}payments/{}", self.base_url(connectors), connector_transaction_id )) } fn get_request_body( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Ok(RequestContent::RawBytes(Vec::new())) } fn build_request( &self, req: &PaymentsSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &PaymentsSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> { let response: authipay::AuthipayPaymentsResponse = res .response .parse_struct("authipay PaymentsSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Authipay { fn get_headers( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_transaction_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}payments/{}", self.base_url(connectors), connector_transaction_id )) } fn get_request_body( &self, req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let amount = utils::convert_amount( self.amount_converter, req.request.minor_amount_to_capture, req.request.currency, )?; let connector_router_data = authipay::AuthipayRouterData::from((amount, req)); let connector_req = authipay::AuthipayCaptureRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCaptureRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsCaptureType::get_headers( self, req, connectors, )?) .set_body(types::PaymentsCaptureType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCaptureRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> { let response: authipay::AuthipayPaymentsResponse = res .response .parse_struct("Authipay PaymentsCaptureResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Authipay { fn get_headers( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { // For void operations, Authipay requires using the /orders/{orderId} endpoint // The orderId should be stored in connector_meta from the authorization response let order_id = req .request .connector_meta .as_ref() .and_then(|meta| meta.get("order_id")) .and_then(|v| v.as_str()) .ok_or(errors::ConnectorError::RequestEncodingFailed)?; Ok(format!("{}orders/{}", self.base_url(connectors), order_id)) } fn get_request_body( &self, req: &PaymentsCancelRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { // For void, we don't need amount conversion since it's always full amount let connector_router_data = authipay::AuthipayRouterData::from((FloatMajorUnit::zero(), req)); let connector_req = authipay::AuthipayVoidRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &PaymentsCancelRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Post) .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) .set_body(types::PaymentsVoidType::get_request_body( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsCancelRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> { let response: authipay::AuthipayPaymentsResponse = res .response .parse_struct("Authipay PaymentsVoidResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Authipay { fn get_headers( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let connector_payment_id = req.request.connector_transaction_id.clone(); Ok(format!( "{}payments/{}", self.base_url(connectors), connector_payment_id )) } fn get_request_body( &self, req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let refund_amount = utils::convert_amount( self.amount_converter, req.request.minor_refund_amount, req.request.currency, )?; let connector_router_data = authipay::AuthipayRouterData::from((refund_amount, req)); let connector_req = authipay::AuthipayRefundRequest::try_from(&connector_router_data)?; Ok(RequestContent::Json(Box::new(connector_req))) } fn build_request( &self, req: &RefundsRouterData<Execute>, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundExecuteType::get_headers( self, req, connectors, )?) .set_body(types::RefundExecuteType::get_request_body( self, req, connectors, )?) .build(); Ok(Some(request)) } fn handle_response( &self, data: &RefundsRouterData<Execute>, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> { let response: authipay::RefundResponse = res .response .parse_struct("authipay RefundResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Authipay { fn get_headers( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { self.build_headers(req, connectors) } fn get_content_type(&self) -> &'static str { self.common_get_content_type() } fn get_url( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let refund_id = req .request .connector_refund_id .clone() .ok_or(errors::ConnectorError::RequestEncodingFailed)?; Ok(format!( "{}payments/{}", self.base_url(connectors), refund_id )) } fn get_request_body( &self, _req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { Ok(RequestContent::RawBytes(Vec::new())) } fn build_request( &self, req: &RefundSyncRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::RefundSyncType::get_url(self, req, connectors)?) .attach_default_headers() .headers(types::RefundSyncType::get_headers(self, req, connectors)?) .build(), )) } fn handle_response( &self, data: &RefundSyncRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> { let response: authipay::RefundResponse = res .response .parse_struct("authipay RefundSyncResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); RouterData::try_from(ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } fn get_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { self.build_error_response(res, event_builder) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Authipay { fn get_webhook_object_reference_id( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_event_type( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } fn get_webhook_resource_object( &self, _request: &webhooks::IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> { Err(report!(errors::ConnectorError::WebhooksNotImplemented)) } } static AUTHIPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![ enums::CaptureMethod::Automatic, enums::CaptureMethod::SequentialAutomatic, enums::CaptureMethod::Manual, ]; let supported_card_network = vec![ common_enums::CardNetwork::Visa, common_enums::CardNetwork::Mastercard, ]; let mut authipay_supported_payment_methods = SupportedPaymentMethods::new(); authipay_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Credit, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); authipay_supported_payment_methods.add( enums::PaymentMethod::Card, enums::PaymentMethodType::Debit, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::Supported, supported_capture_methods: supported_capture_methods.clone(), specific_features: Some( api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({ api_models::feature_matrix::CardSpecificFeatures { three_ds: common_enums::FeatureStatus::NotSupported, no_three_ds: common_enums::FeatureStatus::Supported, supported_card_networks: supported_card_network.clone(), } }), ), }, ); authipay_supported_payment_methods }); static AUTHIPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Authipay", description: "Authipay is a Fiserv-powered payment gateway for the EMEA region supporting Visa and Mastercard transactions. Features include flexible capture methods (automatic, manual, sequential), partial captures/refunds, payment tokenization, and secure HMAC SHA256 authentication.", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Sandbox, }; static AUTHIPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; impl ConnectorSpecifications for Authipay { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&AUTHIPAY_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*AUTHIPAY_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&AUTHIPAY_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/authipay.rs
hyperswitch_connectors
full_file
null
null
null
6,326
null
null
null
null
null
null
null
// Function: unify_with_payment_method_data_billing // File: crates/hyperswitch_domain_models/src/payment_address.rs // Module: hyperswitch_domain_models // Documentation: Here the fields passed in payment_method_data_billing takes precedence pub fn unify_with_payment_method_data_billing( self, payment_method_data_billing: Option<Address>, ) -> Self
crates/hyperswitch_domain_models/src/payment_address.rs
hyperswitch_domain_models
function_signature
null
null
null
73
unify_with_payment_method_data_billing
null
null
null
null
null
null
// Implementation: impl behaviour::Conversion for for PaymentAttempt // File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs // Module: hyperswitch_domain_models // Methods: 3 total (0 public) impl behaviour::Conversion for for PaymentAttempt
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
hyperswitch_domain_models
impl_block
null
null
null
55
null
PaymentAttempt
behaviour::Conversion for
3
0
null
null
// Function: read // File: crates/hsdev/src/input_file.rs // Module: hsdev pub fn read(db_table: &Value) -> Result<Self, toml::de::Error>
crates/hsdev/src/input_file.rs
hsdev
function_signature
null
null
null
43
read
null
null
null
null
null
null
// Implementation: impl Digitalvirgo // File: crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl Digitalvirgo
crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
hyperswitch_connectors
impl_block
null
null
null
49
null
Digitalvirgo
null
1
1
null
null
// Function: check_tenant // File: crates/router/src/services/authorization.rs // Module: router pub fn check_tenant( token_tenant_id: Option<id_type::TenantId>, header_tenant_id: &id_type::TenantId, ) -> RouterResult<()>
crates/router/src/services/authorization.rs
router
function_signature
null
null
null
61
check_tenant
null
null
null
null
null
null
// Function: delete_gsm_rule // File: crates/openapi/src/routes/gsm.rs // Module: openapi pub fn delete_gsm_rule()
crates/openapi/src/routes/gsm.rs
openapi
function_signature
null
null
null
33
delete_gsm_rule
null
null
null
null
null
null
// Function: add_refund_sync_task // File: crates/router/src/core/refunds.rs // Module: router pub fn add_refund_sync_task( db: &dyn db::StorageInterface, refund: &diesel_refund::Refund, runner: storage::ProcessTrackerRunner, ) -> RouterResult<storage::ProcessTracker>
crates/router/src/core/refunds.rs
router
function_signature
null
null
null
74
add_refund_sync_task
null
null
null
null
null
null
// Implementation: impl OrganizationNew // File: crates/api_models/src/organization.rs // Module: api_models // Methods: 1 total (1 public) impl OrganizationNew
crates/api_models/src/organization.rs
api_models
impl_block
null
null
null
37
null
OrganizationNew
null
1
1
null
null
// Implementation: impl api::PaymentSync for for Gigadat // File: crates/hyperswitch_connectors/src/connectors/gigadat.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSync for for Gigadat
crates/hyperswitch_connectors/src/connectors/gigadat.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Gigadat
api::PaymentSync for
0
0
null
null
// Trait: Feature // File: crates/router/src/core/payments/flows.rs // Module: router pub trait Feature<F, T>
crates/router/src/core/payments/flows.rs
router
trait_definition
null
null
null
30
null
null
Feature
null
null
null
null
// Struct: IncrementalAuthorizationDetails // File: crates/router/src/core/payments.rs // Module: router // Implementations: 0 pub struct IncrementalAuthorizationDetails
crates/router/src/core/payments.rs
router
struct_definition
IncrementalAuthorizationDetails
0
[]
37
null
null
null
null
null
null
null
// Function: update_connector // File: crates/router/src/core/admin.rs // Module: router pub fn update_connector( state: SessionState, merchant_id: &id_type::MerchantId, profile_id: Option<id_type::ProfileId>, merchant_connector_id: &id_type::MerchantConnectorAccountId, req: api_models::admin::MerchantConnectorUpdate, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse>
crates/router/src/core/admin.rs
router
function_signature
null
null
null
94
update_connector
null
null
null
null
null
null
// Function: generate_permissions // File: crates/router_derive/src/lib.rs // Module: router_derive pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream
crates/router_derive/src/lib.rs
router_derive
function_signature
null
null
null
42
generate_permissions
null
null
null
null
null
null
// Implementation: impl api::ConnectorAccessToken for for Itaubank // File: crates/hyperswitch_connectors/src/connectors/itaubank.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::ConnectorAccessToken for for Itaubank
crates/hyperswitch_connectors/src/connectors/itaubank.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Itaubank
api::ConnectorAccessToken for
0
0
null
null
// File: crates/storage_impl/src/redis/pub_sub.rs // Module: storage_impl use std::sync::atomic; use error_stack::ResultExt; use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue}; use router_env::{logger, tracing::Instrument}; use crate::redis::cache::{ CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, DECISION_MANAGER_CACHE, ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE, SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE, }; #[async_trait::async_trait] pub trait PubSubInterface { async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError>; async fn publish<'a>( &self, channel: &str, key: CacheKind<'a>, ) -> error_stack::Result<usize, redis_errors::RedisError>; async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError>; } #[async_trait::async_trait] impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> { #[inline] async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> { // Spawns a task that will automatically re-subscribe to any channels or channel patterns used by the client. self.subscriber.manage_subscriptions(); self.subscriber .subscribe::<(), &str>(channel) .await .change_context(redis_errors::RedisError::SubscribeError)?; // Spawn only one thread handling all the published messages to different channels if self .subscriber .is_subscriber_handler_spawned .compare_exchange( false, true, atomic::Ordering::SeqCst, atomic::Ordering::SeqCst, ) .is_ok() { let redis_clone = self.clone(); let _task_handle = tokio::spawn( async move { if let Err(pubsub_error) = redis_clone.on_message().await { logger::error!(?pubsub_error); } } .in_current_span(), ); } Ok(()) } #[inline] async fn publish<'a>( &self, channel: &str, key: CacheKind<'a>, ) -> error_stack::Result<usize, redis_errors::RedisError> { let key = CacheRedact { kind: key, tenant: self.key_prefix.clone(), }; self.publisher .publish( channel, RedisValue::try_from(key).change_context(redis_errors::RedisError::PublishError)?, ) .await .change_context(redis_errors::RedisError::SubscribeError) } #[inline] async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> { logger::debug!("Started on message"); let mut rx = self.subscriber.on_message(); while let Ok(message) = rx.recv().await { let channel_name = message.channel.to_string(); logger::debug!("Received message on channel: {channel_name}"); match channel_name.as_str() { super::cache::IMC_INVALIDATION_CHANNEL => { let message = match CacheRedact::try_from(RedisValue::new(message.value)) .change_context(redis_errors::RedisError::OnMessageError) { Ok(value) => value, Err(err) => { logger::error!(value_conversion_err=?err); continue; } }; let key = match message.kind { CacheKind::Config(key) => { CONFIG_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Accounts(key) => { ACCOUNTS_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::CGraph(key) => { CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::PmFiltersCGraph(key) => { PM_FILTERS_CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::EliminationBasedDynamicRoutingCache(key) => { ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::ContractBasedDynamicRoutingCache(key) => { CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::SuccessBasedDynamicRoutingCache(key) => { SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Routing(key) => { ROUTING_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::DecisionManager(key) => { DECISION_MANAGER_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::Surcharge(key) => { SURCHARGE_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } CacheKind::All(key) => { CONFIG_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ACCOUNTS_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; PM_FILTERS_CGRAPH_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; ROUTING_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; DECISION_MANAGER_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; SURCHARGE_CACHE .remove(CacheKey { key: key.to_string(), prefix: message.tenant.clone(), }) .await; key } }; logger::debug!( key_prefix=?message.tenant.clone(), channel_name=?channel_name, "Done invalidating {key}" ); } _ => { logger::debug!("Received message from unknown channel: {channel_name}"); } } } Ok(()) } }
crates/storage_impl/src/redis/pub_sub.rs
storage_impl
full_file
null
null
null
1,729
null
null
null
null
null
null
null
// File: crates/hyperswitch_domain_models/src/router_response_types/disputes.rs // Module: hyperswitch_domain_models // Public structs: 5 #[derive(Default, Clone, Debug)] pub struct AcceptDisputeResponse { pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: Option<String>, } #[derive(Default, Clone, Debug)] pub struct SubmitEvidenceResponse { pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: Option<String>, } #[derive(Default, Debug, Clone)] pub struct DefendDisputeResponse { pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: Option<String>, } pub struct FileInfo { pub file_data: Option<Vec<u8>>, pub provider_file_id: Option<String>, pub file_type: Option<String>, } #[derive(serde::Serialize, serde::Deserialize, Clone, Debug)] pub struct DisputeSyncResponse { pub object_reference_id: api_models::webhooks::ObjectReferenceId, pub amount: common_utils::types::StringMinorUnit, pub currency: common_enums::enums::Currency, pub dispute_stage: common_enums::enums::DisputeStage, pub dispute_status: api_models::enums::DisputeStatus, pub connector_status: String, pub connector_dispute_id: String, pub connector_reason: Option<String>, pub connector_reason_code: Option<String>, pub challenge_required_by: Option<time::PrimitiveDateTime>, pub created_at: Option<time::PrimitiveDateTime>, pub updated_at: Option<time::PrimitiveDateTime>, } pub type FetchDisputesResponse = Vec<DisputeSyncResponse>;
crates/hyperswitch_domain_models/src/router_response_types/disputes.rs
hyperswitch_domain_models
full_file
null
null
null
358
null
null
null
null
null
null
null
// File: crates/router/src/core/revenue_recovery/types.rs // Module: router // Public functions: 9 // Public structs: 1 use std::{marker::PhantomData, str::FromStr}; use api_models::{ enums as api_enums, payments::{ AmountDetails, PaymentRevenueRecoveryMetadata, PaymentsUpdateIntentRequest, ProxyPaymentsRequest, }, }; use common_utils::{ self, ext_traits::{OptionExt, ValueExt}, id_type, }; use diesel_models::{ enums, payment_intent, process_tracker::business_status, types as diesel_types, }; use error_stack::{self, ResultExt}; use hyperswitch_domain_models::{ api::ApplicationResponse, business_profile, merchant_connector_account, merchant_context::{Context, MerchantContext}, payments::{ self as domain_payments, payment_attempt::PaymentAttempt, PaymentConfirmData, PaymentIntent, PaymentIntentData, PaymentStatusData, }, router_data_v2::{self, flow_common_types}, router_flow_types, router_request_types::revenue_recovery as revenue_recovery_request, router_response_types::revenue_recovery as revenue_recovery_response, ApiModelToDieselModelConvertor, }; use time::PrimitiveDateTime; use super::errors::StorageErrorExt; use crate::{ core::{ errors::{self, RouterResult}, payments::{self, helpers, operations::Operation, transformers::GenerateResponse}, revenue_recovery::{self as revenue_recovery_core, pcr, perform_calculate_workflow}, webhooks::{ create_event_and_trigger_outgoing_webhook, recovery_incoming as recovery_incoming_flow, }, }, db::StorageInterface, logger, routes::SessionState, services::{self, connector_integration_interface::RouterDataConversion}, types::{ self, api as api_types, api::payments as payments_types, domain, storage, transformers::ForeignInto, }, workflows::{ payment_sync, revenue_recovery::{self, get_schedule_time_to_retry_mit_payments}, }, }; type RecoveryResult<T> = error_stack::Result<T, errors::RecoveryError>; pub const REVENUE_RECOVERY: &str = "revenue_recovery"; /// The status of Passive Churn Payments #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub enum RevenueRecoveryPaymentsAttemptStatus { Succeeded, Failed, Processing, InvalidStatus(String), // Cancelled, } impl RevenueRecoveryPaymentsAttemptStatus { pub(crate) async fn update_pt_status_based_on_attempt_status_for_execute_payment( &self, db: &dyn StorageInterface, execute_task_process: &storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { logger::info!("Entering update_pt_status_based_on_attempt_status_for_execute_payment"); match &self { Self::Succeeded | Self::Failed | Self::Processing => { // finish the current execute task db.finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, ) .await?; } Self::InvalidStatus(action) => { logger::debug!( "Invalid Attempt Status for the Recovery Payment : {}", action ); let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Review, business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)), }; // update the process tracker status as Review db.update_process(execute_task_process.clone(), pt_update) .await?; } }; Ok(()) } #[allow(clippy::too_many_arguments)] pub(crate) async fn update_pt_status_based_on_attempt_status_for_payments_sync( &self, state: &SessionState, payment_intent: &PaymentIntent, process_tracker: storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_attempt: PaymentAttempt, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, ) -> Result<(), errors::ProcessTrackerError> { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; let db = &*state.store; let recovery_payment_intent = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( payment_intent, ); let recovery_payment_attempt = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( &payment_attempt, ); let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( &recovery_payment_intent, &recovery_payment_attempt, ); let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt); let retry_count = process_tracker.retry_count; let psync_response = revenue_recovery_payment_data .psync_data .as_ref() .ok_or(errors::RecoveryError::ValueNotFound) .attach_printable("Psync data not found in revenue recovery payment data")?; match self { Self::Succeeded => { // finish psync task as the payment was a success db.as_scheduler() .finish_process_with_business_status( process_tracker, business_status::PSYNC_WORKFLOW_COMPLETE, ) .await?; let event_status = common_enums::EventType::PaymentSucceeded; // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, &recovery_payment_tuple, Some(retry_count+1) ) .await{ router_env::logger::error!( "Failed to publish revenue recovery event to kafka: {:?}", e ); }; // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &None, // Since this is succeeded payment attempt, 'is_hard_decine' will be false. &Some(false), used_token.as_deref(), ) .await; // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; let payments_response = psync_response .clone() .generate_response(state, None, None, None, &merchant_context, profile, None) .change_context(errors::RecoveryError::PaymentsResponseGenerationFailed) .attach_printable("Failed while generating response for payment")?; RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( state, common_enums::EventClass::Payments, event_status, payment_intent, &merchant_context, profile, recovery_payment_attempt .attempt_id .get_string_repr() .to_string(), payments_response ) .await?; // Record a successful transaction back to Billing Connector // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( state, &payment_attempt, payment_intent, &revenue_recovery_payment_data.billing_mca, ) .await .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Failed to update the process tracker")?; } Self::Failed => { // finish psync task db.as_scheduler() .finish_process_with_business_status( process_tracker.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await?; // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, &recovery_payment_tuple, Some(retry_count+1) ) .await{ router_env::logger::error!( "Failed to publish revenue recovery event to kafka : {:?}", e ); }; let error_code = recovery_payment_attempt.error_code; let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt) .await .ok(); // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &error_code, &is_hard_decline, used_token.as_deref(), ) .await; // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; // Reopen calculate workflow on payment failure Box::pin(reopen_calculate_workflow_on_payment_failure( state, &process_tracker, profile, merchant_context, payment_intent, revenue_recovery_payment_data, psync_response.payment_attempt.get_id(), )) .await?; } Self::Processing => { // do a psync payment let action = Box::pin(Action::payment_sync_call( state, revenue_recovery_payment_data, payment_intent, &process_tracker, profile, merchant_context, payment_attempt, )) .await?; //handle the response Box::pin(action.psync_response_handler( state, payment_intent, &process_tracker, revenue_recovery_metadata, revenue_recovery_payment_data, )) .await?; } Self::InvalidStatus(status) => logger::debug!( "Invalid Attempt Status for the Recovery Payment : {}", status ), } Ok(()) } } pub enum Decision { Execute, Psync(enums::AttemptStatus, id_type::GlobalAttemptId), InvalidDecision, ReviewForSuccessfulPayment, ReviewForFailedPayment(enums::TriggeredBy), } impl Decision { pub async fn get_decision_based_on_params( state: &SessionState, intent_status: enums::IntentStatus, called_connector: enums::PaymentConnectorTransmission, active_attempt_id: Option<id_type::GlobalAttemptId>, revenue_recovery_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_id: &id_type::GlobalPaymentId, ) -> RecoveryResult<Self> { logger::info!("Entering get_decision_based_on_params"); Ok(match (intent_status, called_connector, active_attempt_id) { ( enums::IntentStatus::Failed, enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, None, ) => Self::Execute, ( enums::IntentStatus::Processing, enums::PaymentConnectorTransmission::ConnectorCallSucceeded, Some(_), ) => { let psync_data = revenue_recovery_core::api::call_psync_api( state, payment_id, revenue_recovery_data, true, true, ) .await .change_context(errors::RecoveryError::PaymentCallFailed) .attach_printable("Error while executing the Psync call")?; let payment_attempt = psync_data.payment_attempt; Self::Psync(payment_attempt.status, payment_attempt.get_id().clone()) } ( enums::IntentStatus::Failed, enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, Some(_), ) => { let psync_data = revenue_recovery_core::api::call_psync_api( state, payment_id, revenue_recovery_data, true, true, ) .await .change_context(errors::RecoveryError::PaymentCallFailed) .attach_printable("Error while executing the Psync call")?; let payment_attempt = psync_data.payment_attempt; let attempt_triggered_by = payment_attempt .feature_metadata .and_then(|metadata| { metadata.revenue_recovery.map(|revenue_recovery_metadata| { revenue_recovery_metadata.attempt_triggered_by }) }) .get_required_value("Attempt Triggered By") .change_context(errors::RecoveryError::ValueNotFound)?; Self::ReviewForFailedPayment(attempt_triggered_by) } (enums::IntentStatus::Succeeded, _, _) => Self::ReviewForSuccessfulPayment, _ => Self::InvalidDecision, }) } } #[derive(Debug, Clone)] pub enum Action { SyncPayment(PaymentAttempt), RetryPayment(PrimitiveDateTime), TerminalFailure(PaymentAttempt), SuccessfulPayment(PaymentAttempt), ReviewPayment, ManualReviewAction, } impl Action { #[allow(clippy::too_many_arguments)] pub async fn execute_payment( state: &SessionState, _merchant_id: &id_type::MerchantId, payment_intent: &PaymentIntent, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata, latest_attempt_id: &id_type::GlobalAttemptId, ) -> RecoveryResult<Self> { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; let tracking_data: pcr::RevenueRecoveryWorkflowTrackingData = serde_json::from_value(process.tracking_data.clone()) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to deserialize the tracking data from process tracker")?; let last_token_used = payment_intent .feature_metadata .as_ref() .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref()) .map(|rr| { rr.billing_connector_payment_details .payment_processor_token .clone() }); let recovery_algorithm = tracking_data.revenue_recovery_retry; let scheduled_token = match storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type( state, &connector_customer_id, recovery_algorithm, last_token_used.as_deref(), ) .await { Ok(scheduled_token_opt) => scheduled_token_opt, Err(e) => { logger::error!( error = ?e, connector_customer_id = %connector_customer_id, "Failed to get PSP token status" ); None } }; match scheduled_token { Some(scheduled_token) => { let response = revenue_recovery_core::api::call_proxy_api( state, payment_intent, revenue_recovery_payment_data, revenue_recovery_metadata, &scheduled_token .payment_processor_token_details .payment_processor_token, ) .await; let recovery_payment_intent = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from( payment_intent, ); // handle proxy api's response match response { Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() { RevenueRecoveryPaymentsAttemptStatus::Succeeded => { let recovery_payment_attempt = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( &payment_data.payment_attempt, ); let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( &recovery_payment_intent, &recovery_payment_attempt, ); // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, &recovery_payment_tuple, Some(process.retry_count+1) ) .await{ router_env::logger::error!( "Failed to publish revenue recovery event to kafka: {:?}", e ); }; let is_hard_decline = revenue_recovery::check_hard_decline( state, &payment_data.payment_attempt, ) .await .ok(); // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &None, &is_hard_decline, Some(&scheduled_token.payment_processor_token_details.payment_processor_token), ) .await; // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; let event_status = common_enums::EventType::PaymentSucceeded; let payments_response = payment_data .clone() .generate_response( state, None, None, None, &merchant_context, profile, None, ) .change_context( errors::RecoveryError::PaymentsResponseGenerationFailed, ) .attach_printable("Failed while generating response for payment")?; RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status( state, common_enums::EventClass::Payments, event_status, payment_intent, &merchant_context, profile, payment_data.payment_attempt.id.get_string_repr().to_string(), payments_response ) .await?; Ok(Self::SuccessfulPayment( payment_data.payment_attempt.clone(), )) } RevenueRecoveryPaymentsAttemptStatus::Failed => { let recovery_payment_attempt = hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from( &payment_data.payment_attempt, ); let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new( &recovery_payment_intent, &recovery_payment_attempt, ); // publish events to kafka if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka( state, &recovery_payment_tuple, Some(process.retry_count+1) ) .await{ router_env::logger::error!( "Failed to publish revenue recovery event to kafka: {:?}", e ); }; let error_code = payment_data .payment_attempt .clone() .error .map(|error| error.code); let is_hard_decline = revenue_recovery::check_hard_decline( state, &payment_data.payment_attempt, ) .await .ok(); let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &error_code, &is_hard_decline, Some(&scheduled_token .payment_processor_token_details .payment_processor_token) , ) .await; // unlocking the token let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; // Reopen calculate workflow on payment failure Box::pin(reopen_calculate_workflow_on_payment_failure( state, process, profile, merchant_context, payment_intent, revenue_recovery_payment_data, latest_attempt_id, )) .await?; // Return terminal failure to finish the current execute workflow Ok(Self::TerminalFailure(payment_data.payment_attempt.clone())) } RevenueRecoveryPaymentsAttemptStatus::Processing => { Ok(Self::SyncPayment(payment_data.payment_attempt.clone())) } RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => { logger::info!(?action, "Invalid Payment Status For PCR Payment"); Ok(Self::ManualReviewAction) } }, Err(err) => // check for an active attempt being constructed or not { logger::error!(execute_payment_res=?err); Ok(Self::ReviewPayment) } } } None => { let response = revenue_recovery_core::api::call_psync_api( state, payment_intent.get_id(), revenue_recovery_payment_data, true, true, ) .await; let payment_status_data = response .change_context(errors::RecoveryError::PaymentCallFailed) .attach_printable("Error while executing the Psync call")?; let payment_attempt = payment_status_data.payment_attempt; logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "No token available, finishing CALCULATE_WORKFLOW" ); state .store .as_scheduler() .finish_process_with_business_status( process.clone(), business_status::CALCULATE_WORKFLOW_FINISH, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to finish CALCULATE_WORKFLOW")?; logger::info!( process_id = %process.id, connector_customer_id = %connector_customer_id, "CALCULATE_WORKFLOW finished successfully" ); Ok(Self::TerminalFailure(payment_attempt.clone())) } } } pub async fn execute_payment_task_response_handler( &self, state: &SessionState, payment_intent: &PaymentIntent, execute_task_process: &storage::ProcessTracker, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, ) -> Result<(), errors::ProcessTrackerError> { logger::info!("Entering execute_payment_task_response_handler"); let db = &*state.store; match self { Self::SyncPayment(payment_attempt) => { revenue_recovery_core::insert_psync_pcr_task_to_pt( revenue_recovery_payment_data.billing_mca.get_id().clone(), db, revenue_recovery_payment_data .merchant_account .get_id() .to_owned(), payment_intent.id.clone(), revenue_recovery_payment_data.profile.get_id().to_owned(), payment_attempt.id.clone(), storage::ProcessTrackerRunner::PassiveRecoveryWorkflow, revenue_recovery_payment_data.retry_algorithm, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to create a psync workflow in the process tracker")?; db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::RetryPayment(schedule_time) => { db.as_scheduler() .retry_process(execute_task_process.clone(), *schedule_time) .await?; // update the connector payment transmission field to Unsuccessful and unset active attempt id revenue_recovery_metadata.set_payment_transmission_field_for_api_request( enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful, ); let payment_update_req = PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api( payment_intent .feature_metadata .clone() .unwrap_or_default() .convert_back() .set_payment_revenue_recovery_metadata_using_api( revenue_recovery_metadata.clone(), ), api_enums::UpdateActiveAttempt::Unset, ); logger::info!( "Call made to payments update intent api , with the request body {:?}", payment_update_req ); revenue_recovery_core::api::update_payment_intent_api( state, payment_intent.id.clone(), revenue_recovery_payment_data, payment_update_req, ) .await .change_context(errors::RecoveryError::PaymentCallFailed)?; Ok(()) } Self::TerminalFailure(payment_attempt) => { db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_FAILURE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // TODO: Add support for retrying failed outgoing recordback webhooks Ok(()) } Self::SuccessfulPayment(payment_attempt) => { db.as_scheduler() .finish_process_with_business_status( execute_task_process.clone(), business_status::EXECUTE_WORKFLOW_COMPLETE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // Record back to billing connector for terminal status // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( state, payment_attempt, payment_intent, &revenue_recovery_payment_data.billing_mca, ) .await .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::ReviewPayment => { // requeue the process tracker in case of error response let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)), }; db.as_scheduler() .update_process(execute_task_process.clone(), pt_update) .await?; Ok(()) } Self::ManualReviewAction => { logger::debug!("Invalid Payment Status For PCR Payment"); let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Review, business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)), }; // update the process tracker status as Review db.as_scheduler() .update_process(execute_task_process.clone(), pt_update) .await?; Ok(()) } } } pub async fn payment_sync_call( state: &SessionState, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_intent: &PaymentIntent, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, payment_attempt: PaymentAttempt, ) -> RecoveryResult<Self> { logger::info!("Entering payment_sync_call"); let response = revenue_recovery_core::api::call_psync_api( state, payment_intent.get_id(), revenue_recovery_payment_data, true, true, ) .await; let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt); match response { Ok(_payment_data) => match payment_attempt.status.foreign_into() { RevenueRecoveryPaymentsAttemptStatus::Succeeded => { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; // update the status of token in redis let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &None, // Since this is succeeded, 'hard_decine' will be false. &Some(false), used_token.as_deref(), ) .await; // unlocking the token let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; Ok(Self::SuccessfulPayment(payment_attempt)) } RevenueRecoveryPaymentsAttemptStatus::Failed => { let connector_customer_id = payment_intent .extract_connector_customer_id_from_payment_intent() .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to extract customer ID from payment intent")?; let error_code = payment_attempt.clone().error.map(|error| error.code); let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt) .await .ok(); let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker( state, &connector_customer_id, &error_code, &is_hard_decline, used_token.as_deref(), ) .await; // unlocking the token let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status( state, &connector_customer_id, ) .await; // Reopen calculate workflow on payment failure Box::pin(reopen_calculate_workflow_on_payment_failure( state, process, profile, merchant_context, payment_intent, revenue_recovery_payment_data, payment_attempt.get_id(), )) .await?; Ok(Self::TerminalFailure(payment_attempt.clone())) } RevenueRecoveryPaymentsAttemptStatus::Processing => { Ok(Self::SyncPayment(payment_attempt)) } RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => { logger::info!(?action, "Invalid Payment Status For PCR PSync Payment"); Ok(Self::ManualReviewAction) } }, Err(err) => // if there is an error while psync we create a new Review Task { logger::error!(sync_payment_response=?err); Ok(Self::ReviewPayment) } } } pub async fn psync_response_handler( &self, state: &SessionState, payment_intent: &PaymentIntent, psync_task_process: &storage::ProcessTracker, revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, ) -> Result<(), errors::ProcessTrackerError> { logger::info!("Entering psync_response_handler"); let db = &*state.store; let connector_customer_id = payment_intent .feature_metadata .as_ref() .and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref()) .map(|rr| { rr.billing_connector_payment_details .connector_customer_id .clone() }); match self { Self::SyncPayment(payment_attempt) => { // get a schedule time for psync // and retry the process if there is a schedule time // if None mark the pt status as Retries Exceeded and finish the task payment_sync::recovery_retry_sync_task( state, connector_customer_id, revenue_recovery_metadata.connector.to_string(), revenue_recovery_payment_data .merchant_account .get_id() .clone(), psync_task_process.clone(), ) .await?; Ok(()) } Self::RetryPayment(schedule_time) => { // finish the psync task db.as_scheduler() .finish_process_with_business_status( psync_task_process.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // fetch the execute task let task = revenue_recovery_core::EXECUTE_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let process_tracker_id = payment_intent .get_id() .get_execute_revenue_recovery_id(task, runner); let execute_task_process = db .as_scheduler() .find_process_by_id(&process_tracker_id) .await .change_context(errors::RecoveryError::ProcessTrackerFailure)? .get_required_value("Process Tracker")?; // retry the execute tasks db.as_scheduler() .retry_process(execute_task_process, *schedule_time) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::TerminalFailure(payment_attempt) => { // TODO: Add support for retrying failed outgoing recordback webhooks // finish the current psync task db.as_scheduler() .finish_process_with_business_status( psync_task_process.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::SuccessfulPayment(payment_attempt) => { // finish the current psync task db.as_scheduler() .finish_process_with_business_status( psync_task_process.clone(), business_status::PSYNC_WORKFLOW_COMPLETE, ) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; // Record a successful transaction back to Billing Connector // TODO: Add support for retrying failed outgoing recordback webhooks record_back_to_billing_connector( state, payment_attempt, payment_intent, &revenue_recovery_payment_data.billing_mca, ) .await .change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed) .attach_printable("Failed to update the process tracker")?; Ok(()) } Self::ReviewPayment => { // requeue the process tracker task in case of psync api error let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Pending, business_status: Some(String::from(business_status::PSYNC_WORKFLOW_REQUEUE)), }; db.as_scheduler() .update_process(psync_task_process.clone(), pt_update) .await?; Ok(()) } Self::ManualReviewAction => { logger::debug!("Invalid Payment Status For PCR Payment"); let pt_update = storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Review, business_status: Some(String::from(business_status::PSYNC_WORKFLOW_COMPLETE)), }; // update the process tracker status as Review db.as_scheduler() .update_process(psync_task_process.clone(), pt_update) .await .change_context(errors::RecoveryError::ProcessTrackerFailure) .attach_printable("Failed to update the process tracker")?; Ok(()) } } } pub(crate) async fn decide_retry_failure_action( state: &SessionState, merchant_id: &id_type::MerchantId, pt: storage::ProcessTracker, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> RecoveryResult<Self> { let db = &*state.store; let next_retry_count = pt.retry_count + 1; let error_message = payment_attempt .error .as_ref() .map(|details| details.message.clone()); let error_code = payment_attempt .error .as_ref() .map(|details| details.code.clone()); let connector_name = payment_attempt .connector .clone() .ok_or(errors::RecoveryError::ValueNotFound) .attach_printable("unable to derive payment connector from payment attempt")?; let gsm_record = helpers::get_gsm_record( state, error_code, error_message, connector_name, REVENUE_RECOVERY.to_string(), ) .await; let is_hard_decline = gsm_record .and_then(|gsm_record| gsm_record.error_category) .map(|gsm_error_category| { gsm_error_category == common_enums::ErrorCategory::HardDecline }) .unwrap_or(false); let schedule_time = revenue_recovery_payment_data .get_schedule_time_based_on_retry_type( state, merchant_id, next_retry_count, payment_attempt, payment_intent, is_hard_decline, ) .await; match schedule_time { Some(schedule_time) => Ok(Self::RetryPayment(schedule_time)), None => Ok(Self::TerminalFailure(payment_attempt.clone())), } } } /// Reopen calculate workflow when payment fails pub async fn reopen_calculate_workflow_on_payment_failure( state: &SessionState, process: &storage::ProcessTracker, profile: &domain::Profile, merchant_context: domain::MerchantContext, payment_intent: &PaymentIntent, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, latest_attempt_id: &id_type::GlobalAttemptId, ) -> RecoveryResult<()> { let db = &*state.store; let id = payment_intent.id.clone(); let task = revenue_recovery_core::CALCULATE_WORKFLOW; let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow; let old_tracking_data: pcr::RevenueRecoveryWorkflowTrackingData = serde_json::from_value(process.tracking_data.clone()) .change_context(errors::RecoveryError::ValueNotFound) .attach_printable("Failed to deserialize the tracking data from process tracker")?; let new_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData { payment_attempt_id: latest_attempt_id.clone(), ..old_tracking_data };
crates/router/src/core/revenue_recovery/types.rs#chunk0
router
chunk
null
null
null
8,192
null
null
null
null
null
null
null
// Function: get_connector_metadata // File: crates/hyperswitch_domain_models/src/router_response_types.rs // Module: hyperswitch_domain_models pub fn get_connector_metadata(&self) -> Option<masking::Secret<serde_json::Value>>
crates/hyperswitch_domain_models/src/router_response_types.rs
hyperswitch_domain_models
function_signature
null
null
null
52
get_connector_metadata
null
null
null
null
null
null
// Function: retrieve_default_routing_config // File: crates/router/src/core/routing.rs // Module: router pub fn retrieve_default_routing_config( state: SessionState, profile_id: Option<common_utils::id_type::ProfileId>, merchant_context: domain::MerchantContext, transaction_type: &enums::TransactionType, ) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>>
crates/router/src/core/routing.rs
router
function_signature
null
null
null
86
retrieve_default_routing_config
null
null
null
null
null
null
// Function: construct_invoice_record_back_router_data // File: crates/router/src/core/revenue_recovery/types.rs // Module: router pub fn construct_invoice_record_back_router_data( state: &SessionState, billing_mca: &merchant_connector_account::MerchantConnectorAccount, payment_attempt: &PaymentAttempt, payment_intent: &PaymentIntent, ) -> RecoveryResult<hyperswitch_domain_models::types::InvoiceRecordBackRouterData>
crates/router/src/core/revenue_recovery/types.rs
router
function_signature
null
null
null
93
construct_invoice_record_back_router_data
null
null
null
null
null
null
// Implementation: impl events::ApiEventMetric for for DecisionManagerRequest // File: crates/api_models/src/conditional_configs.rs // Module: api_models // Methods: 1 total (0 public) impl events::ApiEventMetric for for DecisionManagerRequest
crates/api_models/src/conditional_configs.rs
api_models
impl_block
null
null
null
54
null
DecisionManagerRequest
events::ApiEventMetric for
1
0
null
null
// Function: handle_webhook_response // File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors pub fn handle_webhook_response( payment_information: WebhookPaymentInformation, status_code: u16, ) -> CustomResult< ( enums::AttemptStatus, Option<ErrorResponse>, PaymentsResponseData, ), errors::ConnectorError, >
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
function_signature
null
null
null
93
handle_webhook_response
null
null
null
null
null
null
// Implementation: impl Responder // File: crates/router/src/analytics.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/analytics.rs
router
impl_block
null
null
null
35
null
Responder
null
0
0
null
null
// Function: verify_email // File: crates/router/src/routes/user.rs // Module: router pub fn verify_email( state: web::Data<AppState>, http_req: HttpRequest, json_payload: web::Json<user_api::VerifyEmailRequest>, ) -> HttpResponse
crates/router/src/routes/user.rs
router
function_signature
null
null
null
59
verify_email
null
null
null
null
null
null
// Struct: DeutschebankMeansOfPayment // File: crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct DeutschebankMeansOfPayment
crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs
hyperswitch_connectors
struct_definition
DeutschebankMeansOfPayment
0
[]
52
null
null
null
null
null
null
null
// File: crates/common_utils/src/id_type/routing.rs // Module: common_utils crate::id_type!( RoutingId, " A type for routing_id that can be used for routing ids" ); crate::impl_id_type_methods!(RoutingId, "routing_id"); // This is to display the `RoutingId` as RoutingId(abcd) crate::impl_debug_id_type!(RoutingId); crate::impl_try_from_cow_str_id_type!(RoutingId, "routing_id"); crate::impl_generate_id_id_type!(RoutingId, "routing"); crate::impl_serializable_secret_id_type!(RoutingId); crate::impl_queryable_id_type!(RoutingId); crate::impl_to_sql_from_sql_id_type!(RoutingId); impl crate::events::ApiEventMetric for RoutingId { fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> { Some(crate::events::ApiEventsType::Routing) } }
crates/common_utils/src/id_type/routing.rs
common_utils
full_file
null
null
null
200
null
null
null
null
null
null
null
// Implementation: impl ClientSecretFetch for for PaymentMethodListRequest // File: crates/router/src/services/authentication.rs // Module: router // Methods: 1 total (0 public) impl ClientSecretFetch for for PaymentMethodListRequest
crates/router/src/services/authentication.rs
router
impl_block
null
null
null
49
null
PaymentMethodListRequest
ClientSecretFetch for
1
0
null
null
// Function: new // File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs // Module: hyperswitch_connectors pub fn new(reference: String) -> Self
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
hyperswitch_connectors
function_signature
null
null
null
40
new
null
null
null
null
null
null
// Function: create_client // File: crates/external_services/src/email/ses.rs // Module: external_services // Documentation: A helper function to create ses client pub fn create_client( conf: &EmailSettings, ses_config: &SESConfig, proxy_url: Option<impl AsRef<str>>, ) -> CustomResult<Client, AwsSesError>
crates/external_services/src/email/ses.rs
external_services
function_signature
null
null
null
80
create_client
null
null
null
null
null
null
// Implementation: impl Tokenizable for for PaymentsAuthorizeData // File: crates/router/src/types.rs // Module: router // Methods: 1 total (0 public) impl Tokenizable for for PaymentsAuthorizeData
crates/router/src/types.rs
router
impl_block
null
null
null
44
null
PaymentsAuthorizeData
Tokenizable for
1
0
null
null
// Struct: PostProcessing // File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct PostProcessing
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
hyperswitch_domain_models
struct_definition
PostProcessing
0
[]
43
null
null
null
null
null
null
null
// Implementation: impl UserCompanyName // File: crates/router/src/types/domain/user.rs // Module: router // Methods: 2 total (2 public) impl UserCompanyName
crates/router/src/types/domain/user.rs
router
impl_block
null
null
null
36
null
UserCompanyName
null
2
2
null
null
// Struct: FrmRoutingAlgorithm // File: crates/router/src/types/api/routing.rs // Module: router // Implementations: 0 pub struct FrmRoutingAlgorithm
crates/router/src/types/api/routing.rs
router
struct_definition
FrmRoutingAlgorithm
0
[]
36
null
null
null
null
null
null
null
// File: crates/diesel_models/src/process_tracker.rs // Module: diesel_models // Public functions: 2 // Public structs: 3 pub use common_enums::{enums::ProcessTrackerRunner, ApiVersion}; use common_utils::ext_traits::Encode; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; use error_stack::ResultExt; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use crate::{enums as storage_enums, errors, schema::process_tracker, StorageResult}; #[derive( Clone, Debug, Eq, PartialEq, Deserialize, Identifiable, Queryable, Selectable, Serialize, router_derive::DebugAsDisplay, )] #[diesel(table_name = process_tracker, check_for_backend(diesel::pg::Pg))] pub struct ProcessTracker { pub id: String, pub name: Option<String>, #[diesel(deserialize_as = super::DieselArray<String>)] pub tag: Vec<String>, pub runner: Option<String>, pub retry_count: i32, #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub schedule_time: Option<PrimitiveDateTime>, pub rule: String, pub tracking_data: serde_json::Value, pub business_status: String, pub status: storage_enums::ProcessTrackerStatus, #[diesel(deserialize_as = super::DieselArray<String>)] pub event: Vec<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, #[serde(with = "common_utils::custom_serde::iso8601")] pub updated_at: PrimitiveDateTime, pub version: ApiVersion, } impl ProcessTracker { #[inline(always)] pub fn is_valid_business_status(&self, valid_statuses: &[&str]) -> bool { valid_statuses.iter().any(|&x| x == self.business_status) } } #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = process_tracker)] pub struct ProcessTrackerNew { pub id: String, pub name: Option<String>, pub tag: Vec<String>, pub runner: Option<String>, pub retry_count: i32, pub schedule_time: Option<PrimitiveDateTime>, pub rule: String, pub tracking_data: serde_json::Value, pub business_status: String, pub status: storage_enums::ProcessTrackerStatus, pub event: Vec<String>, pub created_at: PrimitiveDateTime, pub updated_at: PrimitiveDateTime, pub version: ApiVersion, } impl ProcessTrackerNew { #[allow(clippy::too_many_arguments)] pub fn new<T>( process_tracker_id: impl Into<String>, task: impl Into<String>, runner: ProcessTrackerRunner, tag: impl IntoIterator<Item = impl Into<String>>, tracking_data: T, retry_count: Option<i32>, schedule_time: PrimitiveDateTime, api_version: ApiVersion, ) -> StorageResult<Self> where T: Serialize + std::fmt::Debug, { let current_time = common_utils::date_time::now(); Ok(Self { id: process_tracker_id.into(), name: Some(task.into()), tag: tag.into_iter().map(Into::into).collect(), runner: Some(runner.to_string()), retry_count: retry_count.unwrap_or(0), schedule_time: Some(schedule_time), rule: String::new(), tracking_data: tracking_data .encode_to_value() .change_context(errors::DatabaseError::Others) .attach_printable("Failed to serialize process tracker tracking data")?, business_status: String::from(business_status::PENDING), status: storage_enums::ProcessTrackerStatus::New, event: vec![], created_at: current_time, updated_at: current_time, version: api_version, }) } } #[derive(Debug)] pub enum ProcessTrackerUpdate { Update { name: Option<String>, retry_count: Option<i32>, schedule_time: Option<PrimitiveDateTime>, tracking_data: Option<serde_json::Value>, business_status: Option<String>, status: Option<storage_enums::ProcessTrackerStatus>, updated_at: Option<PrimitiveDateTime>, }, StatusUpdate { status: storage_enums::ProcessTrackerStatus, business_status: Option<String>, }, StatusRetryUpdate { status: storage_enums::ProcessTrackerStatus, retry_count: i32, schedule_time: PrimitiveDateTime, }, } #[derive(Debug, Clone, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = process_tracker)] pub struct ProcessTrackerUpdateInternal { name: Option<String>, retry_count: Option<i32>, schedule_time: Option<PrimitiveDateTime>, tracking_data: Option<serde_json::Value>, business_status: Option<String>, status: Option<storage_enums::ProcessTrackerStatus>, updated_at: Option<PrimitiveDateTime>, } impl Default for ProcessTrackerUpdateInternal { fn default() -> Self { Self { name: Option::default(), retry_count: Option::default(), schedule_time: Option::default(), tracking_data: Option::default(), business_status: Option::default(), status: Option::default(), updated_at: Some(common_utils::date_time::now()), } } } impl From<ProcessTrackerUpdate> for ProcessTrackerUpdateInternal { fn from(process_tracker_update: ProcessTrackerUpdate) -> Self { match process_tracker_update { ProcessTrackerUpdate::Update { name, retry_count, schedule_time, tracking_data, business_status, status, updated_at, } => Self { name, retry_count, schedule_time, tracking_data, business_status, status, updated_at, }, ProcessTrackerUpdate::StatusUpdate { status, business_status, } => Self { status: Some(status), business_status, ..Default::default() }, ProcessTrackerUpdate::StatusRetryUpdate { status, retry_count, schedule_time, } => Self { status: Some(status), retry_count: Some(retry_count), schedule_time: Some(schedule_time), ..Default::default() }, } } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use common_utils::ext_traits::StringExt; use super::ProcessTrackerRunner; #[test] fn test_enum_to_string() { let string_format = "PAYMENTS_SYNC_WORKFLOW".to_string(); let enum_format: ProcessTrackerRunner = string_format.parse_enum("ProcessTrackerRunner").unwrap(); assert_eq!(enum_format, ProcessTrackerRunner::PaymentsSyncWorkflow); } } pub mod business_status { /// Indicates that an irrecoverable error occurred during the workflow execution. pub const GLOBAL_FAILURE: &str = "GLOBAL_FAILURE"; /// Task successfully completed by consumer. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const COMPLETED_BY_PT: &str = "COMPLETED_BY_PT"; /// An error occurred during the workflow execution which prevents further execution and /// retries. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const FAILURE: &str = "FAILURE"; /// The resource associated with the task was removed, due to which further retries can/should /// not be done. pub const REVOKED: &str = "Revoked"; /// The task was executed for the maximum possible number of times without a successful outcome. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const RETRIES_EXCEEDED: &str = "RETRIES_EXCEEDED"; /// The outgoing webhook was successfully delivered in the initial attempt. /// Further retries of the task are not required. pub const INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL: &str = "INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL"; /// Indicates that an error occurred during the workflow execution. /// This status is typically set by the workflow error handler. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const GLOBAL_ERROR: &str = "GLOBAL_ERROR"; /// The resource associated with the task has been significantly modified since the task was /// created, due to which further retries of the current task are not required. /// A task that reaches this status should not be retried (rescheduled for execution) later. pub const RESOURCE_STATUS_MISMATCH: &str = "RESOURCE_STATUS_MISMATCH"; /// Business status set for newly created tasks. pub const PENDING: &str = "Pending"; /// For the PCR Workflow /// /// This status indicates the completion of a execute task pub const EXECUTE_WORKFLOW_COMPLETE: &str = "COMPLETED_EXECUTE_TASK"; /// This status indicates the failure of a execute task pub const EXECUTE_WORKFLOW_FAILURE: &str = "FAILED_EXECUTE_TASK"; /// This status indicates that the execute task was completed to trigger the psync task pub const EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_PSYNC"; /// This status indicates that the execute task was completed to trigger the review task pub const EXECUTE_WORKFLOW_COMPLETE_FOR_REVIEW: &str = "COMPLETED_EXECUTE_TASK_TO_TRIGGER_REVIEW"; /// This status indicates that the requeue was triggered for execute task pub const EXECUTE_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_EXECUTE_WORKFLOW"; /// This status indicates the completion of a psync task pub const PSYNC_WORKFLOW_COMPLETE: &str = "COMPLETED_PSYNC_TASK"; /// This status indicates that the psync task was completed to trigger the review task pub const PSYNC_WORKFLOW_COMPLETE_FOR_REVIEW: &str = "COMPLETED_PSYNC_TASK_TO_TRIGGER_REVIEW"; /// This status indicates that the requeue was triggered for psync task pub const PSYNC_WORKFLOW_REQUEUE: &str = "TRIGGER_REQUEUE_FOR_PSYNC_WORKFLOW"; /// This status indicates the completion of a review task pub const REVIEW_WORKFLOW_COMPLETE: &str = "COMPLETED_REVIEW_TASK"; /// For the CALCULATE_WORKFLOW /// /// This status indicates an invoice is queued pub const CALCULATE_WORKFLOW_QUEUED: &str = "CALCULATE_WORKFLOW_QUEUED"; /// This status indicates an invoice has been declined due to hard decline pub const CALCULATE_WORKFLOW_FINISH: &str = "FAILED_DUE_TO_HARD_DECLINE_ERROR"; /// This status indicates that the invoice is scheduled with the best available token pub const CALCULATE_WORKFLOW_SCHEDULED: &str = "CALCULATE_WORKFLOW_SCHEDULED"; /// This status indicates the invoice is in payment sync state pub const CALCULATE_WORKFLOW_PROCESSING: &str = "CALCULATE_WORKFLOW_PROCESSING"; /// This status indicates the workflow has completed successfully when the invoice is paid pub const CALCULATE_WORKFLOW_COMPLETE: &str = "CALCULATE_WORKFLOW_COMPLETE"; }
crates/diesel_models/src/process_tracker.rs
diesel_models
full_file
null
null
null
2,442
null
null
null
null
null
null
null
// Struct: PoEligibility // File: crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct PoEligibility
crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
hyperswitch_domain_models
struct_definition
PoEligibility
0
[]
48
null
null
null
null
null
null
null
// Implementation: impl RemoveNewLine for for Option // File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs // Module: hyperswitch_connectors // Methods: 1 total (0 public) impl RemoveNewLine for for Option
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Option
RemoveNewLine for
1
0
null
null
// Implementation: impl api::RefundExecute for for Tsys // File: crates/hyperswitch_connectors/src/connectors/tsys.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::RefundExecute for for Tsys
crates/hyperswitch_connectors/src/connectors/tsys.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Tsys
api::RefundExecute for
0
0
null
null
// Function: new // File: crates/test_utils/src/connector_auth.rs // Module: test_utils pub fn new() -> Self
crates/test_utils/src/connector_auth.rs
test_utils
function_signature
null
null
null
29
new
null
null
null
null
null
null
// Function: new // File: crates/hyperswitch_connectors/src/connectors/coingate.rs // Module: hyperswitch_connectors pub fn new() -> &'static Self
crates/hyperswitch_connectors/src/connectors/coingate.rs
hyperswitch_connectors
function_signature
null
null
null
39
new
null
null
null
null
null
null
// Struct: PartnerReferralResponse // File: crates/router/src/types/api/connector_onboarding/paypal.rs // Module: router // Implementations: 1 pub struct PartnerReferralResponse
crates/router/src/types/api/connector_onboarding/paypal.rs
router
struct_definition
PartnerReferralResponse
1
[]
42
null
null
null
null
null
null
null
// Function: find_by_merchant_id_payout_id // File: crates/diesel_models/src/query/payout_attempt.rs // Module: diesel_models pub fn find_by_merchant_id_payout_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payout_id: &common_utils::id_type::PayoutId, ) -> StorageResult<Self>
crates/diesel_models/src/query/payout_attempt.rs
diesel_models
function_signature
null
null
null
88
find_by_merchant_id_payout_id
null
null
null
null
null
null
// Struct: WiseRecipientCreateRequest // File: crates/hyperswitch_connectors/src/connectors/wise/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct WiseRecipientCreateRequest
crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
hyperswitch_connectors
struct_definition
WiseRecipientCreateRequest
0
[]
49
null
null
null
null
null
null
null
// Function: new // File: crates/hyperswitch_connectors/src/connectors/adyen.rs // Module: hyperswitch_connectors pub fn new() -> &'static Self
crates/hyperswitch_connectors/src/connectors/adyen.rs
hyperswitch_connectors
function_signature
null
null
null
39
new
null
null
null
null
null
null
// Implementation: impl webhooks::IncomingWebhook for for Dwolla // File: crates/hyperswitch_connectors/src/connectors/dwolla.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl webhooks::IncomingWebhook for for Dwolla
crates/hyperswitch_connectors/src/connectors/dwolla.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
Dwolla
webhooks::IncomingWebhook for
6
0
null
null
// Implementation: impl quote::ToTokens for for FieldMeta // File: crates/router_derive/src/macros/to_encryptable.rs // Module: router_derive // Methods: 1 total (0 public) impl quote::ToTokens for for FieldMeta
crates/router_derive/src/macros/to_encryptable.rs
router_derive
impl_block
null
null
null
54
null
FieldMeta
quote::ToTokens for
1
0
null
null
// Module Structure // File: crates/hyperswitch_connectors/src/connectors/vgs.rs // Module: hyperswitch_connectors // Public submodules: pub mod transformers;
crates/hyperswitch_connectors/src/connectors/vgs.rs
hyperswitch_connectors
module_structure
null
null
null
38
null
null
null
null
null
1
0
// Struct: StripeConnectPayoutCreateRequest // File: crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct StripeConnectPayoutCreateRequest
crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs
hyperswitch_connectors
struct_definition
StripeConnectPayoutCreateRequest
0
[]
54
null
null
null
null
null
null
null