Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(tokenio): Add OpenBanking Redirection Flow (#8152)

awasthi214c73d7488947
diff --git a/Cargo.lock b/Cargo.lock
index e796992cf7..1aef07f36d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3916,6 +3916,7 @@ dependencies = [
"masking",
"mime",
"num-traits",
+ "openssl",
"qrcode",
"quick-xml",
"rand 0.8.5",
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index c1983fb1d7..ad0d59ac97 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -8150,6 +8150,7 @@
"stripebilling",
"taxjar",
"threedsecureio",
+ "tokenio",
"trustpay",
"tsys",
"vgs",
@@ -12830,16 +12831,19 @@
"properties": {
"iban": {
"type": "object",
+ "description": "IBAN-based account for international transfers",
"required": [
"iban",
"name"
],
"properties": {
"iban": {
- "type": "string"
+ "type": "string",
+ "description": "International Bank Account Number (up to 34 characters)"
},
"name": {
- "type": "string"
+ "type": "string",
+ "description": "Account holder name"
},
"connector_recipient_id": {
"type": "string",
@@ -12857,6 +12861,7 @@
"properties": {
"bacs": {
"type": "object",
+ "description": "UK BACS payment system",
"required": [
"account_number",
"sort_code",
@@ -12864,13 +12869,215 @@
],
"properties": {
"account_number": {
- "type": "string"
+ "type": "string",
+ "description": "8-digit UK account number"
},
"sort_code": {
- "type": "string"
+ "type": "string",
+ "description": "6-digit UK sort code",
+ "example": "123456"
},
"name": {
- "type": "string"
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "faster_payments"
+ ],
+ "properties": {
+ "faster_payments": {
+ "type": "object",
+ "description": "UK Faster Payments (instant transfers)",
+ "required": [
+ "account_number",
+ "sort_code",
+ "name"
+ ],
+ "properties": {
+ "account_number": {
+ "type": "string",
+ "description": "8-digit UK account number"
+ },
+ "sort_code": {
+ "type": "string",
+ "description": "6-digit UK sort code"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "sepa"
+ ],
+ "properties": {
+ "sepa": {
+ "type": "object",
+ "description": "SEPA payments (Euro zone)",
+ "required": [
+ "iban",
+ "name"
+ ],
+ "properties": {
+ "iban": {
+ "type": "string",
+ "description": "IBAN for SEPA transfers",
+ "example": "FR1420041010050500013M02606"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "sepa_instant"
+ ],
+ "properties": {
+ "sepa_instant": {
+ "type": "object",
+ "description": "SEPA Instant payments (10-second transfers)",
+ "required": [
+ "iban",
+ "name"
+ ],
+ "properties": {
+ "iban": {
+ "type": "string",
+ "description": "IBAN for instant SEPA transfers",
+ "example": "DE89370400440532013000"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "elixir"
+ ],
+ "properties": {
+ "elixir": {
+ "type": "object",
+ "description": "Polish Elixir payment system",
+ "required": [
+ "account_number",
+ "iban",
+ "name"
+ ],
+ "properties": {
+ "account_number": {
+ "type": "string",
+ "description": "Polish account number (26 digits)",
+ "example": "12345678901234567890123456"
+ },
+ "iban": {
+ "type": "string",
+ "description": "Polish IBAN (28 chars)",
+ "example": "PL27114020040000300201355387"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "bankgiro"
+ ],
+ "properties": {
+ "bankgiro": {
+ "type": "object",
+ "description": "Swedish Bankgiro system",
+ "required": [
+ "number",
+ "name"
+ ],
+ "properties": {
+ "number": {
+ "type": "string",
+ "description": "Bankgiro number (7-8 digits)",
+ "example": "5402-9656"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name",
+ "example": "Erik Andersson"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "plusgiro"
+ ],
+ "properties": {
+ "plusgiro": {
+ "type": "object",
+ "description": "Swedish Plusgiro system",
+ "required": [
+ "number",
+ "name"
+ ],
+ "properties": {
+ "number": {
+ "type": "string",
+ "description": "Plusgiro number (2-8 digits)",
+ "example": "4789-2"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name",
+ "example": "Anna Larsson"
},
"connector_recipient_id": {
"type": "string",
@@ -22227,6 +22434,7 @@
"stripe",
"stripebilling",
"trustpay",
+ "tokenio",
"tsys",
"volt",
"wellsfargo",
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 53631f9657..280747884b 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -10070,6 +10070,7 @@
"stripebilling",
"taxjar",
"threedsecureio",
+ "tokenio",
"trustpay",
"tsys",
"vgs",
@@ -15193,16 +15194,19 @@
"properties": {
"iban": {
"type": "object",
+ "description": "IBAN-based account for international transfers",
"required": [
"iban",
"name"
],
"properties": {
"iban": {
- "type": "string"
+ "type": "string",
+ "description": "International Bank Account Number (up to 34 characters)"
},
"name": {
- "type": "string"
+ "type": "string",
+ "description": "Account holder name"
},
"connector_recipient_id": {
"type": "string",
@@ -15220,6 +15224,7 @@
"properties": {
"bacs": {
"type": "object",
+ "description": "UK BACS payment system",
"required": [
"account_number",
"sort_code",
@@ -15227,13 +15232,215 @@
],
"properties": {
"account_number": {
- "type": "string"
+ "type": "string",
+ "description": "8-digit UK account number"
},
"sort_code": {
- "type": "string"
+ "type": "string",
+ "description": "6-digit UK sort code",
+ "example": "123456"
},
"name": {
- "type": "string"
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "faster_payments"
+ ],
+ "properties": {
+ "faster_payments": {
+ "type": "object",
+ "description": "UK Faster Payments (instant transfers)",
+ "required": [
+ "account_number",
+ "sort_code",
+ "name"
+ ],
+ "properties": {
+ "account_number": {
+ "type": "string",
+ "description": "8-digit UK account number"
+ },
+ "sort_code": {
+ "type": "string",
+ "description": "6-digit UK sort code"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "sepa"
+ ],
+ "properties": {
+ "sepa": {
+ "type": "object",
+ "description": "SEPA payments (Euro zone)",
+ "required": [
+ "iban",
+ "name"
+ ],
+ "properties": {
+ "iban": {
+ "type": "string",
+ "description": "IBAN for SEPA transfers",
+ "example": "FR1420041010050500013M02606"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "sepa_instant"
+ ],
+ "properties": {
+ "sepa_instant": {
+ "type": "object",
+ "description": "SEPA Instant payments (10-second transfers)",
+ "required": [
+ "iban",
+ "name"
+ ],
+ "properties": {
+ "iban": {
+ "type": "string",
+ "description": "IBAN for instant SEPA transfers",
+ "example": "DE89370400440532013000"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "elixir"
+ ],
+ "properties": {
+ "elixir": {
+ "type": "object",
+ "description": "Polish Elixir payment system",
+ "required": [
+ "account_number",
+ "iban",
+ "name"
+ ],
+ "properties": {
+ "account_number": {
+ "type": "string",
+ "description": "Polish account number (26 digits)",
+ "example": "12345678901234567890123456"
+ },
+ "iban": {
+ "type": "string",
+ "description": "Polish IBAN (28 chars)",
+ "example": "PL27114020040000300201355387"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "bankgiro"
+ ],
+ "properties": {
+ "bankgiro": {
+ "type": "object",
+ "description": "Swedish Bankgiro system",
+ "required": [
+ "number",
+ "name"
+ ],
+ "properties": {
+ "number": {
+ "type": "string",
+ "description": "Bankgiro number (7-8 digits)",
+ "example": "5402-9656"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name",
+ "example": "Erik Andersson"
+ },
+ "connector_recipient_id": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "plusgiro"
+ ],
+ "properties": {
+ "plusgiro": {
+ "type": "object",
+ "description": "Swedish Plusgiro system",
+ "required": [
+ "number",
+ "name"
+ ],
+ "properties": {
+ "number": {
+ "type": "string",
+ "description": "Plusgiro number (2-8 digits)",
+ "example": "4789-2"
+ },
+ "name": {
+ "type": "string",
+ "description": "Account holder name",
+ "example": "Anna Larsson"
},
"connector_recipient_id": {
"type": "string",
@@ -26580,6 +26787,7 @@
"stripe",
"stripebilling",
"trustpay",
+ "tokenio",
"tsys",
"volt",
"wellsfargo",
diff --git a/config/config.example.toml b/config/config.example.toml
index d442b3824e..a426072b9b 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -284,7 +284,7 @@ stripebilling.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
thunes.base_url = "https://api.limonetikqualif.com/"
-tokenio.base_url = "https://api.token.io"
+tokenio.base_url = "https://api.sandbox.token.io"
stripe.base_url_file_upload = "https://files.stripe.com/"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
@@ -1027,7 +1027,7 @@ control_center_url = "http://localhost:9000" # Control center URL
encryption_key = "" # Encryption key used for encrypting data in user_authentication_methods table
[locker_based_open_banking_connectors]
-connector_list = ""
+connector_list = "tokenio"
[recipient_emails]
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 61ef5b1ede..1047267e38 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -121,7 +121,7 @@ stripe.base_url_file_upload = "https://files.stripe.com/"
stripebilling.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
thunes.base_url = "https://api.limonetikqualif.com/"
-tokenio.base_url = "https://api.token.io"
+tokenio.base_url = "https://api.sandbox.token.io"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
tsys.base_url = "https://stagegw.transnox.com/"
@@ -725,7 +725,7 @@ keys = "accept-language,user-agent,x-profile-id"
sdk_eligible_payment_methods = "card"
[locker_based_open_banking_connectors]
-connector_list = ""
+connector_list = "tokenio"
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index d5567a432f..a7f80eba15 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -735,7 +735,7 @@ keys = "accept-language,user-agent,x-profile-id"
sdk_eligible_payment_methods = "card"
[locker_based_open_banking_connectors]
-connector_list = ""
+connector_list = "tokenio"
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index f808331b0a..2d3a5dfd05 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -125,7 +125,7 @@ stripe.base_url_file_upload = "https://files.stripe.com/"
stripebilling.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
thunes.base_url = "https://api.limonetikqualif.com/"
-tokenio.base_url = "https://api.token.io"
+tokenio.base_url = "https://api.sandbox.token.io"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
tsys.base_url = "https://stagegw.transnox.com/"
@@ -741,7 +741,7 @@ keys = "accept-language,user-agent,x-profile-id"
sdk_eligible_payment_methods = "card"
[locker_based_open_banking_connectors]
-connector_list = ""
+connector_list = "tokenio"
[network_tokenization_supported_card_networks]
card_networks = "Visa, AmericanExpress, Mastercard"
diff --git a/config/development.toml b/config/development.toml
index 13b733afa6..5c1841ba75 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -316,7 +316,7 @@ stripebilling.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
thunes.base_url = "https://api.limonetikqualif.com/"
-tokenio.base_url = "https://api.token.io"
+tokenio.base_url = "https://api.sandbox.token.io"
stripe.base_url_file_upload = "https://files.stripe.com/"
wise.base_url = "https://api.sandbox.transferwise.tech/"
worldline.base_url = "https://eu.sandbox.api-ingenico.com/"
@@ -1129,7 +1129,7 @@ control_center_url = "http://localhost:9000"
encryption_key = "A8EF32E029BC3342E54BF2E172A4D7AA43E8EF9D2C3A624A9F04E2EF79DC698F"
[locker_based_open_banking_connectors]
-connector_list = ""
+connector_list = "tokenio"
[cell_information]
id = "12345"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 552511765e..08ba9795a6 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -210,7 +210,7 @@ stripebilling.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
thunes.base_url = "https://api.limonetikqualif.com/"
-tokenio.base_url = "https://api.token.io"
+tokenio.base_url = "https://api.sandbox.token.io"
stripe.base_url_file_upload = "https://files.stripe.com/"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"
@@ -1026,7 +1026,7 @@ sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT,CZ,DE,HU,NO,PL,SE,
ach = { country = "US", currency = "USD" }
[locker_based_open_banking_connectors]
-connector_list = ""
+connector_list = "tokenio"
[cell_information]
id = "12345"
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index e8669b454b..25ac34d8fa 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1001,21 +1001,122 @@ pub struct RevenueRecoveryMetadata {
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum MerchantAccountData {
+ /// IBAN-based account for international transfers
Iban {
- #[schema(value_type= String)]
+ /// International Bank Account Number (up to 34 characters)
+ #[schema(value_type = String)]
iban: Secret<String>,
+
+ /// Account holder name
name: String,
- #[schema(value_type= Option<String>)]
+ #[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
+ /// UK BACS payment system
Bacs {
- #[schema(value_type= String)]
+ /// 8-digit UK account number
+ #[schema(value_type = String)]
account_number: Secret<String>,
- #[schema(value_type= String)]
+
+ /// 6-digit UK sort code
+ #[schema(value_type = String, example = "123456")]
sort_code: Secret<String>,
+
+ /// Account holder name
+ name: String,
+
+ #[schema(value_type = Option<String>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connector_recipient_id: Option<Secret<String>>,
+ },
+ /// UK Faster Payments (instant transfers)
+ FasterPayments {
+ /// 8-digit UK account number
+ #[schema(value_type = String)]
+ account_number: Secret<String>,
+ /// 6-digit UK sort code
+ #[schema(value_type = String)]
+ sort_code: Secret<String>,
+
+ /// Account holder name
+ name: String,
+
+ #[schema(value_type = Option<String>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connector_recipient_id: Option<Secret<String>>,
+ },
+
+ /// SEPA payments (Euro zone)
+ Sepa {
+ /// IBAN for SEPA transfers
+ #[schema(value_type = String, example = "FR1420041010050500013M02606")]
+ iban: Secret<String>,
+ /// Account holder name
+ name: String,
+ #[schema(value_type = Option<String>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connector_recipient_id: Option<Secret<String>>,
+ },
+
+ /// SEPA Instant payments (10-second transfers)
+ SepaInstant {
+ /// IBAN for instant SEPA transfers
+ #[schema(value_type = String, example = "DE89370400440532013000")]
+ iban: Secret<String>,
+
+ /// Account holder name
name: String,
- #[schema(value_type= Option<String>)]
+
+ #[schema(value_type = Option<String>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connector_recipient_id: Option<Secret<String>>,
+ },
+
+ /// Polish Elixir payment system
+ Elixir {
+ /// Polish account number (26 digits)
+ #[schema(value_type = String, example = "12345678901234567890123456")]
+ account_number: Secret<String>,
+
+ /// Polish IBAN (28 chars)
+ #[schema(value_type = String, example = "PL27114020040000300201355387")]
+ iban: Secret<String>,
+
+ /// Account holder name
+ name: String,
+
+ #[schema(value_type = Option<String>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connector_recipient_id: Option<Secret<String>>,
+ },
+
+ /// Swedish Bankgiro system
+ Bankgiro {
+ /// Bankgiro number (7-8 digits)
+ #[schema(value_type = String, example = "5402-9656")]
+ number: Secret<String>,
+
+ /// Account holder name
+ #[schema(example = "Erik Andersson")]
+ name: String,
+
+ #[schema(value_type = Option<String>)]
+ #[serde(skip_serializing_if = "Option::is_none")]
+ connector_recipient_id: Option<Secret<String>>,
+ },
+
+ /// Swedish Plusgiro system
+ Plusgiro {
+ /// Plusgiro number (2-8 digits)
+ #[schema(value_type = String, example = "4789-2")]
+ number: Secret<String>,
+
+ /// Account holder name
+ #[schema(example = "Anna Larsson")]
+ name: String,
+
+ #[schema(value_type = Option<String>)]
#[serde(skip_serializing_if = "Option::is_none")]
connector_recipient_id: Option<Secret<String>>,
},
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs
index 83a19b7bfa..411b873233 100644
--- a/crates/common_enums/src/connector_enums.rs
+++ b/crates/common_enums/src/connector_enums.rs
@@ -140,7 +140,7 @@ pub enum RoutableConnectors {
// Taxjar,
Trustpay,
// Thunes
- // Tokenio,
+ Tokenio,
// Tsys,
Tsys,
// UnifiedAuthenticationService,
@@ -299,6 +299,7 @@ pub enum Connector {
Threedsecureio,
// Tokenio,
//Thunes,
+ Tokenio,
Trustpay,
Tsys,
// UnifiedAuthenticationService,
@@ -487,6 +488,7 @@ impl Connector {
| Self::CtpMastercard
| Self::CtpVisa
| Self::Noon
+ | Self::Tokenio
| Self::Stripe
| Self::Datatrans => false,
Self::Checkout | Self::Nmi |Self::Cybersource | Self::Archipel => true,
@@ -621,6 +623,7 @@ impl From<RoutableConnectors> for Connector {
RoutableConnectors::Stax => Self::Stax,
RoutableConnectors::Stripe => Self::Stripe,
RoutableConnectors::Stripebilling => Self::Stripebilling,
+ RoutableConnectors::Tokenio => Self::Tokenio,
RoutableConnectors::Trustpay => Self::Trustpay,
// RoutableConnectors::Tokenio => Self::Tokenio,
RoutableConnectors::Tsys => Self::Tsys,
@@ -735,7 +738,7 @@ impl TryFrom<Connector> for RoutableConnectors {
Connector::Stax => Ok(Self::Stax),
Connector::Stripe => Ok(Self::Stripe),
Connector::Stripebilling => Ok(Self::Stripebilling),
- // Connector::Tokenio => Ok(Self::Tokenio),
+ Connector::Tokenio => Ok(Self::Tokenio),
Connector::Trustpay => Ok(Self::Trustpay),
Connector::Tsys => Ok(Self::Tsys),
Connector::Volt => Ok(Self::Volt),
diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs
index d7cb8d7c20..9c1af493e2 100644
--- a/crates/common_utils/src/crypto.rs
+++ b/crates/common_utils/src/crypto.rs
@@ -8,6 +8,8 @@ use ring::{
aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey},
hmac,
};
+#[cfg(feature = "logs")]
+use router_env::logger;
use crate::{
errors::{self, CustomResult},
@@ -330,7 +332,88 @@ impl DecodeMessage for GcmAes256 {
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;
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index f05ca7b5f4..81f09e7459 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -87,6 +87,12 @@ pub struct ConfigMerchantAdditionalDetails {
pub bacs: Option<Vec<InputData>>,
pub connector_recipient_id: Option<InputData>,
pub wallet_id: Option<InputData>,
+ pub faster_payments: Option<Vec<InputData>>,
+ pub sepa: Option<Vec<InputData>>,
+ pub sepa_instant: Option<Vec<InputData>>,
+ pub elixir: Option<Vec<InputData>>,
+ pub bankgiro: Option<Vec<InputData>>,
+ pub plusgiro: Option<Vec<InputData>>,
}
#[serde_with::skip_serializing_none]
@@ -438,6 +444,7 @@ impl ConnectorConfig {
Connector::Stax => Ok(connector_data.stax),
Connector::Stripe => Ok(connector_data.stripe),
Connector::Stripebilling => Ok(connector_data.stripebilling),
+ Connector::Tokenio => Ok(connector_data.tokenio),
Connector::Trustpay => Ok(connector_data.trustpay),
Connector::Threedsecureio => Ok(connector_data.threedsecureio),
Connector::Taxjar => Ok(connector_data.taxjar),
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 884f9aca6b..40960da0c1 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -5529,6 +5529,170 @@ options=["Hyperswitch"]
[fiuu.connector_webhook_details]
merchant_secret="Source verification key"
+[tokenio]
+[[tokenio.open_banking]]
+ payment_method_type = "open_banking_pis"
+[tokenio.connector_auth.MultiAuthKey]
+api_key="Key Id"
+api_secret="Private Key"
+key1="Merchant Id"
+key2="Key Algorithm"
+[tokenio.connector_webhook_details]
+merchant_secret="Tokenio Public Key"
+[tokenio.additional_merchant_data.open_banking_recipient_data]
+name="open_banking_recipient_data"
+label="Open Banking Recipient Data"
+placeholder="Enter Open Banking Recipient Data"
+required=true
+type="Select"
+options=["account_data"]
+[tokenio.additional_merchant_data.account_data]
+name="account_data"
+label="Bank scheme"
+placeholder="Enter account_data"
+required=true
+type="Select"
+options=["iban","bacs","faster_payments","sepa","sepa_instant","elixir","bankgiro","plusgiro"]
+
+[tokenio.additional_merchant_data.iban]
+name="iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.iban_name]
+name="iban.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# BACS Configuration
+[tokenio.additional_merchant_data.bacs_sort_code]
+name="bacs.sort_code"
+label="Sort Code"
+placeholder="Enter sort code (e.g., 12-34-56)"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bacs_account_number]
+name="bacs.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bacs_name]
+name="bacs.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Faster Payments Configuration
+[tokenio.additional_merchant_data.faster_payments_sort_code]
+name="faster_payments.sort_code"
+label="Sort Code"
+placeholder="Enter sort code (e.g., 12-34-56)"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.faster_payments_account_number]
+name="faster_payments.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.faster_payments_name]
+name="faster_payments.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# SEPA Configuration
+[tokenio.additional_merchant_data.sepa_iban]
+name="sepa.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.sepa_name]
+name="sepa.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# SEPA Instant Configuration
+[tokenio.additional_merchant_data.sepa_instant_iban]
+name="sepa_instant.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.sepa_instant_name]
+name="sepa_instant.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Elixir Configuration
+[tokenio.additional_merchant_data.elixir_account_number]
+name="elixir.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.elixir_iban]
+name="elixir.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.elixir_name]
+name="elixir.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Bankgiro Configuration
+[tokenio.additional_merchant_data.bankgiro_number]
+name="bankgiro.number"
+label="Bankgiro Number"
+placeholder="Enter bankgiro number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bankgiro_name]
+name="bankgiro.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Plusgiro Configuration
+[tokenio.additional_merchant_data.plusgiro_number]
+name="plusgiro.number"
+label="Plusgiro Number"
+placeholder="Enter plusgiro number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.plusgiro_name]
+name="plusgiro.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
[elavon]
[[elavon.credit]]
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index a070ce95be..bb9e84f46f 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -4146,6 +4146,172 @@ options=["Hyperswitch"]
[fiuu.connector_webhook_details]
merchant_secret="Source verification key"
+
+[tokenio]
+[[tokenio.open_banking]]
+ payment_method_type = "open_banking_pis"
+[tokenio.connector_webhook_details]
+merchant_secret="Tokenio Public Key"
+[tokenio.connector_auth.MultiAuthKey]
+api_key="Key Id"
+api_secret="Private Key"
+key1="Merchant Id"
+key2="Key Algorithm"
+[tokenio.additional_merchant_data.open_banking_recipient_data]
+name="open_banking_recipient_data"
+label="Open Banking Recipient Data"
+placeholder="Enter Open Banking Recipient Data"
+required=true
+type="Select"
+options=["account_data"]
+[tokenio.additional_merchant_data.account_data]
+name="account_data"
+label="Bank scheme"
+placeholder="Enter account_data"
+required=true
+type="Select"
+options=["iban","bacs","faster_payments","sepa","sepa_instant","elixir","bankgiro","plusgiro"]
+
+[tokenio.additional_merchant_data.iban]
+name="iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.iban_name]
+name="iban.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# BACS Configuration
+[tokenio.additional_merchant_data.bacs_sort_code]
+name="bacs.sort_code"
+label="Sort Code"
+placeholder="Enter sort code (e.g., 12-34-56)"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bacs_account_number]
+name="bacs.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bacs_name]
+name="bacs.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Faster Payments Configuration
+[tokenio.additional_merchant_data.faster_payments_sort_code]
+name="faster_payments.sort_code"
+label="Sort Code"
+placeholder="Enter sort code (e.g., 12-34-56)"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.faster_payments_account_number]
+name="faster_payments.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.faster_payments_name]
+name="faster_payments.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# SEPA Configuration
+[tokenio.additional_merchant_data.sepa_iban]
+name="sepa.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.sepa_name]
+name="sepa.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# SEPA Instant Configuration
+[tokenio.additional_merchant_data.sepa_instant_iban]
+name="sepa_instant.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.sepa_instant_name]
+name="sepa_instant.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Elixir Configuration
+[tokenio.additional_merchant_data.elixir_account_number]
+name="elixir.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.elixir_iban]
+name="elixir.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.elixir_name]
+name="elixir.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Bankgiro Configuration
+[tokenio.additional_merchant_data.bankgiro_number]
+name="bankgiro.number"
+label="Bankgiro Number"
+placeholder="Enter bankgiro number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bankgiro_name]
+name="bankgiro.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Plusgiro Configuration
+[tokenio.additional_merchant_data.plusgiro_number]
+name="plusgiro.number"
+label="Plusgiro Number"
+placeholder="Enter plusgiro number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.plusgiro_name]
+name="plusgiro.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
[elavon]
[[elavon.credit]]
payment_method_type = "Mastercard"
@@ -4549,7 +4715,6 @@ placeholder = "Enter Acquirer Merchant ID"
required = false
type = "Text"
-
[worldpayxml]
[[worldpayxml.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 83110fd91a..8a7e27f6b6 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -5499,6 +5499,171 @@ options=["Hyperswitch"]
[fiuu.connector_webhook_details]
merchant_secret="Source verification key"
+[tokenio]
+[[tokenio.open_banking]]
+ payment_method_type = "open_banking_pis"
+[tokenio.connector_webhook_details]
+merchant_secret="Tokenio Public Key"
+[tokenio.connector_auth.MultiAuthKey]
+api_key="Key Id"
+api_secret="Private Key"
+key1="Merchant Id"
+key2="Key Algorithm"
+[tokenio.additional_merchant_data.open_banking_recipient_data]
+name="open_banking_recipient_data"
+label="Open Banking Recipient Data"
+placeholder="Enter Open Banking Recipient Data"
+required=true
+type="Select"
+options=["account_data"]
+[tokenio.additional_merchant_data.account_data]
+name="account_data"
+label="Bank scheme"
+placeholder="Enter account_data"
+required=true
+type="Select"
+options=["iban","bacs","faster_payments","sepa","sepa_instant","elixir","bankgiro","plusgiro"]
+
+[tokenio.additional_merchant_data.iban]
+name="iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.iban_name]
+name="iban.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# BACS Configuration
+[tokenio.additional_merchant_data.bacs_sort_code]
+name="bacs.sort_code"
+label="Sort Code"
+placeholder="Enter sort code (e.g., 12-34-56)"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bacs_account_number]
+name="bacs.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bacs_name]
+name="bacs.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Faster Payments Configuration
+[tokenio.additional_merchant_data.faster_payments_sort_code]
+name="faster_payments.sort_code"
+label="Sort Code"
+placeholder="Enter sort code (e.g., 12-34-56)"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.faster_payments_account_number]
+name="faster_payments.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.faster_payments_name]
+name="faster_payments.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# SEPA Configuration
+[tokenio.additional_merchant_data.sepa_iban]
+name="sepa.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.sepa_name]
+name="sepa.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# SEPA Instant Configuration
+[tokenio.additional_merchant_data.sepa_instant_iban]
+name="sepa_instant.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.sepa_instant_name]
+name="sepa_instant.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Elixir Configuration
+[tokenio.additional_merchant_data.elixir_account_number]
+name="elixir.account_number"
+label="Account Number"
+placeholder="Enter account number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.elixir_iban]
+name="elixir.iban"
+label="IBAN"
+placeholder="Enter IBAN"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.elixir_name]
+name="elixir.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Bankgiro Configuration
+[tokenio.additional_merchant_data.bankgiro_number]
+name="bankgiro.number"
+label="Bankgiro Number"
+placeholder="Enter bankgiro number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.bankgiro_name]
+name="bankgiro.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
+# Plusgiro Configuration
+[tokenio.additional_merchant_data.plusgiro_number]
+name="plusgiro.number"
+label="Plusgiro Number"
+placeholder="Enter plusgiro number"
+required=true
+type="Text"
+
+[tokenio.additional_merchant_data.plusgiro_name]
+name="plusgiro.name"
+label="Account Holder Name"
+placeholder="Enter account holder name"
+required=true
+type="Text"
+
[elavon]
[[elavon.credit]]
payment_method_type = "Mastercard"
diff --git a/crates/hyperswitch_connectors/Cargo.toml b/crates/hyperswitch_connectors/Cargo.toml
index 130745274c..6be421eb30 100644
--- a/crates/hyperswitch_connectors/Cargo.toml
+++ b/crates/hyperswitch_connectors/Cargo.toml
@@ -29,6 +29,7 @@ josekit = { git = "https://github.com/sumanmaji4/josekit-rs.git", rev = "5ab5487
lazy_static = "1.5.0"
mime = "0.3.17"
num-traits = "0.2.19"
+openssl = {version = "0.10.70"}
qrcode = "0.14.1"
quick-xml = { version = "0.31.0", features = ["serialize"] }
rand = "0.8.5"
diff --git a/crates/hyperswitch_connectors/src/connectors/tokenio.rs b/crates/hyperswitch_connectors/src/connectors/tokenio.rs
index a24b5e3414..58c01f9259 100644
--- a/crates/hyperswitch_connectors/src/connectors/tokenio.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tokenio.rs
@@ -1,12 +1,19 @@
pub mod transformers;
+use std::{
+ sync::LazyLock,
+ time::{SystemTime, UNIX_EPOCH},
+};
+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
+use common_enums::{enums, FeatureStatus, PaymentMethodType};
use common_utils::{
+ crypto::{self, VerifySignature},
errors::CustomResult,
- ext_traits::BytesExt,
+ ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
- types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
+ types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
-use error_stack::{report, ResultExt};
+use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
@@ -19,10 +26,13 @@ use hyperswitch_domain_models::{
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
- router_response_types::{PaymentsResponseData, RefundsResponseData},
+ router_response_types::{
+ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
+ SupportedPaymentMethods, SupportedPaymentMethodsExt,
+ },
types::{
- PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
- RefundSyncRouterData, RefundsRouterData,
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
@@ -33,25 +43,194 @@ use hyperswitch_interfaces::{
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
- types::{self, Response},
+ types::Response,
webhooks,
};
-use masking::{ExposeInterface, Mask};
-use transformers as tokenio;
+use masking::{ExposeInterface, Mask, Secret};
+use openssl::{ec::EcKey, hash::MessageDigest, pkey::PKey, rsa::Rsa, sign::Signer};
+use transformers::{self as tokenio, TokenioPaymentStatus};
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Tokenio {
- amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Tokenio {
pub fn new() -> &'static Self {
&Self {
- amount_converter: &StringMinorUnitForConnector,
+ amount_converter: &StringMajorUnitForConnector,
}
}
+ fn create_jwt_token(
+ &self,
+ auth: &tokenio::TokenioAuthType,
+ method: &str,
+ path: &str,
+ body: &RequestContent,
+ connectors: &Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ // Create JWT header
+ let exp_time = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?
+ .as_millis()
+ + 600_000; // 10 minutes
+
+ let header = serde_json::json!({
+ "alg": match auth.key_algorithm {
+ tokenio::CryptoAlgorithm::RS256 => "RS256",
+ tokenio::CryptoAlgorithm::ES256 => "ES256",
+ tokenio::CryptoAlgorithm::EDDSA => "EdDSA",
+ },
+ "exp": exp_time.to_string(), // Convert to string as Token.io expects
+ "mid": auth.merchant_id.clone().expose(),
+ "kid": auth.key_id.clone().expose(),
+ "method": method.to_uppercase(),
+ "host": connectors.tokenio.base_url.trim_start_matches("https://").trim_end_matches("/"),
+ "path": path,
+ "typ": "JWT",
+ });
+
+ // For GET requests, use detached JWT (no payload)
+ // For POST/PUT requests, include the request body as payload
+ let is_get_request = method.to_uppercase() == "GET";
+ let payload = if is_get_request {
+ None // No payload for GET requests (detached JWT)
+ } else {
+ // For non-GET requests, include the request body
+ match body {
+ RequestContent::Json(json_body) => Some(
+ serde_json::to_value(json_body)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?,
+ ),
+ _ => Some(serde_json::json!({})),
+ }
+ };
+
+ // Use compact JSON serialization (no extra whitespace)
+ let encoded_header = self.base64url_encode(
+ serde_json::to_string(&header)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?
+ .as_bytes(),
+ )?;
+
+ let (encoded_payload, signing_input) = match payload {
+ Some(p) => {
+ // Standard JWT with payload
+ let encoded_payload = self.base64url_encode(
+ serde_json::to_string(&p)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?
+ .as_bytes(),
+ )?;
+ let signing_input = format!("{}.{}", encoded_header, encoded_payload);
+ (encoded_payload, signing_input)
+ }
+ None => {
+ // Detached JWT (GET requests) - sign only the header with a dot
+ let signing_input = format!("{}.", encoded_header);
+ (String::new(), signing_input) // Empty payload for detached JWT
+ }
+ };
+
+ // Sign the JWT based on algorithm
+ let signature = match auth.key_algorithm {
+ tokenio::CryptoAlgorithm::RS256 => {
+ self.sign_rsa(&auth.private_key.clone().expose(), &signing_input)?
+ }
+ tokenio::CryptoAlgorithm::ES256 => {
+ self.sign_ecdsa(&auth.private_key.clone().expose(), &signing_input)?
+ }
+ tokenio::CryptoAlgorithm::EDDSA => {
+ self.sign_eddsa(&auth.private_key.clone().expose(), &signing_input)?
+ }
+ };
+
+ let encoded_signature = self.base64url_encode(&signature)?;
+
+ // Assemble JWT - for detached JWT, middle part is empty
+ Ok(format!(
+ "{}.{}.{}",
+ encoded_header, encoded_payload, encoded_signature
+ ))
+ }
+
+ fn base64url_encode(&self, data: &[u8]) -> CustomResult<String, errors::ConnectorError> {
+ Ok(URL_SAFE_NO_PAD.encode(data))
+ }
+
+ fn sign_rsa(
+ &self,
+ private_key_pem: &str,
+ data: &str,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let rsa = Rsa::private_key_from_pem(private_key_pem.as_bytes())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let pkey =
+ PKey::from_rsa(rsa).change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let mut signer = Signer::new(MessageDigest::sha256(), &pkey)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ signer
+ .update(data.as_bytes())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let signature = signer
+ .sign_to_vec()
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ Ok(signature)
+ }
+
+ fn sign_ecdsa(
+ &self,
+ private_key_pem: &str,
+ data: &str,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let ec_key = EcKey::private_key_from_pem(private_key_pem.as_bytes())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let pkey = PKey::from_ec_key(ec_key)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let mut signer = Signer::new(MessageDigest::sha256(), &pkey)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ signer
+ .update(data.as_bytes())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let signature = signer
+ .sign_to_vec()
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ Ok(signature)
+ }
+
+ fn sign_eddsa(
+ &self,
+ private_key_pem: &str,
+ data: &str,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let pkey = PKey::private_key_from_pem(private_key_pem.as_bytes())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let mut signer = Signer::new_without_digest(&pkey)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ signer
+ .update(data.as_bytes())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ let signature = signer
+ .sign_to_vec()
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ Ok(signature)
+ }
}
impl api::Payment for Tokenio {}
@@ -79,15 +258,15 @@ where
{
fn build_headers(
&self,
- req: &RouterData<Flow, Request, Response>,
+ _req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
- let mut header = vec![(
+ // Basic headers - JWT will be added in individual build_request methods
+ let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- header.append(&mut api_key);
+
Ok(header)
}
}
@@ -99,9 +278,6 @@ impl ConnectorCommon for Tokenio {
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
- // TODO! Check connector documentation, on which unit they are processing the currency.
- // If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
- // if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
@@ -114,14 +290,9 @@ impl ConnectorCommon for Tokenio {
fn get_auth_header(
&self,
- auth_type: &ConnectorAuthType,
+ _auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
- let auth = tokenio::TokenioAuthType::try_from(auth_type)
- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(vec![(
- headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
- )])
+ Ok(vec![])
}
fn build_error_response(
@@ -139,13 +310,13 @@ impl ConnectorCommon for Tokenio {
Ok(ErrorResponse {
status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
+ code: response.get_error_code(),
+ message: response.get_message(),
+ reason: Some(response.get_message()),
attempt_status: None,
connector_transaction_id: None,
- network_advice_code: None,
network_decline_code: None,
+ network_advice_code: None,
network_error_message: None,
})
}
@@ -179,9 +350,10 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
- _connectors: &Connectors,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let base_url = self.base_url(connectors);
+ Ok(format!("{}/v2/payments", base_url))
}
fn get_request_body(
@@ -205,19 +377,34 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let auth = tokenio::TokenioAuthType::try_from(&req.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+
+ let url = self.get_url(req, connectors)?;
+ let body = self.get_request_body(req, connectors)?;
+
+ // Create JWT for authentication
+ let jwt = self.create_jwt_token(&auth, "POST", "/v2/payments", &body, connectors)?;
+
+ // Build headers with JWT authorization
+ let headers = vec![
+ (
+ headers::CONTENT_TYPE.to_string(),
+ "application/json".to_string().into(),
+ ),
+ (
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", jwt).into_masked(),
+ ),
+ ];
+
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ .url(&url)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(headers)
+ .set_body(body)
.build(),
))
}
@@ -256,7 +443,35 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tok
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
- self.build_headers(req, connectors)
+ // For GET requests, we need JWT with detached format (no body)
+ let auth = tokenio::TokenioAuthType::try_from(&req.connector_auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+
+ // Use empty RequestContent for GET requests - the create_jwt_token method
+ // will handle this properly by creating detached JWT
+ let empty_body = RequestContent::Json(Box::new(serde_json::json!({})));
+
+ let path = format!(
+ "/v2/payments/{}",
+ req.request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?
+ );
+
+ let jwt = self.create_jwt_token(&auth, "GET", &path, &empty_body, connectors)?;
+
+ let headers = vec![
+ (
+ headers::CONTENT_TYPE.to_string(),
+ "application/json".to_string().into(),
+ ),
+ (
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", jwt).into_masked(),
+ ),
+ ];
+ Ok(headers)
}
fn get_content_type(&self) -> &'static str {
@@ -265,10 +480,16 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tok
fn get_url(
&self,
- _req: &PaymentsSyncRouterData,
- _connectors: &Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_payment_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ let base_url = self.base_url(connectors);
+ Ok(format!("{}/v2/payments/{}", base_url, connector_payment_id))
}
fn build_request(
@@ -279,9 +500,9 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tok
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .url(&self.get_url(req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(self.get_headers(req, connectors)?)
.build(),
))
}
@@ -294,7 +515,7 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tok
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: tokenio::TokenioPaymentsResponse = res
.response
- .parse_struct("tokenio PaymentsSyncResponse")
+ .parse_struct("tokenio TokenioPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -315,232 +536,58 @@ impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Tok
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Tokenio {
- 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> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
-
- fn get_request_body(
+ fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
- ) -> CustomResult<RequestContent, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ Err(errors::ConnectorError::FlowNotSupported {
+ flow: "Capture".to_string(),
+ connector: "Tokenio".to_string(),
+ }
+ .into())
}
+}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Tokenio {
fn build_request(
&self,
- req: &PaymentsCaptureRouterData,
- connectors: &Connectors,
+ _req: &PaymentsCancelRouterData,
+ _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: tokenio::TokenioPaymentsResponse = res
- .response
- .parse_struct("Tokenio 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)
+ Err(errors::ConnectorError::FlowNotSupported {
+ flow: "Refunds".to_string(),
+ connector: "Tokenio".to_string(),
+ }
+ .into())
}
}
-impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Tokenio {}
-
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Tokenio {
- 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(
+ fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
-
- 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 = tokenio::TokenioRouterData::from((refund_amount, req));
- let connector_req = tokenio::TokenioRefundRequest::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: tokenio::RefundResponse = res
- .response
- .parse_struct("tokenio 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)
+ Err(errors::ConnectorError::FlowNotSupported {
+ flow: "Refunds".to_string(),
+ connector: "Tokenio".to_string(),
+ }
+ .into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Tokenio {
- 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(
+ fn build_request(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
-
- 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)?)
- .set_body(types::RefundSyncType::get_request_body(
- self, req, connectors,
- )?)
- .build(),
- ))
- }
-
- fn handle_response(
- &self,
- data: &RefundSyncRouterData,
- event_builder: Option<&mut ConnectorEvent>,
- res: Response,
- ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
- let response: tokenio::RefundResponse = res
- .response
- .parse_struct("tokenio 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)
+ Err(errors::ConnectorError::FlowNotSupported {
+ flow: "Refund Sync".to_string(),
+ connector: "Tokenio".to_string(),
+ }
+ .into())
}
}
@@ -548,24 +595,196 @@ impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Tokenio {
impl webhooks::IncomingWebhook for Tokenio {
fn get_webhook_object_reference_id(
&self,
- _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
- Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ let webhook_payload: tokenio::TokenioWebhookPayload = request
+ .body
+ .parse_struct("TokenioWebhookPayload")
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
+
+ match &webhook_payload.event_data {
+ tokenio::TokenioWebhookEventData::PaymentV2 { payment } => {
+ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::ConnectorTransactionId(payment.id.clone()),
+ ))
+ }
+ }
}
fn get_webhook_event_type(
&self,
- _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
- Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ // Check token-event header first
+ let event_type = if let Some(header_value) = request.headers.get("token-event") {
+ header_value
+ .to_str()
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?
+ .to_string()
+ } else {
+ // Fallback to parsing body for eventType field
+ let webhook_payload: tokenio::TokenioWebhookPayload = request
+ .body
+ .parse_struct("TokenioWebhookPayload")
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
+
+ webhook_payload
+ .event_type
+ .ok_or(errors::ConnectorError::WebhookEventTypeNotFound)?
+ };
+ match event_type.as_str() {
+ "PAYMENT_STATUS_CHANGED" => {
+ let webhook_payload: tokenio::TokenioWebhookPayload = request
+ .body
+ .parse_struct("TokenioWebhookPayload")
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
+
+ let tokenio::TokenioWebhookEventData::PaymentV2 { payment } =
+ &webhook_payload.event_data;
+
+ match payment.status {
+ TokenioPaymentStatus::InitiationCompleted => {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
+ }
+ TokenioPaymentStatus::PaymentCompleted => {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
+ }
+ TokenioPaymentStatus::PaymentFailed => {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
+ }
+ TokenioPaymentStatus::PaymentCancelled => {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentCancelled)
+ }
+ TokenioPaymentStatus::InitiationRejected => {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
+ }
+ TokenioPaymentStatus::InitiationProcessing => {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
+ }
+ TokenioPaymentStatus::InitiationPendingRedirectHp => {
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
+ }
+ TokenioPaymentStatus::Other => {
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
+ }
+ }
+ }
+ _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
+ }
}
fn get_webhook_resource_object(
&self,
- _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
- Err(report!(errors::ConnectorError::WebhooksNotImplemented))
+ let webhook_payload: tokenio::TokenioWebhookPayload = request
+ .body
+ .parse_struct("TokenioWebhookPayload")
+ .change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
+
+ Ok(Box::new(webhook_payload))
+ }
+ async fn verify_webhook_source(
+ &self,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ merchant_id: &common_utils::id_type::MerchantId,
+ connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
+ _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
+ connector_name: &str,
+ ) -> CustomResult<bool, errors::ConnectorError> {
+ let connector_webhook_secrets = self
+ .get_webhook_source_verification_merchant_secret(
+ merchant_id,
+ connector_name,
+ connector_webhook_details,
+ )
+ .await?;
+
+ // Convert UTF-8 bytes back to base64url string
+ let base64url_string = String::from_utf8(connector_webhook_secrets.secret)
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed to convert public key bytes to base64url string")?;
+
+ // Decode base64url string to actual ED25519 key bytes
+ let public_key_bytes = URL_SAFE_NO_PAD
+ .decode(&base64url_string)
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed to decode base64url public key to ED25519 bytes")?;
+
+ // Extract the signature from token-signature header
+ let signature_header = request
+ .headers
+ .get("token-signature")
+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)?
+ .to_str()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)
+ .attach_printable("Failed to convert token-signature header to string")?;
+
+ // Decode the base64url signature to bytes
+ let signature_bytes = URL_SAFE_NO_PAD
+ .decode(signature_header)
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)
+ .attach_printable("Failed to decode base64url signature")?;
+
+ // Get the raw message body (this is what Token.io signed)
+ let message_bytes = request.body;
+
+ // Use ED25519 to verify the signature
+ let ed25519 = crypto::Ed25519;
+ let is_valid = ed25519
+ .verify_signature(
+ &public_key_bytes,
+ &signature_bytes, // ED25519 signature (64 bytes)
+ message_bytes, // Raw webhook body
+ )
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("ED25519 signature verification failed")?;
+
+ Ok(is_valid)
}
}
-impl ConnectorSpecifications for Tokenio {}
+static TOKENIO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
+ let supported_capture_methods = vec![
+ enums::CaptureMethod::Automatic,
+ enums::CaptureMethod::Manual,
+ enums::CaptureMethod::SequentialAutomatic,
+ ];
+
+ let mut tokenio_supported_payment_methods = SupportedPaymentMethods::new();
+
+ // Open Banking - SEPA
+ tokenio_supported_payment_methods.add(
+ enums::PaymentMethod::OpenBanking,
+ PaymentMethodType::OpenBankingPIS,
+ PaymentMethodDetails {
+ mandates: FeatureStatus::NotSupported,
+ refunds: FeatureStatus::NotSupported,
+ supported_capture_methods: supported_capture_methods.clone(),
+ specific_features: None,
+ },
+ );
+ tokenio_supported_payment_methods
+});
+
+static TOKENIO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
+ display_name: "Token.io",
+ description: "Token.io is a financial technology company that provides Open Banking and real-time payment solutions across Europe. They enable secure bank-to-bank transfers using various payment rails including SEPA, Faster Payments, and other regional payment systems.",
+ connector_type: enums::PaymentConnectorCategory::PaymentGateway,
+};
+
+static TOKENIO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
+
+impl ConnectorSpecifications for Tokenio {
+ fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
+ Some(&TOKENIO_CONNECTOR_INFO)
+ }
+
+ fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
+ Some(&*TOKENIO_SUPPORTED_PAYMENT_METHODS)
+ }
+
+ fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
+ Some(&TOKENIO_SUPPORTED_WEBHOOK_FLOWS)
+ }
+}
diff --git a/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs b/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
index 4fdef952f5..ccacc4f2d4 100644
--- a/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
@@ -1,52 +1,122 @@
+use std::collections::HashMap;
+
+use api_models::admin::{AdditionalMerchantData, MerchantAccountData, MerchantRecipientData};
use common_enums::enums;
-use common_utils::types::StringMinorUnit;
+use common_utils::{id_type::MerchantId, request::Method, types::StringMajorUnit};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
- router_data::{ConnectorAuthType, RouterData},
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
- router_response_types::{PaymentsResponseData, RefundsResponseData},
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsAuthorizeRouterData, RefundsRouterData},
};
-use hyperswitch_interfaces::errors;
-use masking::Secret;
+use hyperswitch_interfaces::{
+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
+ errors,
+};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
- utils::PaymentsAuthorizeRequestData,
+ utils::{self},
};
//TODO: Fill the struct with respective fields
pub struct TokenioRouterData<T> {
- pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub amount: StringMajorUnit,
pub router_data: T,
}
-impl<T> From<(StringMinorUnit, T)> for TokenioRouterData<T> {
- fn from((amount, item): (StringMinorUnit, T)) -> Self {
- //Todo : use utils to convert the amount to the type of amount that a connector accepts
+impl<T> From<(StringMajorUnit, T)> for TokenioRouterData<T> {
+ fn from((amount, item): (StringMajorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
-
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, PartialEq)]
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct TokenioPaymentsRequest {
- amount: StringMinorUnit,
- card: TokenioCard,
+ pub initiation: PaymentInitiation,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct PaymentInitiation {
+ pub ref_id: String,
+ pub remittance_information_primary: MerchantId,
+ pub amount: Amount,
+ pub local_instrument: LocalInstrument,
+ pub creditor: Creditor,
+ pub callback_url: Option<String>,
+ pub flow_type: FlowType,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct Amount {
+ pub value: StringMajorUnit,
+ pub currency: enums::Currency,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum LocalInstrument {
+ Sepa,
+ SepaInstant,
+ FasterPayments,
+ Elixir,
+ Bankgiro,
+ Plusgiro,
+}
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(untagged)]
+pub enum Creditor {
+ FasterPayments {
+ #[serde(rename = "sortCode")]
+ sort_code: Secret<String>,
+ #[serde(rename = "accountNumber")]
+ account_number: Secret<String>,
+ name: Secret<String>,
+ },
+ Sepa {
+ iban: Secret<String>,
+ name: Secret<String>,
+ },
+ SepaInstant {
+ iban: Secret<String>,
+ name: Secret<String>,
+ },
+ ElixirIban {
+ iban: Secret<String>,
+ name: Secret<String>,
+ },
+ ElixirAccount {
+ #[serde(rename = "accountNumber")]
+ account_number: Secret<String>,
+ name: Secret<String>,
+ },
+ Bankgiro {
+ #[serde(rename = "bankgiroNumber")]
+ bankgiro_number: Secret<String>,
+ name: Secret<String>,
+ },
+ Plusgiro {
+ #[serde(rename = "plusgiroNumber")]
+ plusgiro_number: Secret<String>,
+ name: Secret<String>,
+ },
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct TokenioCard {
- number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+#[derive(Serialize, Deserialize, Debug)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum FlowType {
+ ApiOnly,
+ FullHostedPages,
+ EmbeddedHostedPages,
}
impl TryFrom<&TokenioRouterData<&PaymentsAuthorizeRouterData>> for TokenioPaymentsRequest {
@@ -55,17 +125,133 @@ impl TryFrom<&TokenioRouterData<&PaymentsAuthorizeRouterData>> for TokenioPaymen
item: &TokenioRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
- PaymentMethodData::Card(req_card) => {
- let card = TokenioCard {
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
- cvc: req_card.card_cvc,
- complete: item.router_data.request.is_auto_capture()?,
+ PaymentMethodData::OpenBanking(_) => {
+ let (local_instrument, creditor) = match item
+ .router_data
+ .additional_merchant_data
+ .as_ref()
+ .and_then(|data| match data {
+ AdditionalMerchantData::OpenBankingRecipientData(recipient_data) => {
+ match recipient_data {
+ MerchantRecipientData::AccountData(account_data) => {
+ Some(account_data)
+ }
+ _ => None,
+ }
+ }
+ }) {
+ Some(MerchantAccountData::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ ..
+ }) => (
+ LocalInstrument::FasterPayments,
+ Creditor::FasterPayments {
+ sort_code: sort_code.clone(),
+ account_number: account_number.clone(),
+ name: name.clone().into(),
+ },
+ ),
+
+ Some(MerchantAccountData::SepaInstant { iban, name, .. }) => (
+ LocalInstrument::SepaInstant,
+ Creditor::SepaInstant {
+ iban: iban.clone(),
+ name: name.clone().into(),
+ },
+ ),
+
+ Some(MerchantAccountData::Sepa { iban, name, .. }) => (
+ LocalInstrument::Sepa,
+ Creditor::Sepa {
+ iban: iban.clone(),
+ name: name.clone().into(),
+ },
+ ),
+
+ Some(MerchantAccountData::Iban { iban, name, .. }) => (
+ LocalInstrument::Sepa, // Assuming IBAN defaults to SEPA
+ Creditor::Sepa {
+ iban: iban.clone(),
+ name: name.clone().into(),
+ },
+ ),
+
+ Some(MerchantAccountData::Elixir {
+ account_number,
+ iban,
+ name,
+ ..
+ }) => {
+ if !iban.peek().is_empty() {
+ (
+ LocalInstrument::Elixir,
+ Creditor::ElixirIban {
+ iban: iban.clone(),
+ name: name.clone().into(),
+ },
+ )
+ } else {
+ (
+ LocalInstrument::Elixir,
+ Creditor::ElixirAccount {
+ account_number: account_number.clone(),
+ name: name.clone().into(),
+ },
+ )
+ }
+ }
+ Some(MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ ..
+ }) => (
+ LocalInstrument::FasterPayments,
+ Creditor::FasterPayments {
+ sort_code: sort_code.clone(),
+ account_number: account_number.clone(),
+ name: name.clone().into(),
+ },
+ ),
+
+ Some(MerchantAccountData::Bankgiro { number, name, .. }) => (
+ LocalInstrument::Bankgiro,
+ Creditor::Bankgiro {
+ bankgiro_number: number.clone(),
+ name: name.clone().into(),
+ },
+ ),
+
+ Some(MerchantAccountData::Plusgiro { number, name, .. }) => (
+ LocalInstrument::Plusgiro,
+ Creditor::Plusgiro {
+ plusgiro_number: number.clone(),
+ name: name.clone().into(),
+ },
+ ),
+
+ None => {
+ return Err(errors::ConnectorError::InvalidConnectorConfig {
+ config: "No valid payment method found in additional merchant data",
+ }
+ .into())
+ }
};
Ok(Self {
- amount: item.amount.clone(),
- card,
+ initiation: PaymentInitiation {
+ ref_id: utils::generate_12_digit_number().to_string(),
+ remittance_information_primary: item.router_data.merchant_id.clone(),
+ amount: Amount {
+ value: item.amount.clone(),
+ currency: item.router_data.request.currency,
+ },
+ local_instrument,
+ creditor,
+ callback_url: item.router_data.request.router_return_url.clone(),
+ flow_type: FlowType::FullHostedPages,
+ },
})
}
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
@@ -73,49 +259,155 @@ impl TryFrom<&TokenioRouterData<&PaymentsAuthorizeRouterData>> for TokenioPaymen
}
}
-//TODO: Fill the struct with respective fields
-// Auth Struct
pub struct TokenioAuthType {
- pub(super) api_key: Secret<String>,
+ pub(super) merchant_id: Secret<String>,
+ pub(super) private_key: Secret<String>,
+ pub(super) key_id: Secret<String>,
+ pub(super) key_algorithm: CryptoAlgorithm,
}
+#[derive(Debug, Deserialize, PartialEq)]
+pub enum CryptoAlgorithm {
+ RS256,
+ ES256,
+ #[serde(rename = "EdDSA")]
+ EDDSA,
+}
+
+impl TryFrom<&str> for CryptoAlgorithm {
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(s: &str) -> Result<Self, Self::Error> {
+ match s.to_uppercase().as_str() {
+ "RS256" | "rs256" => Ok(Self::RS256),
+ "ES256" | "es256" => Ok(Self::ES256),
+ "EDDSA" | "eddsa" | "EdDSA" => Ok(Self::EDDSA),
+ _ => Err(errors::ConnectorError::InvalidConnectorConfig {
+ config: "Unsupported key algorithm. Select from RS256, ES256, EdDSA",
+ }
+ .into()),
+ }
+ }
+}
impl TryFrom<&ConnectorAuthType> for TokenioAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
+
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_owned(),
+ ConnectorAuthType::MultiAuthKey {
+ api_key,
+ key1,
+ api_secret,
+ key2,
+ } => Ok(Self {
+ merchant_id: key1.to_owned(),
+ private_key: api_secret.to_owned(),
+ key_id: api_key.to_owned(),
+ key_algorithm: CryptoAlgorithm::try_from(key2.clone().expose().as_str())?,
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
-// PaymentsResponse
-//TODO: Append the remaining status flags
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "lowercase")]
-pub enum TokenioPaymentStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
+
+#[derive(Debug, Serialize, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TokenioApiWrapper {
+ pub payment: PaymentResponse,
+}
+#[derive(Debug, Serialize, Clone, Deserialize)]
+#[serde(untagged)]
+pub enum TokenioPaymentsResponse {
+ Success(TokenioApiWrapper),
+ Error(TokenioErrorResponse),
}
-impl From<TokenioPaymentStatus> for common_enums::AttemptStatus {
- fn from(item: TokenioPaymentStatus) -> Self {
- match item {
- TokenioPaymentStatus::Succeeded => Self::Charged,
- TokenioPaymentStatus::Failed => Self::Failure,
- TokenioPaymentStatus::Processing => Self::Authorizing,
- }
- }
+#[derive(Debug, Serialize, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PaymentResponse {
+ pub id: String,
+ pub status: PaymentStatus,
+ pub status_reason_information: Option<String>,
+ pub authentication: Option<Authentication>,
+ pub error_info: Option<ErrorInfo>,
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
-pub struct TokenioPaymentsResponse {
- status: TokenioPaymentStatus,
- id: String,
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum PaymentStatus {
+ InitiationPending,
+ InitiationPendingRedirectAuth,
+ InitiationPendingRedirectAuthVerification,
+ InitiationPendingRedirectHp,
+ InitiationPendingRedemption,
+ InitiationPendingRedemptionVerification,
+ InitiationProcessing,
+ InitiationCompleted,
+ InitiationRejected,
+ InitiationRejectedInsufficientFunds,
+ InitiationFailed,
+ InitiationDeclined,
+ InitiationExpired,
+ InitiationNoFinalStatusAvailable,
+ SettlementInProgress,
+ SettlementCompleted,
+ SettlementIncomplete,
+}
+
+#[derive(Debug, Serialize, Clone, Deserialize)]
+#[serde(untagged)]
+pub enum Authentication {
+ RedirectUrl {
+ #[serde(rename = "redirectUrl")]
+ redirect_url: String,
+ },
+}
+
+#[derive(Debug, Serialize, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ErrorInfo {
+ pub http_error_code: i32,
+ pub message: Option<String>,
+ pub token_external_error: Option<bool>,
+ pub token_trace_id: Option<String>,
+}
+
+impl From<TokenioPaymentsResponse> for common_enums::AttemptStatus {
+ fn from(response: TokenioPaymentsResponse) -> Self {
+ match response {
+ TokenioPaymentsResponse::Success(wrapper) => match wrapper.payment.status {
+ // Pending statuses - payment is still in progress
+ PaymentStatus::InitiationPending
+ | PaymentStatus::InitiationPendingRedirectAuth
+ | PaymentStatus::InitiationPendingRedirectAuthVerification
+ | PaymentStatus::InitiationPendingRedirectHp
+ | PaymentStatus::InitiationPendingRedemption
+ | PaymentStatus::InitiationPendingRedemptionVerification => {
+ Self::AuthenticationPending
+ }
+
+ // Success statuses
+ PaymentStatus::SettlementCompleted => Self::Charged,
+
+ // Settlement in progress - could map to different status based on business logic
+ PaymentStatus::SettlementInProgress => Self::Pending,
+
+ // Failure statuses
+ PaymentStatus::InitiationRejected
+ | PaymentStatus::InitiationFailed
+ | PaymentStatus::InitiationExpired
+ | PaymentStatus::InitiationRejectedInsufficientFunds
+ | PaymentStatus::InitiationDeclined => Self::Failure,
+
+ // Uncertain status
+ PaymentStatus::InitiationCompleted
+ | PaymentStatus::InitiationProcessing
+ | PaymentStatus::InitiationNoFinalStatusAvailable
+ | PaymentStatus::SettlementIncomplete => Self::Pending,
+ },
+ TokenioPaymentsResponse::Error(_) => Self::Failure,
+ }
+ }
}
impl<F, T> TryFrom<ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>>
@@ -125,29 +417,84 @@ impl<F, T> TryFrom<ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsRes
fn try_from(
item: ResponseRouterData<F, TokenioPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
- Ok(Self {
- status: common_enums::AttemptStatus::from(item.response.status),
- response: Ok(PaymentsResponseData::TransactionResponse {
- resource_id: ResponseId::ConnectorTransactionId(item.response.id),
- 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,
+ let status = common_enums::AttemptStatus::from(item.response.clone());
+ let response = match item.response {
+ TokenioPaymentsResponse::Success(wrapper) => {
+ let payment = wrapper.payment;
+ if let common_enums::AttemptStatus::Failure = status {
+ Err(ErrorResponse {
+ code: payment
+ .error_info
+ .as_ref()
+ .map(|ei| ei.http_error_code.to_string())
+ .unwrap_or_else(|| NO_ERROR_CODE.to_string()),
+ message: payment
+ .error_info
+ .as_ref()
+ .and_then(|ei| ei.message.clone())
+ .or_else(|| payment.status_reason_information.clone())
+ .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
+ reason: Some(
+ payment
+ .error_info
+ .as_ref()
+ .and_then(|ei| ei.message.clone())
+ .or_else(|| payment.status_reason_information.clone())
+ .unwrap_or_else(|| NO_ERROR_MESSAGE.to_string()),
+ ),
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(payment.id.clone()),
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ })
+ } else {
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(payment.id.clone()),
+ redirection_data: Box::new(payment.authentication.as_ref().map(|auth| {
+ match auth {
+ Authentication::RedirectUrl { redirect_url } => {
+ RedirectForm::Form {
+ endpoint: redirect_url.to_string(),
+ method: Method::Get,
+ form_fields: HashMap::new(),
+ }
+ }
+ }
+ })),
+ mandate_reference: Box::new(None),
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: None,
+ incremental_authorization_allowed: None,
+ charges: None,
+ })
+ }
+ }
+ TokenioPaymentsResponse::Error(error_response) => Err(ErrorResponse {
+ code: error_response.get_error_code(),
+ message: error_response.get_message(),
+ reason: Some(error_response.get_message()),
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
}),
+ };
+ Ok(Self {
+ status,
+ response,
..item.data
})
}
}
-//TODO: Fill the struct with respective fields
-// REFUND :
-// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
pub struct TokenioRefundRequest {
- pub amount: StringMinorUnit,
+ pub amount: StringMajorUnit,
}
impl<F> TryFrom<&TokenioRouterData<&RefundsRouterData<F>>> for TokenioRefundRequest {
@@ -159,8 +506,6 @@ impl<F> TryFrom<&TokenioRouterData<&RefundsRouterData<F>>> for TokenioRefundRequ
}
}
-// Type definition for Refund Response
-
#[allow(dead_code)]
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
@@ -218,11 +563,102 @@ impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouter
}
}
-//TODO: Fill the struct with respective fields
-#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
-pub struct TokenioErrorResponse {
- pub status_code: u16,
- pub code: String,
- pub message: String,
- pub reason: Option<String>,
+#[derive(Debug, Serialize, Clone, Deserialize)]
+#[serde(untagged)]
+pub enum TokenioErrorResponse {
+ Json {
+ #[serde(rename = "errorCode")]
+ error_code: Option<String>,
+ message: Option<String>,
+ },
+ Text(String),
+}
+impl TokenioErrorResponse {
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ // First try to parse as JSON
+ if let Ok(json_response) = serde_json::from_slice::<Self>(bytes) {
+ json_response
+ } else {
+ // If JSON parsing fails, treat as plain text
+ let text = String::from_utf8_lossy(bytes).to_string();
+ Self::Text(text)
+ }
+ }
+ pub fn get_message(&self) -> String {
+ match self {
+ Self::Json {
+ message,
+ error_code,
+ } => message
+ .as_deref()
+ .or(error_code.as_deref())
+ .unwrap_or(NO_ERROR_MESSAGE)
+ .to_string(),
+ Self::Text(text) => text.clone(),
+ }
+ }
+
+ pub fn get_error_code(&self) -> String {
+ match self {
+ Self::Json { error_code, .. } => {
+ error_code.as_deref().unwrap_or(NO_ERROR_CODE).to_string()
+ }
+ Self::Text(_) => NO_ERROR_CODE.to_string(),
+ }
+ }
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum TokenioWebhookEventType {
+ PaymentStatusChanged,
+ #[serde(other)]
+ Unknown,
+}
+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum TokenioWebhookPaymentStatus {
+ InitiationCompleted,
+ PaymentCompleted,
+ PaymentFailed,
+ PaymentCancelled,
+ InitiationRejected,
+ InitiationProcessing,
+ #[serde(other)]
+ Unknown,
+}
+
+// Base webhook payload structure
+#[derive(Debug, Deserialize, Serialize)]
+pub struct TokenioWebhookPayload {
+ #[serde(rename = "eventType", skip_serializing_if = "Option::is_none")]
+ pub event_type: Option<String>,
+ pub id: String,
+ #[serde(flatten)]
+ pub event_data: TokenioWebhookEventData,
+}
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum TokenioWebhookEventData {
+ PaymentV2 { payment: TokenioPaymentObjectV2 },
+}
+
+// Payment v2 structures
+#[derive(Debug, Deserialize, Serialize)]
+pub struct TokenioPaymentObjectV2 {
+ pub id: String,
+ pub status: TokenioPaymentStatus,
+}
+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum TokenioPaymentStatus {
+ InitiationCompleted,
+ PaymentCompleted,
+ PaymentFailed,
+ PaymentCancelled,
+ InitiationRejected,
+ InitiationProcessing,
+ InitiationPendingRedirectHp,
+ #[serde(other)]
+ Other,
}
diff --git a/crates/pm_auth/src/connector/plaid.rs b/crates/pm_auth/src/connector/plaid.rs
index 6f91b2cb1a..0d933bf6a6 100644
--- a/crates/pm_auth/src/connector/plaid.rs
+++ b/crates/pm_auth/src/connector/plaid.rs
@@ -378,7 +378,7 @@ impl
&self,
req: &auth_types::RecipientCreateRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
- let req_obj = plaid::PlaidRecipientCreateRequest::from(req);
+ let req_obj = plaid::PlaidRecipientCreateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs
index a10ff0d60e..b15207770d 100644
--- a/crates/pm_auth/src/connector/plaid/transformers.rs
+++ b/crates/pm_auth/src/connector/plaid/transformers.rs
@@ -152,21 +152,32 @@ pub enum PlaidRecipientAccountData {
},
}
-impl From<&types::RecipientAccountData> for PlaidRecipientAccountData {
- fn from(item: &types::RecipientAccountData) -> Self {
+impl TryFrom<&types::RecipientAccountData> for PlaidRecipientAccountData {
+ type Error = errors::ConnectorError;
+
+ fn try_from(item: &types::RecipientAccountData) -> Result<Self, Self::Error> {
match item {
- types::RecipientAccountData::Iban(iban) => Self::Iban(iban.clone()),
+ types::RecipientAccountData::Iban(iban) => Ok(Self::Iban(iban.clone())),
types::RecipientAccountData::Bacs {
sort_code,
account_number,
- } => Self::Bacs {
+ } => Ok(Self::Bacs {
sort_code: sort_code.clone(),
account: account_number.clone(),
- },
+ }),
+ types::RecipientAccountData::FasterPayments { .. }
+ | types::RecipientAccountData::Sepa(_)
+ | types::RecipientAccountData::SepaInstant(_)
+ | types::RecipientAccountData::Elixir { .. }
+ | types::RecipientAccountData::Bankgiro(_)
+ | types::RecipientAccountData::Plusgiro(_) => {
+ Err(errors::ConnectorError::InvalidConnectorConfig {
+ config: "Invalid payment method selected. Only Iban, Bacs Supported",
+ })
+ }
}
}
}
-
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateAddress {
pub street: String,
@@ -186,17 +197,19 @@ impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress {
}
}
-impl From<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest {
- fn from(item: &types::RecipientCreateRouterData) -> Self {
- Self {
+impl TryFrom<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest {
+ type Error = errors::ConnectorError;
+
+ fn try_from(item: &types::RecipientCreateRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
name: item.request.name.clone(),
- account_data: PlaidRecipientAccountData::from(&item.request.account_data),
+ account_data: PlaidRecipientAccountData::try_from(&item.request.account_data)?,
address: item
.request
.address
.as_ref()
.map(PlaidRecipientCreateAddress::from),
- }
+ })
}
}
diff --git a/crates/pm_auth/src/core/errors.rs b/crates/pm_auth/src/core/errors.rs
index 31b178a627..6d7855b198 100644
--- a/crates/pm_auth/src/core/errors.rs
+++ b/crates/pm_auth/src/core/errors.rs
@@ -10,8 +10,9 @@ pub enum ConnectorError {
ResponseDeserializationFailed,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
+ #[error("Invalid connector configuration: {config}")]
+ InvalidConnectorConfig { config: &'static str },
}
-
pub type CustomResult<T, E> = error_stack::Result<T, E>;
#[derive(Debug, thiserror::Error)]
diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs
index bae9ee5984..fbef8fadb5 100644
--- a/crates/pm_auth/src/types.rs
+++ b/crates/pm_auth/src/types.rs
@@ -135,8 +135,19 @@ pub enum RecipientAccountData {
sort_code: Secret<String>,
account_number: Secret<String>,
},
+ FasterPayments {
+ sort_code: Secret<String>,
+ account_number: Secret<String>,
+ },
+ Sepa(Secret<String>),
+ SepaInstant(Secret<String>),
+ Elixir {
+ account_number: Secret<String>,
+ iban: Secret<String>,
+ },
+ Bankgiro(Secret<String>),
+ Plusgiro(Secret<String>),
}
-
#[derive(Debug, Clone)]
pub struct RecipientCreateAddress {
pub street: String,
@@ -206,6 +217,32 @@ pub enum MerchantAccountData {
sort_code: Secret<String>,
name: String,
},
+ FasterPayments {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ name: String,
+ },
+ Sepa {
+ iban: Secret<String>,
+ name: String,
+ },
+ SepaInstant {
+ iban: Secret<String>,
+ name: String,
+ },
+ Elixir {
+ account_number: Secret<String>,
+ iban: Secret<String>,
+ name: String,
+ },
+ Bankgiro {
+ number: Secret<String>,
+ name: String,
+ },
+ Plusgiro {
+ number: Secret<String>,
+ name: String,
+ },
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 9f6ce920a5..19b28f36d1 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -220,6 +220,39 @@ pub const AUTHENTICATION_SERVICE_ELIGIBLE_CONFIG: &str =
/// Refund flow identifier used for performing GSM operations
pub const REFUND_FLOW_STR: &str = "refund_flow";
+/// Minimum IBAN length (country-dependent), as per ISO 13616 standard
+pub const IBAN_MIN_LENGTH: usize = 15;
+
+/// Maximum IBAN length defined by the ISO 13616 standard (standard max)
+pub const IBAN_MAX_LENGTH: usize = 34;
+
+/// Minimum UK BACS account number length in digits
+pub const BACS_MIN_ACCOUNT_NUMBER_LENGTH: usize = 6;
+
+/// Maximum UK BACS account number length in digits
+pub const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8;
+
+/// Fixed length of UK BACS sort code in digits (always 6)
+pub const BACS_SORT_CODE_LENGTH: usize = 6;
+
+/// Exact length of Polish Elixir system domestic account number (NRB) in digits
+pub const ELIXIR_ACCOUNT_NUMBER_LENGTH: usize = 26;
+
+/// Total length of Polish IBAN including country code and checksum (28 characters)
+pub const ELIXIR_IBAN_LENGTH: usize = 28;
+
+/// Minimum length of Swedish Bankgiro number in digits
+pub const BANKGIRO_MIN_LENGTH: usize = 7;
+
+/// Maximum length of Swedish Bankgiro number in digits
+pub const BANKGIRO_MAX_LENGTH: usize = 8;
+
+/// Minimum length of Swedish Plusgiro number in digits
+pub const PLUSGIRO_MIN_LENGTH: usize = 2;
+
+/// Maximum length of Swedish Plusgiro number in digits
+pub const PLUSGIRO_MAX_LENGTH: usize = 8;
+
/// Default payment method session expiry
pub const DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY: u32 = 15 * 60; // 15 minutes
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 94bf54a9f9..b8d24573c3 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -11,9 +11,9 @@ use common_utils::{
fp_utils, id_type, pii, type_name,
types::keymanager::{self as km_types, KeyManagerState, ToEncryptable},
};
-use diesel_models::configs;
#[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))]
use diesel_models::{business_profile::CardTestingGuardConfig, organization::OrganizationBridge};
+use diesel_models::{configs, payment_method};
use error_stack::{report, FutureExt, ResultExt};
use external_services::http_client::client;
use hyperswitch_domain_models::merchant_connector_account::{
@@ -21,7 +21,6 @@ use hyperswitch_domain_models::merchant_connector_account::{
};
use masking::{ExposeInterface, PeekInterface, Secret};
use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types};
-use regex::Regex;
use uuid::Uuid;
#[cfg(any(feature = "v1", feature = "v2"))]
@@ -56,10 +55,6 @@ use crate::{
utils,
};
-const IBAN_MAX_LENGTH: usize = 34;
-const BACS_SORT_CODE_LENGTH: usize = 6;
-const BACS_MAX_ACCOUNT_NUMBER_LENGTH: usize = 8;
-
#[inline]
pub fn create_merchant_publishable_key() -> String {
format!(
@@ -1735,10 +1730,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> {
trustpay::transformers::TrustpayAuthType::try_from(self.auth_type)?;
Ok(())
}
- // api_enums::Connector::Tokenio => {
- // tokenio::transformers::TokenioAuthType::try_from(self.auth_type)?;
- // Ok(())
- // }
+ api_enums::Connector::Tokenio => {
+ tokenio::transformers::TokenioAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Tsys => {
tsys::transformers::TsysAuthType::try_from(self.auth_type)?;
Ok(())
@@ -2379,6 +2374,7 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
&self.connector_type,
&mca.connector_name,
types::AdditionalMerchantData::foreign_from(data.clone()),
+ merchant_context.get_merchant_key_store(),
)
.await?,
)
@@ -2561,6 +2557,7 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnect
&self.connector_type,
&connector_enum,
types::AdditionalMerchantData::foreign_from(data.clone()),
+ merchant_context.get_merchant_key_store(),
)
.await?,
)
@@ -2708,6 +2705,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
&self.connector_type,
&self.connector_name,
types::AdditionalMerchantData::foreign_from(data.clone()),
+ &key_store,
)
.await?,
)
@@ -2913,6 +2911,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {
&self.connector_type,
&self.connector_name,
types::AdditionalMerchantData::foreign_from(data.clone()),
+ &key_store,
)
.await?,
)
@@ -5013,6 +5012,7 @@ async fn process_open_banking_connectors(
connector_type: &api_enums::ConnectorType,
connector: &api_enums::Connector,
additional_merchant_data: types::AdditionalMerchantData,
+ key_store: &domain::MerchantKeyStore,
) -> RouterResult<types::MerchantRecipientData> {
let new_merchant_data = match additional_merchant_data {
types::AdditionalMerchantData::OpenBankingRecipientData(merchant_data) => {
@@ -5026,7 +5026,7 @@ async fn process_open_banking_connectors(
}
match &merchant_data {
types::MerchantRecipientData::AccountData(acc_data) => {
- validate_bank_account_data(acc_data)?;
+ core_utils::validate_bank_account_data(acc_data)?;
let connector_name = api_enums::Connector::to_string(connector);
@@ -5035,9 +5035,8 @@ async fn process_open_banking_connectors(
.locker_based_open_banking_connectors
.connector_list
.contains(connector_name.as_str());
-
let recipient_id = if recipient_creation_not_supported {
- locker_recipient_create_call(state, merchant_id, acc_data).await
+ locker_recipient_create_call(state, merchant_id, acc_data, key_store).await
} else {
connector_recipient_create_call(
state,
@@ -5077,6 +5076,56 @@ async fn process_open_banking_connectors(
name: name.clone(),
connector_recipient_id: conn_recipient_id.clone(),
},
+ types::MerchantAccountData::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ ..
+ } => types::MerchantAccountData::FasterPayments {
+ account_number: account_number.clone(),
+ sort_code: sort_code.clone(),
+ name: name.clone(),
+ connector_recipient_id: conn_recipient_id.clone(),
+ },
+ types::MerchantAccountData::Sepa { iban, name, .. } => {
+ types::MerchantAccountData::Sepa {
+ iban: iban.clone(),
+ name: name.clone(),
+ connector_recipient_id: conn_recipient_id.clone(),
+ }
+ }
+ types::MerchantAccountData::SepaInstant { iban, name, .. } => {
+ types::MerchantAccountData::SepaInstant {
+ iban: iban.clone(),
+ name: name.clone(),
+ connector_recipient_id: conn_recipient_id.clone(),
+ }
+ }
+ types::MerchantAccountData::Elixir {
+ account_number,
+ iban,
+ name,
+ ..
+ } => types::MerchantAccountData::Elixir {
+ account_number: account_number.clone(),
+ iban: iban.clone(),
+ name: name.clone(),
+ connector_recipient_id: conn_recipient_id.clone(),
+ },
+ types::MerchantAccountData::Bankgiro { number, name, .. } => {
+ types::MerchantAccountData::Bankgiro {
+ number: number.clone(),
+ name: name.clone(),
+ connector_recipient_id: conn_recipient_id.clone(),
+ }
+ }
+ types::MerchantAccountData::Plusgiro { number, name, .. } => {
+ types::MerchantAccountData::Plusgiro {
+ number: number.clone(),
+ name: name.clone(),
+ connector_recipient_id: conn_recipient_id.clone(),
+ }
+ }
};
types::MerchantRecipientData::AccountData(account_data)
@@ -5089,87 +5138,6 @@ async fn process_open_banking_connectors(
Ok(new_merchant_data)
}
-fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> {
- match data {
- types::MerchantAccountData::Iban { iban, .. } => {
- // IBAN check algorithm
- if iban.peek().len() > IBAN_MAX_LENGTH {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "IBAN length must be up to 34 characters".to_string(),
- }
- .into());
- }
- let pattern = Regex::new(r"^[A-Z0-9]*$")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to create regex pattern")?;
-
- let mut iban = iban.peek().to_string();
-
- if !pattern.is_match(iban.as_str()) {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "IBAN data must be alphanumeric".to_string(),
- }
- .into());
- }
-
- // MOD check
- let first_4 = iban.chars().take(4).collect::<String>();
- iban.push_str(first_4.as_str());
- let len = iban.len();
-
- let rearranged_iban = iban
- .chars()
- .rev()
- .take(len - 4)
- .collect::<String>()
- .chars()
- .rev()
- .collect::<String>();
-
- let mut result = String::new();
-
- rearranged_iban.chars().for_each(|c| {
- if c.is_ascii_uppercase() {
- let digit = (u32::from(c) - u32::from('A')) + 10;
- result.push_str(&format!("{:02}", digit));
- } else {
- result.push(c);
- }
- });
-
- let num = result
- .parse::<u128>()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to validate IBAN")?;
-
- if num % 97 != 1 {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "Invalid IBAN".to_string(),
- }
- .into());
- }
-
- Ok(())
- }
- types::MerchantAccountData::Bacs {
- account_number,
- sort_code,
- ..
- } => {
- if account_number.peek().len() > BACS_MAX_ACCOUNT_NUMBER_LENGTH
- || sort_code.peek().len() != BACS_SORT_CODE_LENGTH
- {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "Invalid BACS numbers".to_string(),
- }
- .into());
- }
-
- Ok(())
- }
- }
-}
-
async fn connector_recipient_create_call(
state: &SessionState,
merchant_id: &id_type::MerchantId,
@@ -5192,29 +5160,7 @@ async fn connector_recipient_create_call(
pm_auth_types::RecipientCreateResponse,
> = connector.connector.get_connector_integration();
- let req = match data {
- types::MerchantAccountData::Iban { iban, name, .. } => {
- pm_auth_types::RecipientCreateRequest {
- name: name.clone(),
- account_data: pm_auth_types::RecipientAccountData::Iban(iban.clone()),
- address: None,
- }
- }
- types::MerchantAccountData::Bacs {
- account_number,
- sort_code,
- name,
- ..
- } => pm_auth_types::RecipientCreateRequest {
- name: name.clone(),
- account_data: pm_auth_types::RecipientAccountData::Bacs {
- sort_code: sort_code.clone(),
- account_number: account_number.clone(),
- },
- address: None,
- },
- };
-
+ let req = pm_auth_types::RecipientCreateRequest::from(data);
let router_data = pm_auth_types::RecipientCreateRouterData {
flow: std::marker::PhantomData,
merchant_id: Some(merchant_id.to_owned()),
@@ -5254,16 +5200,33 @@ async fn connector_recipient_create_call(
Ok(recipient_id)
}
-
async fn locker_recipient_create_call(
state: &SessionState,
merchant_id: &id_type::MerchantId,
data: &types::MerchantAccountData,
+ key_store: &domain::MerchantKeyStore,
) -> RouterResult<String> {
- let enc_data = serde_json::to_string(data)
+ let key_manager_state = &state.into();
+ let key = key_store.key.get_inner().peek();
+ let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone());
+
+ let data_json = serde_json::to_string(data)
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to convert to MerchantAccountData json to String")?;
+ .attach_printable("Failed to serialize MerchantAccountData to JSON")?;
+
+ let encrypted_data = domain_types::crypto_operation(
+ key_manager_state,
+ type_name!(payment_method::PaymentMethod),
+ domain_types::CryptoOperation::Encrypt(Secret::<String, masking::WithType>::new(data_json)),
+ identifier,
+ key,
+ )
+ .await
+ .and_then(|val| val.try_into_operation())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encrypt merchant account data")?;
+ let enc_data = hex::encode(encrypted_data.into_encrypted().expose());
let merchant_id_string = merchant_id.get_string_repr().to_owned();
let cust_id = id_type::CustomerId::try_from(std::borrow::Cow::from(merchant_id_string))
@@ -5321,3 +5284,72 @@ pub async fn enable_platform_account(
.attach_printable("Error while enabling platform merchant account")
.map(|_| services::ApplicationResponse::StatusOk)
}
+
+impl From<&types::MerchantAccountData> for pm_auth_types::RecipientCreateRequest {
+ fn from(data: &types::MerchantAccountData) -> Self {
+ let (name, account_data) = match data {
+ types::MerchantAccountData::Iban { iban, name, .. } => (
+ name.clone(),
+ pm_auth_types::RecipientAccountData::Iban(iban.clone()),
+ ),
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ ..
+ } => (
+ name.clone(),
+ pm_auth_types::RecipientAccountData::Bacs {
+ sort_code: sort_code.clone(),
+ account_number: account_number.clone(),
+ },
+ ),
+ types::MerchantAccountData::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ ..
+ } => (
+ name.clone(),
+ pm_auth_types::RecipientAccountData::FasterPayments {
+ sort_code: sort_code.clone(),
+ account_number: account_number.clone(),
+ },
+ ),
+ types::MerchantAccountData::Sepa { iban, name, .. } => (
+ name.clone(),
+ pm_auth_types::RecipientAccountData::Sepa(iban.clone()),
+ ),
+ types::MerchantAccountData::SepaInstant { iban, name, .. } => (
+ name.clone(),
+ pm_auth_types::RecipientAccountData::SepaInstant(iban.clone()),
+ ),
+ types::MerchantAccountData::Elixir {
+ account_number,
+ iban,
+ name,
+ ..
+ } => (
+ name.clone(),
+ pm_auth_types::RecipientAccountData::Elixir {
+ account_number: account_number.clone(),
+ iban: iban.clone(),
+ },
+ ),
+ types::MerchantAccountData::Bankgiro { number, name, .. } => (
+ name.clone(),
+ pm_auth_types::RecipientAccountData::Bankgiro(number.clone()),
+ ),
+ types::MerchantAccountData::Plusgiro { number, name, .. } => (
+ name.clone(),
+ pm_auth_types::RecipientAccountData::Plusgiro(number.clone()),
+ ),
+ };
+
+ Self {
+ name,
+ account_data,
+ address: None,
+ }
+ }
+}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 539298ac53..7706eda095 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2018,9 +2018,7 @@ pub async fn decode_and_decrypt_locker_data(
key_store: &domain::MerchantKeyStore,
enc_card_data: String,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
- // Fetch key
let key = key_store.key.get_inner().peek();
- // Decode
let decoded_bytes = hex::decode(&enc_card_data)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed to decode hex string into bytes")?;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 3099e8c54d..dc1b06e852 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -6336,28 +6336,50 @@ pub fn get_recipient_id_for_open_banking(
match merchant_data {
AdditionalMerchantData::OpenBankingRecipientData(data) => match data {
MerchantRecipientData::ConnectorRecipientId(id) => Ok(Some(id.peek().clone())),
- MerchantRecipientData::AccountData(acc_data) => match acc_data {
- MerchantAccountData::Bacs {
- connector_recipient_id,
- ..
- } => match connector_recipient_id {
- Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())),
- Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())),
- _ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
- config: "recipient_id".to_string(),
- }),
- },
- MerchantAccountData::Iban {
- connector_recipient_id,
- ..
- } => match connector_recipient_id {
+ MerchantRecipientData::AccountData(acc_data) => {
+ let connector_recipient_id = match acc_data {
+ MerchantAccountData::Bacs {
+ connector_recipient_id,
+ ..
+ }
+ | MerchantAccountData::Iban {
+ connector_recipient_id,
+ ..
+ }
+ | MerchantAccountData::FasterPayments {
+ connector_recipient_id,
+ ..
+ }
+ | MerchantAccountData::Sepa {
+ connector_recipient_id,
+ ..
+ }
+ | MerchantAccountData::SepaInstant {
+ connector_recipient_id,
+ ..
+ }
+ | MerchantAccountData::Elixir {
+ connector_recipient_id,
+ ..
+ }
+ | MerchantAccountData::Bankgiro {
+ connector_recipient_id,
+ ..
+ }
+ | MerchantAccountData::Plusgiro {
+ connector_recipient_id,
+ ..
+ } => connector_recipient_id,
+ };
+
+ match connector_recipient_id {
Some(RecipientIdType::ConnectorId(id)) => Ok(Some(id.peek().clone())),
Some(RecipientIdType::LockerId(id)) => Ok(Some(id.peek().clone())),
_ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: "recipient_id".to_string(),
}),
- },
- },
+ }
+ }
_ => Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: "recipient_id".to_string(),
}),
diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs
index b8a855f533..0b52be098c 100644
--- a/crates/router/src/core/pm_auth/transformers.rs
+++ b/crates/router/src/core/pm_auth/transformers.rs
@@ -16,6 +16,36 @@ impl From<types::MerchantAccountData> for pm_auth_types::MerchantAccountData {
sort_code,
name,
},
+ types::MerchantAccountData::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ ..
+ } => Self::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ },
+ types::MerchantAccountData::Sepa { iban, name, .. } => Self::Sepa { iban, name },
+ types::MerchantAccountData::SepaInstant { iban, name, .. } => {
+ Self::SepaInstant { iban, name }
+ }
+ types::MerchantAccountData::Elixir {
+ account_number,
+ iban,
+ name,
+ ..
+ } => Self::Elixir {
+ account_number,
+ iban,
+ name,
+ },
+ types::MerchantAccountData::Bankgiro { number, name, .. } => {
+ Self::Bankgiro { number, name }
+ }
+ types::MerchantAccountData::Plusgiro { number, name, .. } => {
+ Self::Plusgiro { number, name }
+ }
}
}
}
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index b357465bc6..246b9eed3e 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -27,9 +27,11 @@ use hyperswitch_domain_models::{
};
#[cfg(all(feature = "v2", feature = "refunds_v2"))]
use masking::ExposeOptionInterface;
+use masking::Secret;
#[cfg(feature = "payouts")]
use masking::{ExposeInterface, PeekInterface};
use maud::{html, PreEscaped};
+use regex::Regex;
use router_env::{instrument, tracing};
use uuid::Uuid;
@@ -2073,3 +2075,201 @@ pub async fn construct_vault_router_data<F>(
Ok(router_data)
}
+
+pub fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> {
+ match data {
+ types::MerchantAccountData::Iban { iban, .. } => validate_iban(iban),
+
+ types::MerchantAccountData::Sepa { iban, .. } => validate_iban(iban),
+
+ types::MerchantAccountData::SepaInstant { iban, .. } => validate_iban(iban),
+
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ ..
+ } => validate_uk_account(account_number, sort_code),
+
+ types::MerchantAccountData::FasterPayments {
+ account_number,
+ sort_code,
+ ..
+ } => validate_uk_account(account_number, sort_code),
+
+ types::MerchantAccountData::Elixir { iban, .. } => validate_elixir_account(iban),
+
+ types::MerchantAccountData::Bankgiro { number, .. } => validate_bankgiro_number(number),
+
+ types::MerchantAccountData::Plusgiro { number, .. } => validate_plusgiro_number(number),
+ }
+}
+
+fn validate_iban(iban: &Secret<String>) -> RouterResult<()> {
+ let iban_str = iban.peek();
+
+ if iban_str.len() > consts::IBAN_MAX_LENGTH || iban_str.len() < consts::IBAN_MIN_LENGTH {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "IBAN length must be between {} and {} characters",
+ consts::IBAN_MIN_LENGTH,
+ consts::IBAN_MAX_LENGTH
+ ),
+ }
+ .into());
+ }
+
+ if iban.peek().len() > consts::IBAN_MAX_LENGTH {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "IBAN length must be up to 34 characters".to_string(),
+ }
+ .into());
+ }
+ let pattern = Regex::new(r"^[A-Z0-9]*$")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to create regex pattern")?;
+
+ let mut iban = iban.peek().to_string();
+
+ if !pattern.is_match(iban.as_str()) {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "IBAN data must be alphanumeric".to_string(),
+ }
+ .into());
+ }
+
+ // MOD check
+ let first_4 = iban.chars().take(4).collect::<String>();
+ iban.push_str(first_4.as_str());
+ let len = iban.len();
+
+ let rearranged_iban = iban
+ .chars()
+ .rev()
+ .take(len - 4)
+ .collect::<String>()
+ .chars()
+ .rev()
+ .collect::<String>();
+
+ let mut result = String::new();
+
+ rearranged_iban.chars().for_each(|c| {
+ if c.is_ascii_uppercase() {
+ let digit = (u32::from(c) - u32::from('A')) + 10;
+ result.push_str(&format!("{:02}", digit));
+ } else {
+ result.push(c);
+ }
+ });
+
+ let num = result
+ .parse::<u128>()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to validate IBAN")?;
+
+ if num % 97 != 1 {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid IBAN".to_string(),
+ }
+ .into());
+ }
+
+ Ok(())
+}
+
+fn validate_uk_account(
+ account_number: &Secret<String>,
+ sort_code: &Secret<String>,
+) -> RouterResult<()> {
+ if account_number.peek().len() > consts::BACS_MAX_ACCOUNT_NUMBER_LENGTH
+ || sort_code.peek().len() != consts::BACS_SORT_CODE_LENGTH
+ {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid BACS numbers".to_string(),
+ }
+ .into());
+ }
+
+ Ok(())
+}
+
+fn validate_elixir_account(iban: &Secret<String>) -> RouterResult<()> {
+ let iban_str = iban.peek();
+
+ // Validate IBAN first
+ validate_iban(iban)?;
+
+ // Check if IBAN is Polish
+ if !iban_str.starts_with("PL") {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Elixir IBAN must be Polish (PL)".to_string(),
+ }
+ .into());
+ }
+
+ // Validate IBAN length for Poland
+ if iban_str.len() != consts::ELIXIR_IBAN_LENGTH {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Polish IBAN must be 28 characters".to_string(),
+ }
+ .into());
+ }
+
+ Ok(())
+}
+
+fn validate_bankgiro_number(number: &Secret<String>) -> RouterResult<()> {
+ let num_str = number.peek();
+ let clean_number = num_str.replace("-", "").replace(" ", "");
+
+ // Length validation
+ if clean_number.len() < consts::BANKGIRO_MIN_LENGTH
+ || clean_number.len() > consts::BANKGIRO_MAX_LENGTH
+ {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "Bankgiro number must be between {} and {} digits",
+ consts::BANKGIRO_MIN_LENGTH,
+ consts::BANKGIRO_MAX_LENGTH
+ ),
+ }
+ .into());
+ }
+
+ // Must be numeric
+ if !clean_number.chars().all(|c| c.is_ascii_digit()) {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Bankgiro number must be numeric".to_string(),
+ }
+ .into());
+ }
+ Ok(())
+}
+
+fn validate_plusgiro_number(number: &Secret<String>) -> RouterResult<()> {
+ let num_str = number.peek();
+ let clean_number = num_str.replace("-", "").replace(" ", "");
+
+ // Length validation
+ if clean_number.len() < consts::PLUSGIRO_MIN_LENGTH
+ || clean_number.len() > consts::PLUSGIRO_MAX_LENGTH
+ {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "Plusgiro number must be between {} and {} digits",
+ consts::PLUSGIRO_MIN_LENGTH,
+ consts::PLUSGIRO_MAX_LENGTH
+ ),
+ }
+ .into());
+ }
+
+ // Must be numeric
+ if !clean_number.chars().all(|c| c.is_ascii_digit()) {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Plusgiro number must be numeric".to_string(),
+ }
+ .into());
+ }
+ Ok(())
+}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 9a96a1cdc5..d7e149b9db 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -599,6 +599,38 @@ pub enum MerchantAccountData {
name: String,
connector_recipient_id: Option<RecipientIdType>,
},
+ FasterPayments {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ name: String,
+ connector_recipient_id: Option<RecipientIdType>,
+ },
+ Sepa {
+ iban: Secret<String>,
+ name: String,
+ connector_recipient_id: Option<RecipientIdType>,
+ },
+ SepaInstant {
+ iban: Secret<String>,
+ name: String,
+ connector_recipient_id: Option<RecipientIdType>,
+ },
+ Elixir {
+ account_number: Secret<String>,
+ iban: Secret<String>,
+ name: String,
+ connector_recipient_id: Option<RecipientIdType>,
+ },
+ Bankgiro {
+ number: Secret<String>,
+ name: String,
+ connector_recipient_id: Option<RecipientIdType>,
+ },
+ Plusgiro {
+ number: Secret<String>,
+ name: String,
+ connector_recipient_id: Option<RecipientIdType>,
+ },
}
impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData {
@@ -630,6 +662,82 @@ impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData
_ => None,
},
},
+ MerchantAccountData::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ connector_recipient_id,
+ } => Self::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ connector_recipient_id: match connector_recipient_id {
+ Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
+ _ => None,
+ },
+ },
+ MerchantAccountData::Sepa {
+ iban,
+ name,
+ connector_recipient_id,
+ } => Self::Sepa {
+ iban,
+ name,
+ connector_recipient_id: match connector_recipient_id {
+ Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
+ _ => None,
+ },
+ },
+ MerchantAccountData::SepaInstant {
+ iban,
+ name,
+ connector_recipient_id,
+ } => Self::SepaInstant {
+ iban,
+ name,
+ connector_recipient_id: match connector_recipient_id {
+ Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
+ _ => None,
+ },
+ },
+ MerchantAccountData::Elixir {
+ account_number,
+ iban,
+ name,
+ connector_recipient_id,
+ } => Self::Elixir {
+ account_number,
+ iban,
+ name,
+ connector_recipient_id: match connector_recipient_id {
+ Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
+ _ => None,
+ },
+ },
+ MerchantAccountData::Bankgiro {
+ number,
+ name,
+ connector_recipient_id,
+ } => Self::Bankgiro {
+ number,
+ name,
+ connector_recipient_id: match connector_recipient_id {
+ Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
+ _ => None,
+ },
+ },
+ MerchantAccountData::Plusgiro {
+ number,
+ name,
+ connector_recipient_id,
+ } => Self::Plusgiro {
+ number,
+ name,
+ connector_recipient_id: match connector_recipient_id {
+ Some(RecipientIdType::ConnectorId(id)) => Some(id.clone()),
+ _ => None,
+ },
+ },
}
}
}
@@ -657,10 +765,67 @@ impl From<api_models::admin::MerchantAccountData> for MerchantAccountData {
name,
connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
},
+ api_models::admin::MerchantAccountData::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ connector_recipient_id,
+ } => Self::FasterPayments {
+ account_number,
+ sort_code,
+ name,
+ connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
+ },
+ api_models::admin::MerchantAccountData::Sepa {
+ iban,
+ name,
+ connector_recipient_id,
+ } => Self::Sepa {
+ iban,
+ name,
+ connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
+ },
+ api_models::admin::MerchantAccountData::SepaInstant {
+ iban,
+ name,
+ connector_recipient_id,
+ } => Self::SepaInstant {
+ iban,
+ name,
+ connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
+ },
+ api_models::admin::MerchantAccountData::Elixir {
+ account_number,
+ iban,
+ name,
+ connector_recipient_id,
+ } => Self::Elixir {
+ account_number,
+ iban,
+ name,
+ connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
+ },
+ api_models::admin::MerchantAccountData::Bankgiro {
+ number,
+ name,
+ connector_recipient_id,
+ } => Self::Bankgiro {
+ number,
+ name,
+ connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
+ },
+ api_models::admin::MerchantAccountData::Plusgiro {
+ number,
+ name,
+ connector_recipient_id,
+ } => Self::Plusgiro {
+ number,
+ name,
+ connector_recipient_id: connector_recipient_id.map(RecipientIdType::ConnectorId),
+ },
}
}
}
-
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MerchantRecipientData {
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index c947bcd265..dbb24e3cb0 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -603,7 +603,9 @@ impl ConnectorData {
Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new())))
}
// enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))),
- // enums::Connector::Tokenio => Ok(ConnectorEnum::Old(Box::new(connector::Tokenio))),
+ enums::Connector::Tokenio => {
+ Ok(ConnectorEnum::Old(Box::new(connector::Tokenio::new())))
+ }
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 66e9c0963d..e8c136c4ed 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -328,7 +328,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Stripebilling => Self::Stripebilling,
// api_enums::Connector::Taxjar => Self::Taxjar,
// api_enums::Connector::Thunes => Self::Thunes,
- // api_enums::Connector::Tokenio => Self::Tokenio,
+ api_enums::Connector::Tokenio => Self::Tokenio,
api_enums::Connector::Trustpay => Self::Trustpay,
api_enums::Connector::Tsys => Self::Tsys,
// api_enums::Connector::UnifiedAuthenticationService => {
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 365d1efc42..55378f475e 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -177,7 +177,7 @@ stripebilling.base_url = "https://api.stripe.com/"
taxjar.base_url = "https://api.sandbox.taxjar.com/v2/"
threedsecureio.base_url = "https://service.sandbox.3dsecure.io"
thunes.base_url = "https://api.limonetikqualif.com/"
-tokenio.base_url = "https://api.token.io"
+tokenio.base_url = "https://api.sandbox.token.io"
stripe.base_url_file_upload = "https://files.stripe.com/"
trustpay.base_url = "https://test-tpgw.trustpay.eu/"
trustpay.base_url_bank_redirects = "https://aapi.trustpay.eu/"