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(payments): add Twilio Generic Pay inbound adapter (#14713)

Ankit Kumar Guptabe9dbdd80fa5
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index aed5590c1b..cf6a09fdfc 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -12,6 +12,7 @@ pub mod refund;
#[cfg(feature = "v2")]
pub mod revenue_recovery;
pub mod routing;
+pub mod telephone_order;
pub mod user;
pub mod user_role;
use common_utils::{
diff --git a/crates/api_models/src/events/telephone_order.rs b/crates/api_models/src/events/telephone_order.rs
new file mode 100644
index 0000000000..c790bc7b31
--- /dev/null
+++ b/crates/api_models/src/events/telephone_order.rs
@@ -0,0 +1,19 @@
+use common_utils::events::ApiEventMetric;
+
+use crate::telephone_order::twilio::{TwilioGenericPayRequest, TwilioGenericPayResponse};
+
+impl ApiEventMetric for TwilioGenericPayRequest {}
+
+#[cfg(feature = "v1")]
+impl ApiEventMetric for TwilioGenericPayResponse {
+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
+ // `charge_id` is the Hyperswitch `payment_id`, so a successful charge is reported as an
+ // ordinary payment event. A decline has no payment to point at.
+ self.charge_id
+ .clone()
+ .map(|payment_id| common_utils::events::ApiEventsType::Payment { payment_id })
+ }
+}
+
+#[cfg(feature = "v2")]
+impl ApiEventMetric for TwilioGenericPayResponse {}
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs
index b5df3f787a..fa44d620e2 100644
--- a/crates/api_models/src/lib.rs
+++ b/crates/api_models/src/lib.rs
@@ -51,6 +51,7 @@ pub mod subscription;
pub mod superposition_proxy;
pub mod superposition_sdk_config;
pub mod surcharge_decision_configs;
+pub mod telephone_order;
pub mod three_ds_decision_rule;
#[cfg(feature = "tokenization_v2")]
pub mod tokenization;
diff --git a/crates/api_models/src/telephone_order.rs b/crates/api_models/src/telephone_order.rs
new file mode 100644
index 0000000000..037fc14e0b
--- /dev/null
+++ b/crates/api_models/src/telephone_order.rs
@@ -0,0 +1 @@
+pub mod twilio;
diff --git a/crates/api_models/src/telephone_order/twilio.rs b/crates/api_models/src/telephone_order/twilio.rs
new file mode 100644
index 0000000000..b611d6469a
--- /dev/null
+++ b/crates/api_models/src/telephone_order/twilio.rs
@@ -0,0 +1,101 @@
+use std::collections::HashMap;
+
+use hyperswitch_masking::Secret;
+
+/// The operation Twilio is asking us to perform.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TwilioPayMethod {
+ /// Move money for the collected payment method.
+ Charge,
+ /// Store the collected payment method for later use, without moving money.
+ Tokenize,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct TwilioGenericPayRequest {
+ /// Whether Twilio wants a charge or a tokenization.
+ pub method: TwilioPayMethod,
+
+ /// Twilio's identifier for this payment attempt. Stable across Twilio's retries.
+ pub transaction_id: String,
+
+ /// Card number collected over DTMF.
+ pub cardnumber: Option<cards::CardNumber>,
+
+ /// Card security code collected over DTMF.
+ pub cvv: Option<Secret<String>>,
+
+ /// Two digit card expiry month.
+ pub expiry_month: Option<Secret<String>>,
+
+ /// Two or four digit card expiry year.
+ pub expiry_year: Option<Secret<String>>,
+
+ /// Billing postal code, collected for AVS.
+ pub postal_code: Option<Secret<String>>,
+
+ /// Bank account number, sent for ACH debits. Not supported.
+ pub bankaccountnumber: Option<Secret<String>>,
+
+ /// Bank routing number, sent for ACH debits. Not supported.
+ pub routingnumber: Option<Secret<String>>,
+
+ /// Amount in major units, as a decimal string. Absent for `tokenize`.
+ pub amount: Option<common_utils::types::StringMajorUnit>,
+
+ /// Currency of `amount`. Absent for `tokenize`.
+ pub currency_code: Option<common_enums::Currency>,
+
+ /// Free-form description configured on the `<Pay>` verb.
+ pub description: Option<String>,
+
+ /// Values supplied by the IVR through `<Parameter>` tags on the `<Pay>` verb. Not a `Secret`:
+ /// the core persists these unmasked in the payment's `metadata`, so keep nothing sensitive here.
+ pub parameters: Option<HashMap<String, String>>,
+}
+
+/// Body Twilio expects back. It reads `error_code` to decide whether the payment succeeded, so a
+/// decline is a `200` with that set; every field is serialized even when `None`.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct TwilioGenericPayResponse {
+ /// Reference for a successful charge. This is the Hyperswitch `payment_id`.
+ pub charge_id: Option<common_utils::id_type::PaymentId>,
+
+ /// Set when the payment did not succeed. `null` on success.
+ pub error_code: Option<String>,
+
+ /// Human readable counterpart to `error_code`. `null` on success.
+ pub error_message: Option<String>,
+
+ /// Handed back either way — the only channel carrying a `payment_id` when `charge_id` is
+ /// `null`. Flat and all-string: Twilio raises a JSON mapping exception on anything else.
+ pub parameters: HashMap<String, String>,
+}
+
+impl TwilioGenericPayResponse {
+ pub fn success(
+ charge_id: common_utils::id_type::PaymentId,
+ parameters: HashMap<String, String>,
+ ) -> Self {
+ Self {
+ charge_id: Some(charge_id),
+ error_code: None,
+ error_message: None,
+ parameters,
+ }
+ }
+
+ pub fn failure(
+ error_code: String,
+ error_message: String,
+ parameters: HashMap<String, String>,
+ ) -> Self {
+ Self {
+ charge_id: None,
+ error_code: Some(error_code),
+ error_message: Some(error_message),
+ parameters,
+ }
+ }
+}
diff --git a/crates/router/src/core.rs b/crates/router/src/core.rs
index 9b0288d335..e706dd177b 100644
--- a/crates/router/src/core.rs
+++ b/crates/router/src/core.rs
@@ -72,6 +72,8 @@ pub mod superposition_proxy;
#[cfg(feature = "v1")]
pub mod superposition_sdk_config;
pub mod surcharge_decision_config;
+#[cfg(feature = "v1")]
+pub mod telephone_order;
pub mod three_ds_decision_rule;
pub mod tokenization;
pub mod unified_authentication_service;
diff --git a/crates/router/src/core/telephone_order.rs b/crates/router/src/core/telephone_order.rs
new file mode 100644
index 0000000000..cd85727327
--- /dev/null
+++ b/crates/router/src/core/telephone_order.rs
@@ -0,0 +1,664 @@
+pub mod twilio;
+
+use std::collections::HashMap;
+
+use common_utils::events::ApiEventMetric;
+use hyperswitch_domain_models::payments::HeaderPayload;
+use router_env::logger;
+
+use crate::{
+ core::{
+ api_locking,
+ errors::{self, RouterResponse},
+ payments,
+ },
+ routes::{app::ReqState, lock_utils, SessionState},
+ services::{
+ self,
+ authentication::{
+ ApiKeyBasicAuthWithMerchantIdFromRoute, AuthenticateAndFetch, AuthenticationData,
+ },
+ ApplicationResponse,
+ },
+ types::api,
+};
+
+/// Codes shared by every adapter. An adapter adds its own for what it rejects on its way in.
+pub mod error_codes {
+ pub const INVALID_REQUEST: &str = "INVALID_REQUEST";
+ pub const PROFILE_NOT_FOUND: &str = "PROFILE_NOT_FOUND";
+ pub const PAYMENT_NOT_COMPLETED: &str = "PAYMENT_NOT_COMPLETED";
+ pub const PROCESSING_ERROR: &str = "PROCESSING_ERROR";
+ pub const DUPLICATE_TRANSACTION: &str = "DUPLICATE_TRANSACTION";
+ /// The charge reached the connector with no final outcome. Kept apart from a decline so an
+ /// IVR can be told not to ask for another card: the first authorization may be standing.
+ pub const PAYMENT_PENDING: &str = "PAYMENT_PENDING";
+}
+
+pub type Parameters = HashMap<String, String>;
+
+/// Why a charge failed, in terms the provider can read back to the caller.
+#[derive(Debug)]
+pub struct Failure {
+ pub code: String,
+ pub message: String,
+ pub parameters: ResponseParameters,
+}
+
+impl Failure {
+ pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
+ Self {
+ code: code.into(),
+ message: message.into(),
+ parameters: ResponseParameters::new(),
+ }
+ }
+
+ /// Only for a failure with a payment behind it; one rejected earlier has nothing to point at.
+ fn with_parameters(mut self, parameters: ResponseParameters) -> Self {
+ self.parameters = parameters;
+ self
+ }
+
+ /// A failure of ours: reported without detail, investigated from the logs.
+ fn processing_error() -> Self {
+ Self::new(
+ error_codes::PROCESSING_ERROR,
+ "Payment could not be processed",
+ )
+ }
+}
+
+pub type ResponseParameters = HashMap<String, String>;
+
+/// How a finished payment reads to the caller. Three outcomes, not two: a payment that is not yet
+/// paid is not thereby declined, and the difference decides whether the IVR asks for another card.
+#[derive(Debug)]
+pub enum Outcome {
+ /// Money is secured. An authorization counts — the capture is the merchant's to make.
+ Paid,
+ /// Terminal, and no money moved. Asking the caller for another card is the right next step.
+ Declined(Failure),
+ /// We do not know, or money is held in a state that cannot be read back. Carries
+ /// [`error_codes::PAYMENT_PENDING`] so a provider can tell it from a decline.
+ Indeterminate(Failure),
+}
+
+/// The half of the payment every adapter fills in the same way, read out of [`Parameters`].
+pub struct Context {
+ /// `None` falls back to the merchant's default profile.
+ pub profile_id: Option<common_utils::id_type::ProfileId>,
+ /// What makes a provider's retry idempotent: it collides on `(payment_id, merchant_id)`
+ /// instead of charging again. Settled by [`TelephoneOrderAdapter::resolve_payment_id`].
+ pub payment_id: Option<common_utils::id_type::PaymentId>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
+ pub metadata: Option<serde_json::Value>,
+}
+
+impl Context {
+ /// The shared fields, for an adapter to fill the rest in with `..context.payments_request()`.
+ /// Confirmed, auto-captured, flagged a telephone order, never 3DS — a caller has no browser.
+ pub fn payments_request(self) -> api_models::payments::PaymentsRequest {
+ api_models::payments::PaymentsRequest {
+ confirm: Some(true),
+ capture_method: Some(common_enums::CaptureMethod::Automatic),
+ authentication_type: Some(common_enums::AuthenticationType::NoThreeDs),
+ payment_channel: Some(common_enums::PaymentChannel::TelephoneOrder),
+ profile_id: self.profile_id,
+ payment_id: self
+ .payment_id
+ .map(api_models::payments::PaymentIdType::PaymentIntentId),
+ customer_id: self.customer_id,
+ metadata: self.metadata,
+ // `connector` is left unset so the merchant's configured routing decides.
+ ..Default::default()
+ }
+ }
+}
+
+/// The providers this endpoint serves, as they appear in the `{provider}` path segment. These are
+/// inbound providers that hand us a card to charge, not connectors we send it to.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumString)]
+#[strum(serialize_all = "snake_case")]
+pub enum TelephoneOrderProvider {
+ /// Twilio's `<Pay>` verb, through its Generic Pay Connector.
+ Twilio,
+}
+
+/// One provider's translation to and from Hyperswitch. An adapter implements the translation
+/// methods and nothing else; [`charge`](TelephoneOrderAdapter::charge) is the same for all of them.
+#[async_trait::async_trait]
+pub trait TelephoneOrderAdapter {
+ /// The provider's request body. Serialized into the `ApiEvent` log through `masked_serialize`,
+ /// so every sensitive field on it must be a `Secret`; [`Parameters`] is the exception.
+ type Request: serde::de::DeserializeOwned
+ + serde::Serialize
+ + std::fmt::Debug
+ + ApiEventMetric
+ + Send
+ + Sync;
+
+ /// What the provider expects back, on success and on failure alike.
+ type Response: serde::Serialize + std::fmt::Debug + ApiEventMetric + Send;
+
+ /// The provider's identifier for the attempt. Logged, not used as a key.
+ fn transaction_reference(request: &Self::Request) -> String;
+
+ /// The provider's own value that stays the same across *its* retries: the payment id derives
+ /// from it, so a retry collides instead of charging again. `None` means no such protection.
+ fn idempotency_reference(request: &Self::Request) -> Option<&str>;
+
+ /// Where the provider carries the IVR's [`Parameters`]. A reference, so a provider holding
+ /// those ids as typed fields would need a `Cow` or a typed getter instead.
+ fn parameters(request: &Self::Request) -> Option<&Parameters>;
+
+ /// Maps the provider's own fields — amount, payment method, descriptors — onto the payment.
+ fn build_payments_request(
+ request: &Self::Request,
+ context: Context,
+ ) -> Result<api_models::payments::PaymentsRequest, Failure>;
+
+ fn success_response(
+ payment: &api_models::payments::PaymentsResponse,
+ parameters: ResponseParameters,
+ ) -> Self::Response;
+
+ fn failure_response(failure: Failure) -> Self::Response;
+
+ /// The credential check these requests go through; HTTP Basic carrying a Hyperswitch API key
+ /// by default. Auth never sees the body, so `parameters.profile_id` is read here and handed in.
+ fn authenticator(
+ merchant_id: common_utils::id_type::MerchantId,
+ request: &Self::Request,
+ ) -> Box<dyn AuthenticateAndFetch<AuthenticationData, SessionState>> {
+ Box::new(ApiKeyBasicAuthWithMerchantIdFromRoute {
+ merchant_id,
+ profile_id: extract_id(Self::parameters(request), "profile_id")
+ // An unusable id is rejected with `INVALID_REQUEST` in `charge`.
+ .ok()
+ .flatten(),
+ })
+ }
+
+ /// The payment id this request becomes, settled in one place because the route locks on it and
+ /// the core puts it on the payment. `parameters.payment_id` wins; else [`derive_payment_id`].
+ fn resolve_payment_id(
+ request: &Self::Request,
+ ) -> Result<Option<common_utils::id_type::PaymentId>, Failure> {
+ extract_id(Self::parameters(request), "payment_id").map(|supplied| {
+ supplied.or_else(|| Self::idempotency_reference(request).and_then(derive_payment_id))
+ })
+ }
+
+ /// Answers the provider with a failure, leaving a log line behind to explain it.
+ fn report_failure(
+ transaction_reference: &str,
+ failure: Failure,
+ ) -> ApplicationResponse<Self::Response> {
+ logger::warn!(
+ transaction_reference = %transaction_reference,
+ error_code = %failure.code,
+ "Generic pay charge was not completed: {}",
+ failure.message
+ );
+ ApplicationResponse::Json(Self::failure_response(failure))
+ }
+
+ /// Creates and confirms the payment the provider is asking for. Failures are answered with a
+ /// `200` carrying an error code, so the provider reads a result instead of an opaque 5xx.
+ async fn charge(
+ state: SessionState,
+ req_state: ReqState,
+ auth: AuthenticationData,
+ request: Self::Request,
+ ) -> RouterResponse<Self::Response> {
+ let transaction_reference = Self::transaction_reference(&request);
+
+ let payments_request = Self::resolve_payment_id(&request)
+ .and_then(|payment_id| build_context(&auth, Self::parameters(&request), payment_id))
+ .and_then(|context| Self::build_payments_request(&request, context))
+ .and_then(finalize_payments_request);
+
+ let outcome = match payments_request {
+ Err(failure) => Err(failure),
+ Ok(payments_request) => {
+ let profile_id = payments_request.profile_id.clone();
+
+ let payments_response = Box::pin(payments::payments_core::<
+ api::Authorize,
+ api::PaymentsResponse,
+ _,
+ _,
+ _,
+ payments::PaymentData<api::Authorize>,
+ >(
+ state.clone(),
+ req_state.clone(),
+ auth.platform.clone(),
+ profile_id,
+ payments::PaymentCreate,
+ payments_request,
+ services::api::AuthFlow::Merchant,
+ payments::CallConnectorAction::Trigger,
+ None,
+ None,
+ HeaderPayload::with_source(common_enums::PaymentSource::MerchantServer),
+ None,
+ ))
+ .await;
+
+ match payments_response {
+ Ok(ApplicationResponse::Json(payment))
+ | Ok(ApplicationResponse::JsonWithHeaders((payment, _))) => Ok(payment),
+ Ok(other) => {
+ logger::error!(
+ transaction_reference = %transaction_reference,
+ "Unexpected response variant from payments core: {other:?}"
+ );
+ Err(Failure::processing_error())
+ }
+ // The one error with a payment behind it. Answered with that charge's own
+ // outcome, so the retry does not read as a decline and send the caller round
+ // for a second card.
+ Err(error) => match error.current_context() {
+ errors::ApiErrorResponse::DuplicatePayment { payment_id } => {
+ logger::info!(
+ transaction_reference = %transaction_reference,
+ payment_id = %payment_id.get_string_repr(),
+ "A charge that already exists was retried; replaying its outcome"
+ );
+
+ retrieve_payment(&state, req_state, &auth, payment_id).await
+ }
+ _ => Err(classify_core_error(&transaction_reference, &error)),
+ },
+ }
+ }
+ };
+
+ Ok(match outcome {
+ Ok(payment) => Self::answer(&transaction_reference, &payment),
+ Err(failure) => Self::report_failure(&transaction_reference, failure),
+ })
+ }
+
+ /// Reads a finished payment back to the provider.
+ fn answer(
+ transaction_reference: &str,
+ payment: &api_models::payments::PaymentsResponse,
+ ) -> ApplicationResponse<Self::Response> {
+ match payment_outcome(payment) {
+ Outcome::Paid => ApplicationResponse::Json(Self::success_response(
+ payment,
+ outcome_parameters(payment),
+ )),
+ Outcome::Declined(failure) => Self::report_failure(transaction_reference, failure),
+ // Logged louder than a decline: nobody has to act on a declined card, and somebody
+ // has to act on an authorization the caller was not told about.
+ Outcome::Indeterminate(failure) => {
+ logger::error!(
+ transaction_reference = %transaction_reference,
+ payment_id = %payment.payment_id.get_string_repr(),
+ status = %payment.status,
+ "Telephone order charge has no outcome that can be read to the caller; \
+ funds may be held at the connector"
+ );
+ Self::report_failure(transaction_reference, failure)
+ }
+ }
+ }
+}
+
+/// Locks the payment this request becomes, so a provider's retry waits for the charge in flight
+/// instead of racing it. `NotApplicable` only when there is no id to lock on at all — the route
+/// resolves the id once, records it on the span and hands it here.
+pub fn locking_action<F>(
+ payment_id: Option<&common_utils::id_type::PaymentId>,
+ flow: F,
+) -> api_locking::LockAction
+where
+ F: router_env::types::FlowMetric,
+ lock_utils::ApiIdentifier: From<F>,
+{
+ payment_id.map_or(api_locking::LockAction::NotApplicable, |payment_id| {
+ api_locking::LockAction::Hold {
+ input: api_locking::LockingInput {
+ unique_locking_key: payment_id.get_string_repr().to_owned(),
+ api_identifier: lock_utils::ApiIdentifier::from(flow),
+ override_lock_retries: None,
+ },
+ }
+ })
+}
+
+/// Reads the ids the IVR passed through. The profile was resolved by authentication, the payment
+/// id by [`TelephoneOrderAdapter::resolve_payment_id`] — which the route needed first, to lock on.
+fn build_context(
+ auth: &AuthenticationData,
+ parameters: Option<&Parameters>,
+ payment_id: Option<common_utils::id_type::PaymentId>,
+) -> Result<Context, Failure> {
+ Ok(Context {
+ profile_id: resolve_profile_id(auth, parameters)?,
+ payment_id,
+ // A convenience: an unusable one is dropped rather than failing the charge.
+ customer_id: extract_id(parameters, "customer_id")
+ .inspect_err(|failure| {
+ logger::warn!(
+ "Ignoring unusable customer_id from telephone order parameters: {}",
+ failure.message
+ )
+ })
+ .ok()
+ .flatten(),
+ metadata: build_metadata(parameters),
+ })
+}
+
+/// The profile the IVR named, as authentication resolved it. Parsed again here so a mangled id is
+/// rejected rather than dropped by the route and replaced by the default profile.
+fn resolve_profile_id(
+ auth: &AuthenticationData,
+ parameters: Option<&Parameters>,
+) -> Result<Option<common_utils::id_type::ProfileId>, Failure> {
+ extract_id::<common_utils::id_type::ProfileId>(parameters, "profile_id")?;
+
+ Ok(auth
+ .profile
+ .as_ref()
+ .map(|profile| profile.get_id().clone()))
+}
+
+/// Reads one Hyperswitch id out of the parameters. An unusable value is rejected, not ignored.
+fn extract_id<I>(parameters: Option<&Parameters>, key: &str) -> Result<Option<I>, Failure>
+where
+ I: TryFrom<std::borrow::Cow<'static, str>>,
+ <I as TryFrom<std::borrow::Cow<'static, str>>>::Error: std::fmt::Display,
+{
+ parameters
+ .and_then(|parameters| parameters.get(key))
+ .map(|value| {
+ I::try_from(std::borrow::Cow::Owned(value.clone())).map_err(|error| {
+ Failure::new(
+ error_codes::INVALID_REQUEST,
+ format!("parameters.{key} is not a valid {key}: {error}"),
+ )
+ })
+ })
+ .transpose()
+}
+
+/// Carries the IVR's parameters through to the payment, for reconciliation. Lands in
+/// `payment_intent.metadata` unmasked — returned by payments retrieve, sent in webhooks.
+fn build_metadata(parameters: Option<&Parameters>) -> Option<serde_json::Value> {
+ let parameters = parameters.filter(|parameters| !parameters.is_empty())?;
+
+ serde_json::to_value(parameters)
+ .inspect_err(|error| {
+ logger::warn!("Could not serialize telephone order parameters into metadata: {error:?}")
+ })
+ .ok()
+}
+
+/// Validates the mapped payment and settles its id, keeping the one the IVR supplied.
+fn finalize_payments_request(
+ mut payments_request: api_models::payments::PaymentsRequest,
+) -> Result<api_models::payments::PaymentsRequest, Failure> {
+ payments_request
+ .validate()
+ .map_err(|message| Failure::new(error_codes::INVALID_REQUEST, message))?;
+
+ crate::routes::payments::get_or_generate_payment_id(&mut payments_request).map_err(
+ |error| {
+ Failure::new(
+ error_codes::INVALID_REQUEST,
+ format!("payment_id could not be resolved: {error}"),
+ )
+ },
+ )?;
+
+ Ok(payments_request)
+}
+
+/// One id per provider attempt, shared by its retries. Derived, not generated: Twilio resends the
+/// same body when we miss its budget, so a fresh id would charge the card again. The reference is
+/// hashed because it is untrusted text, and kept a pure function so route and core agree.
+fn derive_payment_id(reference: &str) -> Option<common_utils::id_type::PaymentId> {
+ use common_utils::crypto::GenerateDigest;
+
+ let digest = common_utils::crypto::Sha256
+ .generate_digest(reference.as_bytes())
+ .inspect_err(|error| {
+ logger::error!("Could not derive a payment_id for a telephone order: {error:?}")
+ })
+ .ok()?;
+
+ // `pay_` is what every payment id in this repo carries, generated or derived; 32 hex
+ // characters is half the digest, well inside the 64 a `PaymentId` allows. Nothing stops a
+ // merchant choosing this exact string for a payment of their own — the prefix is a
+ // convention, not a namespace — but 128 bits of digest makes landing on one by accident not a
+ // thing that happens.
+ common_utils::id_type::PaymentId::wrap(format!("pay_{}", hex::encode(digest.get(..16)?))).ok()
+}
+
+/// Reads back the payment a retry collided with, so the collision answers with the original
+/// outcome rather than a decline. Not force-synced: the lock means that charge already finished.
+async fn retrieve_payment(
+ state: &SessionState,
+ req_state: ReqState,
+ auth: &AuthenticationData,
+ payment_id: &common_utils::id_type::PaymentId,
+) -> Result<api_models::payments::PaymentsResponse, Failure> {
+ let response = Box::pin(payments::payments_core::<
+ api::PSync,
+ api::PaymentsResponse,
+ _,
+ _,
+ _,
+ payments::PaymentData<api::PSync>,
+ >(
+ state.clone(),
+ req_state,
+ auth.platform.clone(),
+ None,
+ payments::operations::PaymentStatus,
+ api::PaymentsRetrieveRequest {
+ resource_id: api_models::payments::PaymentIdType::PaymentIntentId(payment_id.clone()),
+ merchant_id: Some(auth.platform.get_processor().get_account().get_id().clone()),
+ force_sync: false,
+ ..Default::default()
+ },
+ services::api::AuthFlow::Merchant,
+ payments::CallConnectorAction::Avoid,
+ None,
+ None,
+ HeaderPayload::default(),
+ None,
+ ))
+ .await;
+
+ match response {
+ Ok(ApplicationResponse::Json(payment))
+ | Ok(ApplicationResponse::JsonWithHeaders((payment, _))) => Ok(payment),
+ // The payment exists, so failing to read it is ours. Still not a decline: the first charge
+ // stands either way, and a decline would send the caller round for another card.
+ other => {
+ logger::error!(
+ payment_id = %payment_id.get_string_repr(),
+ "Could not read back the payment a telephone order retry collided with: {other:?}"
+ );
+ Err(Failure::new(
+ error_codes::DUPLICATE_TRANSACTION,
+ "A payment already exists for this payment_id",
+ )
+ .with_parameters(ResponseParameters::from([(
+ "payment_id".to_string(),
+ payment_id.get_string_repr().to_owned(),
+ )])))
+ }
+ }
+}
+
+/// Reads a payments core error back as something the provider can act on.
+fn classify_core_error(
+ transaction_reference: &str,
+ error: &error_stack::Report<errors::ApiErrorResponse>,
+) -> Failure {
+ match error.current_context() {
+ // `PaymentCreate`'s merchant-scoped profile lookup, which rejects a `parameters.profile_id`
+ // that is not this merchant's — an IVR configuration mistake, not a failure of ours.
+ errors::ApiErrorResponse::ProfileNotFound { id } => {
+ logger::warn!(
+ transaction_reference = %transaction_reference,
+ "Telephone order named a profile the merchant does not have: {id}"
+ );
+ Failure::new(
+ error_codes::PROFILE_NOT_FOUND,
+ format!("profile_id {id} is not available for this merchant"),
+ )
+ }
+ // Kept apart from `PROCESSING_ERROR`: a mistyped expiry is worth re-prompting for, an
+ // outage is not. The core's message names the field to ask for again.
+ errors::ApiErrorResponse::PreconditionFailed { message }
+ | errors::ApiErrorResponse::InvalidRequestData { message } => {
+ invalid_request(transaction_reference, message.clone())
+ }
+ errors::ApiErrorResponse::InvalidDataValue { field_name } => {
+ invalid_request(transaction_reference, format!("{field_name} is not valid"))
+ }
+ errors::ApiErrorResponse::MissingRequiredField { field_name } => {
+ invalid_request(transaction_reference, format!("{field_name} is required"))
+ }
+ errors::ApiErrorResponse::InvalidDataFormat {
+ field_name,
+ expected_format,
+ } => invalid_request(
+ transaction_reference,
+ format!("{field_name} is not in the expected format: {expected_format}"),
+ ),
+
+ // A failure we cannot classify is reported as `PROCESSING_ERROR` — ours, not the card's —
+ // and investigated from the logs.
+ _ => {
+ logger::error!(
+ transaction_reference = %transaction_reference,
+ "Payments core returned an error for a telephone order charge: {error:?}"
+ );
+ Failure::processing_error()
+ }
+ }
+}
+
+/// A rejection the caller caused. `warn`, not `error`: a mistyped card is not an incident.
+fn invalid_request(transaction_reference: &str, message: String) -> Failure {
+ logger::warn!(
+ transaction_reference = %transaction_reference,
+ "Telephone order charge was rejected on its input: {message}"
+ );
+ Failure::new(error_codes::INVALID_REQUEST, message)
+}
+
+/// How a finished payment reads to the caller. Matched exhaustively on purpose: a wildcard would
+/// drop every `IntentStatus` Hyperswitch grows next into whichever bucket happens to be last.
+fn payment_outcome(payment: &api_models::payments::PaymentsResponse) -> Outcome {
+ use common_enums::IntentStatus as Status;
+
+ match payment.status {
+ // Captured, in whole or in part.
+ Status::Succeeded | Status::PartiallyCaptured => Outcome::Paid,
+
+ // Authorized and not captured — still paid: the funds are held, and a decline here would
+ // leave the authorization standing while the IVR collects another card.
+ Status::RequiresCapture | Status::PartiallyAuthorizedAndRequiresCapture => Outcome::Paid,
+
+ // Money has moved, or may yet, by an amount that cannot be read back. `CancelledPostCapture`
+ // too: a capture happened before the cancellation.
+ Status::Processing
+ | Status::PartiallyCapturedAndCapturable
+ | Status::PartiallyCapturedAndProcessing
+ | Status::Review
+ | Status::RequiresMerchantAction
+ | Status::Conflicted
+ | Status::CancelledPostCapture => Outcome::Indeterminate(
+ Failure::new(
+ error_codes::PAYMENT_PENDING,
+ format!(
+ "Payment outcome is not final and funds may be held: {}",
+ payment.status
+ ),
+ )
+ .with_parameters(outcome_parameters(payment)),
+ ),
+
+ // Terminal with nothing held — the only statuses where another card is the right next step.
+ // `RequiresCustomerAction` included: its redirect is unreachable for a caller on a phone.
+ Status::Failed
+ | Status::Cancelled
+ | Status::Expired
+ | Status::RequiresPaymentMethod
+ | Status::RequiresConfirmation
+ | Status::RequiresCustomerAction => Outcome::Declined(decline_failure(payment)),
+ }
+}
+
+/// A decline in the connector's own terms where it gave them, and in ours where it did not.
+fn decline_failure(payment: &api_models::payments::PaymentsResponse) -> Failure {
+ let code = payment
+ .unified_code
+ .clone()
+ .or_else(|| payment.error_code.clone())
+ .unwrap_or_else(|| error_codes::PAYMENT_NOT_COMPLETED.to_string());
+
+ let message = payment
+ .unified_message
+ .clone()
+ .or_else(|| payment.error_message.clone())
+ .unwrap_or_else(|| format!("Payment was not completed: {}", payment.status));
+
+ Failure::new(code, message).with_parameters(outcome_parameters(payment))
+}
+
+/// What a merchant needs to find this payment again — the only place a `payment_id` reaches the
+/// provider when its own success field is null. An explicit list, never the request's own.
+fn outcome_parameters(payment: &api_models::payments::PaymentsResponse) -> ResponseParameters {
+ let mut parameters = ResponseParameters::from([
+ (
+ "payment_id".to_string(),
+ payment.payment_id.get_string_repr().to_owned(),
+ ),
+ ("status".to_string(), payment.status.to_string()),
+ (
+ "amount_capturable".to_string(),
+ payment.amount_capturable.get_amount_as_i64().to_string(),
+ ),
+ ]);
+
+ // A missing value drops its key: Twilio raises a JSON mapping exception on a non-string, which
+ // would break the whole response rather than this one field.
+ let optional = [
+ (
+ "merchant_order_reference_id",
+ payment.merchant_order_reference_id.clone(),
+ ),
+ ("connector", payment.connector.clone()),
+ (
+ "connector_transaction_id",
+ payment.connector_transaction_id.clone(),
+ ),
+ ("unified_code", payment.unified_code.clone()),
+ (
+ "amount_received",
+ payment
+ .amount_received
+ .map(|amount| amount.get_amount_as_i64().to_string()),
+ ),
+ ];
+
+ for (key, value) in optional {
+ if let Some(value) = value {
+ parameters.insert(key.to_string(), value);
+ }
+ }
+
+ parameters
+}
diff --git a/crates/router/src/core/telephone_order/twilio.rs b/crates/router/src/core/telephone_order/twilio.rs
new file mode 100644
index 0000000000..e1adfd164c
--- /dev/null
+++ b/crates/router/src/core/telephone_order/twilio.rs
@@ -0,0 +1,153 @@
+use api_models::telephone_order::twilio::{
+ TwilioGenericPayRequest, TwilioGenericPayResponse, TwilioPayMethod,
+};
+use common_utils::{
+ fp_utils,
+ types::{AmountConvertor, StringMajorUnitForConnector},
+};
+
+use crate::core::telephone_order::{
+ self, Context, Failure, Parameters, ResponseParameters, TelephoneOrderAdapter,
+};
+
+/// What Twilio can ask for that this endpoint does not do; the rest are shared.
+mod error_codes {
+ pub const TOKENIZE_UNSUPPORTED: &str = "TOKENIZE_UNSUPPORTED";
+ pub const BANK_ACCOUNT_UNSUPPORTED: &str = "BANK_ACCOUNT_UNSUPPORTED";
+}
+
+struct TwilioCardDetails {
+ card_number: cards::CardNumber,
+ card_exp_month: hyperswitch_masking::Secret<String>,
+ card_exp_year: hyperswitch_masking::Secret<String>,
+ card_cvc: hyperswitch_masking::Secret<String>,
+}
+
+/// Twilio's Generic Pay Connector. All but the request and response shapes is shared.
+pub struct TwilioGenericPay;
+
+#[async_trait::async_trait]
+impl TelephoneOrderAdapter for TwilioGenericPay {
+ type Request = TwilioGenericPayRequest;
+ type Response = TwilioGenericPayResponse;
+
+ fn transaction_reference(request: &Self::Request) -> String {
+ request.transaction_id.clone()
+ }
+
+ /// Twilio documents `transaction_id` as stable across its own retries — the same value for
+ /// all five retries of one `<Pay>` attempt, a different one for the next caller.
+ fn idempotency_reference(request: &Self::Request) -> Option<&str> {
+ Some(&request.transaction_id)
+ }
+
+ fn parameters(request: &Self::Request) -> Option<&Parameters> {
+ request.parameters.as_ref()
+ }
+
+ /// Maps the `<Pay>` verb's fields onto a card payment.
+ fn build_payments_request(
+ request: &Self::Request,
+ context: Context,
+ ) -> Result<api_models::payments::PaymentsRequest, Failure> {
+ fp_utils::when(request.method != TwilioPayMethod::Charge, || {
+ Err(Failure::new(
+ error_codes::TOKENIZE_UNSUPPORTED,
+ "Tokenization is not supported on this endpoint",
+ ))
+ })?;
+
+ fp_utils::when(
+ request.bankaccountnumber.is_some() || request.routingnumber.is_some(),
+ || {
+ Err(Failure::new(
+ error_codes::BANK_ACCOUNT_UNSUPPORTED,
+ "Bank account payments are not supported on this endpoint",
+ ))
+ },
+ )?;
+
+ let card = extract_card(request)?;
+
+ let currency = request
+ .currency_code
+ .ok_or_else(|| invalid_request("currency_code is required"))?;
+
+ let amount = request
+ .amount
+ .clone()
+ .ok_or_else(|| invalid_request("amount is required"))?;
+
+ let amount = StringMajorUnitForConnector
+ .convert_back(amount, currency)
+ .map_err(|error| invalid_request(format!("amount could not be parsed: {error}")))?;
+
+ let billing = request
+ .postal_code
+ .clone()
+ .map(|zip| api_models::payments::Address {
+ address: Some(api_models::payments::AddressDetails {
+ zip: Some(zip),
+ ..Default::default()
+ }),
+ ..Default::default()
+ });
+
+ Ok(api_models::payments::PaymentsRequest {
+ amount: Some(amount.into()),
+ currency: Some(currency),
+ payment_method: Some(common_enums::PaymentMethod::Card),
+ payment_method_data: Some(api_models::payments::PaymentMethodDataRequest {
+ payment_method_data: Some(api_models::payments::PaymentMethodData::Card(
+ api_models::payments::Card {
+ card_number: card.card_number,
+ card_exp_month: card.card_exp_month,
+ card_exp_year: card.card_exp_year,
+ card_cvc: card.card_cvc,
+ ..Default::default()
+ },
+ )),
+ billing: billing.clone(),
+ }),
+ billing,
+ description: request.description.clone(),
+ merchant_order_reference_id: Some(request.transaction_id.clone()),
+ ..context.payments_request()
+ })
+ }
+
+ fn success_response(
+ payment: &api_models::payments::PaymentsResponse,
+ parameters: ResponseParameters,
+ ) -> Self::Response {
+ TwilioGenericPayResponse::success(payment.payment_id.clone(), parameters)
+ }
+
+ fn failure_response(failure: Failure) -> Self::Response {
+ TwilioGenericPayResponse::failure(failure.code, failure.message, failure.parameters)
+ }
+}
+
+fn invalid_request(message: impl Into<String>) -> Failure {
+ Failure::new(telephone_order::error_codes::INVALID_REQUEST, message)
+}
+
+fn extract_card(request: &TwilioGenericPayRequest) -> Result<TwilioCardDetails, Failure> {
+ let missing = |field: &str| invalid_request(format!("{field} is required for a card charge"));
+
+ Ok(TwilioCardDetails {
+ card_number: request
+ .cardnumber
+ .clone()
+ .ok_or_else(|| missing("cardnumber"))?,
+ card_exp_month: request
+ .expiry_month
+ .clone()
+ .ok_or_else(|| missing("expiry_month"))?,
+ card_exp_year: request
+ .expiry_year
+ .clone()
+ .ok_or_else(|| missing("expiry_year"))?,
+ card_cvc: request.cvv.clone().ok_or_else(|| missing("cvv"))?,
+ })
+}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 427f1a4338..87dc38e345 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -317,6 +317,10 @@ pub fn mk_app(
{
server_app = server_app.service(routes::Poll::server(state.clone()))
}
+ #[cfg(all(feature = "oltp", feature = "v1"))]
+ {
+ server_app = server_app.service(routes::TelephoneOrder::server(state.clone()))
+ }
#[cfg(feature = "olap")]
{
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 193f1b7063..b24effd4c9 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -60,6 +60,8 @@ pub mod routing;
pub mod subscription;
pub mod superposition_proxy;
pub mod superposition_sdk_config;
+#[cfg(feature = "v1")]
+pub mod telephone_order;
pub mod three_ds_decision_rule;
pub mod tokenization;
#[cfg(feature = "olap")]
@@ -102,8 +104,8 @@ pub use self::app::{
FeatureMatrix, Files, Forex, Gsm, Health, Hypersense, Mandates, MerchantAccount,
MerchantConnectorAccount, OfferEngine, Oidc, PaymentLink, PaymentMethods, Payments, Poll,
ProcessTracker, ProcessTrackerDeprecated, Profile, ProfileAcquirer, ProfileNew, Refunds, Relay,
- RelayWebhooks, SdkConfig, SessionState, SuperpositionProxy, ThreeDsDecisionRule, User,
- UserDeprecated, Webhooks,
+ RelayWebhooks, SdkConfig, SessionState, SuperpositionProxy, TelephoneOrder,
+ ThreeDsDecisionRule, User, UserDeprecated, Webhooks,
};
#[cfg(feature = "olap")]
pub use self::app::{
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 71e562178c..5ef8f7ad88 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -63,6 +63,8 @@ use super::recovery_webhooks::*;
use super::refunds;
#[cfg(feature = "olap")]
use super::routing;
+#[cfg(all(feature = "oltp", feature = "v1"))]
+use super::telephone_order;
#[cfg(all(feature = "oltp", feature = "v2"))]
use super::tokenization as tokenization_routes;
#[cfg(feature = "olap")]
@@ -2868,6 +2870,20 @@ impl ThreeDsDecisionRule {
}
}
+pub struct TelephoneOrder;
+
+#[cfg(all(feature = "oltp", feature = "v1"))]
+impl TelephoneOrder {
+ pub fn server(state: AppState) -> Scope {
+ web::scope("/telephone_order")
+ .app_data(web::Data::new(state))
+ .service(
+ web::resource("/{merchant_id}/{provider}")
+ .route(web::post().to(telephone_order::telephone_order_charge)),
+ )
+ }
+}
+
#[cfg(feature = "olap")]
pub struct Verify;
#[cfg(all(feature = "olap", feature = "v1"))]
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 208addfacd..f85faa3f59 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -213,7 +213,10 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentsSubmitEligibility
// PaymentLinkCreate creates a payment intent, so it uses the Payments lock namespace
| Flow::PaymentLinkCreate
- | Flow::PaymentsCancelPostCaptureSync => Self::Payments,
+ | Flow::PaymentsCancelPostCaptureSync
+ // A telephone order adapter creates and confirms a payment, so it belongs in the
+ // Payments lock namespace
+ | Flow::TelephoneOrderCharge => Self::Payments,
Flow::PayoutsCreate
| Flow::PayoutsRetrieve
| Flow::PayoutsUpdate
diff --git a/crates/router/src/routes/telephone_order.rs b/crates/router/src/routes/telephone_order.rs
new file mode 100644
index 0000000000..4e8a463239
--- /dev/null
+++ b/crates/router/src/routes/telephone_order.rs
@@ -0,0 +1,91 @@
+use std::str::FromStr;
+
+use actix_web::{web, HttpRequest, HttpResponse};
+use router_env::{instrument, logger, tracing, Flow};
+
+use super::app::AppState;
+use crate::{
+ core::{
+ errors,
+ telephone_order::{
+ self, twilio::TwilioGenericPay, TelephoneOrderAdapter, TelephoneOrderProvider,
+ },
+ },
+ services::{api, authentication as auth},
+};
+
+#[cfg(feature = "v1")]
+#[instrument(skip_all, fields(flow = ?Flow::TelephoneOrderCharge, payment_id))]
+pub async fn telephone_order_charge(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ body: web::Bytes,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
+) -> HttpResponse {
+ let (merchant_id, provider) = path.into_inner();
+
+ match TelephoneOrderProvider::from_str(&provider) {
+ Ok(TelephoneOrderProvider::Twilio) => {
+ charge_with::<TwilioGenericPay>(state, req, body, merchant_id).await
+ }
+ Err(error) => {
+ logger::warn!("Unknown telephone order provider {provider}: {error:?}");
+ api::log_and_return_error_response(errors::ApiErrorResponse::InvalidRequestUrl.into())
+ }
+ }
+}
+
+#[cfg(feature = "v1")]
+async fn charge_with<A>(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ body: web::Bytes,
+ merchant_id: common_utils::id_type::MerchantId,
+) -> HttpResponse
+where
+ A: TelephoneOrderAdapter + Send,
+{
+ let flow = Flow::TelephoneOrderCharge;
+
+ match serde_json::from_slice::<A::Request>(&body) {
+ Ok(payload) => {
+ let payment_id = A::resolve_payment_id(&payload).ok().flatten();
+
+ tracing::Span::current().record(
+ "payment_id",
+ payment_id
+ .as_ref()
+ .map(|payment_id| payment_id.get_string_repr())
+ .unwrap_or_default(),
+ );
+
+ let locking_action = telephone_order::locking_action(payment_id.as_ref(), flow.clone());
+
+ let authenticator = A::authenticator(merchant_id, &payload);
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: auth::AuthenticationData, payload, req_state| {
+ A::charge(state, req_state, auth, payload)
+ },
+ &*authenticator,
+ locking_action,
+ ))
+ .await
+ }
+ Err(error) => {
+ logger::warn!("Telephone order request body could not be deserialized: {error:?}");
+ api::log_and_return_error_response(
+ errors::ApiErrorResponse::InvalidDataFormat {
+ field_name: "request body".to_string(),
+ expected_format: "a telephone order charge request for this provider"
+ .to_string(),
+ }
+ .into(),
+ )
+ }
+ }
+}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index b8bf89486c..5b28b290e2 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1,6 +1,6 @@
use std::{marker::PhantomData, str::FromStr};
-use actix_web::http::header::HeaderMap;
+use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue};
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodIntentConfirm;
#[cfg(feature = "v1")]
@@ -2560,6 +2560,47 @@ where
}
}
+#[derive(Debug)]
+#[cfg(feature = "v1")]
+pub struct ApiKeyBasicAuthWithMerchantIdFromRoute {
+ pub merchant_id: id_type::MerchantId,
+ pub profile_id: Option<id_type::ProfileId>,
+}
+
+#[cfg(feature = "v1")]
+#[async_trait]
+impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyBasicAuthWithMerchantIdFromRoute
+where
+ A: SessionStateInfo + Sync,
+{
+ async fn authenticate_and_fetch(
+ &self,
+ request_headers: &HeaderMap,
+ state: &A,
+ ) -> RouterResult<(AuthenticationData, AuthenticationType)> {
+ let (_username, api_key) = parse_basic_auth_credentials(request_headers)?;
+
+ let mut api_key = HeaderValue::from_str(api_key.peek())
+ .change_context(errors::ApiErrorResponse::InvalidBasicAuth)
+ .attach_printable("API key in the Basic auth password is not a valid header value")?;
+ // Keeps the key out of any debug rendering of the header map.
+ api_key.set_sensitive(true);
+
+ let mut request_headers = request_headers.clone();
+ request_headers.insert(HeaderName::from_static("api-key"), api_key);
+
+ if let Some(profile_id) = &self.profile_id {
+ let profile_id = HeaderValue::from_str(profile_id.get_string_repr())
+ .change_context(errors::ApiErrorResponse::InvalidBasicAuth)
+ .attach_printable("Profile ID is not a valid header value")?;
+ request_headers.insert(HeaderName::from_static("x-profile-id"), profile_id);
+ }
+
+ api_key_auth_with_merchant_id_from_route(&self.merchant_id, false, &request_headers, state)
+ .await
+ }
+}
+
#[derive(Debug)]
#[cfg(feature = "v2")]
pub struct MerchantIdAuth;
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 58dd305b36..c5d3382cbd 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -834,6 +834,8 @@ pub enum Flow {
ListMembersForEntity,
/// Authorize external token
AuthorizeUserToken,
+ /// Generic pay inbound charge flow, for any provider
+ TelephoneOrderCharge,
}
/// Trait for providing generic behaviour to flow metric