Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(router): Add manual payment status update API (#12293)
Anurag Thakur853dac2df856
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rsindex fba434e3e3..d1574efccc 100644--- a/crates/api_models/src/enums.rs+++ b/crates/api_models/src/enums.rs@@ -619,3 +619,24 @@ pub enum TokenStatus {/// Indicates that the token is deleted and further can't be used for paymentsDeleted,}++/// Enum representing the allowed intent statuses for manual status update+/// Only Succeeded and Failed are valid transitions from Review state+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum ManualUpdateIntentStatus {+ /// Transition the payment to succeeded state+ Succeeded,+ /// Transition the payment to failed state+ Failed,+}++impl ManualUpdateIntentStatus {+ /// Convert ManualUpdateIntentStatus to the corresponding IntentStatus+ pub fn to_intent_status(&self) -> IntentStatus {+ match self {+ Self::Succeeded => IntentStatus::Succeeded,+ Self::Failed => IntentStatus::Failed,+ }+ }+}diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rsindex 8421531a6c..c2f15a6813 100644--- a/crates/api_models/src/events/payment.rs+++ b/crates/api_models/src/events/payment.rs@@ -37,6 +37,7 @@ use crate::{PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse,PaymentsExtendAuthorizationRequest, PaymentsExternalAuthenticationRequest,PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest,+ PaymentsManualStatusUpdateRequest, PaymentsManualStatusUpdateResponse,PaymentsManualUpdateRequest, PaymentsManualUpdateResponse,PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest,PaymentsRetrieveRequest, PaymentsStartRequest, PaymentsUpdateMetadataRequest,@@ -570,6 +571,13 @@ impl ApiEventMetric for PaymentsManualUpdateRequest {}}+#[cfg(feature = "v1")]+impl ApiEventMetric for PaymentsManualStatusUpdateRequest {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ None+ }+}+#[cfg(feature = "v1")]impl ApiEventMetric for PaymentsManualUpdateResponse {fn get_api_event_type(&self) -> Option<ApiEventsType> {@@ -579,6 +587,15 @@ impl ApiEventMetric for PaymentsManualUpdateResponse {}}+#[cfg(feature = "v1")]+impl ApiEventMetric for PaymentsManualStatusUpdateResponse {+ fn get_api_event_type(&self) -> Option<ApiEventsType> {+ Some(ApiEventsType::Payment {+ payment_id: self.payment_id.clone(),+ })+ }+}+impl ApiEventMetric for PaymentsSessionResponse {fn get_api_event_type(&self) -> Option<ApiEventsType> {Some(ApiEventsType::Payment {diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rsindex 7f6f959287..17e35d3276 100644--- a/crates/api_models/src/payments.rs+++ b/crates/api_models/src/payments.rs@@ -11257,6 +11257,26 @@ pub struct PaymentsManualUpdateResponse {pub amount_capturable: Option<MinorUnit>,}+/// Request to manually update payment status from Review state (Dashboard API)+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+pub struct PaymentsManualStatusUpdateRequest {+ /// The target status to transition to (Succeeded or Failed)+ pub intent_status: enums::ManualUpdateIntentStatus,+}++/// Response for manual payment status update (Dashboard API)+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]+pub struct PaymentsManualStatusUpdateResponse {+ /// The identifier for the payment+ pub payment_id: id_type::PaymentId,+ /// The identifier for the payment attempt+ pub attempt_id: String,+ /// The updated status of the intent+ pub intent_status: enums::IntentStatus,+ /// The updated status of the attempt+ pub attempt_status: enums::AttemptStatus,+}+#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, SmithyModel)]#[smithy(namespace = "com.hyperswitch.smithy.types")]/// Indicates if 3DS method data was successfully completed or notdiff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex c60d51bd99..199034a689 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -12111,6 +12111,132 @@ pub async fn payments_manual_update())}+#[cfg(all(feature = "olap", feature = "v1"))]+pub async fn payments_manual_status_update(+ state: SessionState,+ platform: domain::Platform,+ payment_id: id_type::PaymentId,+ req: api_models::payments::PaymentsManualStatusUpdateRequest,+) -> RouterResponse<api_models::payments::PaymentsManualStatusUpdateResponse> {+ let api_models::payments::PaymentsManualStatusUpdateRequest { intent_status } = req;++ let merchant_id = platform.get_processor().get_account().get_id();++ let key_store = state+ .store+ .get_merchant_key_store_by_merchant_id(+ merchant_id,+ &state.store.get_master_key().to_vec().into(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)+ .attach_printable("Error while fetching the key store by merchant_id")?;++ let merchant_account = state+ .store+ .find_merchant_account_by_merchant_id(merchant_id, &key_store)+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)+ .attach_printable("Error while fetching the merchant_account by merchant_id")?;++ let payment_intent = state+ .store+ .find_payment_intent_by_payment_id_processor_merchant_id(+ &payment_id,+ merchant_account.get_id(),+ &key_store,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ .attach_printable("Error while fetching the payment_intent by payment_id, merchant_id")?;++ if payment_intent.status != enums::IntentStatus::Review {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "Payment status must be 'review' to perform manual status update, current status is '{}'",+ payment_intent.status+ ),+ }+ .into());+ }++ let attempt_id = payment_intent.active_attempt.get_id();++ let attempt_status = match intent_status {+ enums::ManualUpdateIntentStatus::Succeeded => enums::AttemptStatus::Charged,+ enums::ManualUpdateIntentStatus::Failed => enums::AttemptStatus::Failure,+ };++ let payment_attempt = state+ .store+ .find_payment_attempt_by_payment_id_processor_merchant_id_attempt_id(+ &payment_id,+ merchant_id,+ &attempt_id,+ merchant_account.storage_scheme,+ &key_store,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ .attach_printable("Error while fetching the payment_attempt")?;++ if payment_attempt.status != enums::AttemptStatus::CaptureReview {+ return Err(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "Payment attempt status must be 'capture_review' to perform manual status update, current status is '{}'",+ payment_attempt.status+ ),+ }+ .into());+ }++ let attempt_update = storage::PaymentAttemptUpdate::StatusUpdate {+ status: attempt_status,+ updated_by: merchant_account.storage_scheme.to_string(),+ };++ let updated_payment_attempt = state+ .store+ .update_payment_attempt_with_attempt_id(+ payment_attempt,+ attempt_update,+ merchant_account.storage_scheme,+ &key_store,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ .attach_printable("Error while updating the payment_attempt")?;++ let intent_status = intent_status.to_intent_status();++ let intent_update = storage::PaymentIntentUpdate::ManualUpdate {+ status: Some(intent_status),+ updated_by: merchant_account.storage_scheme.to_string(),+ };++ state+ .store+ .update_payment_intent(+ payment_intent,+ intent_update,+ &key_store,+ merchant_account.storage_scheme,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)+ .attach_printable("Error while updating payment_intent")?;++ Ok(services::ApplicationResponse::Json(+ api_models::payments::PaymentsManualStatusUpdateResponse {+ payment_id,+ attempt_id: updated_payment_attempt.attempt_id,+ intent_status,+ attempt_status: updated_payment_attempt.status,+ },+ ))+}+// Trait for Eligibility Checks#[cfg(feature = "v1")]#[async_trait::async_trait]diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex 076fc11626..12b62ab51f 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -950,6 +950,10 @@ impl Payments {web::resource("/{payment_id}/manual-update").route(web::put().to(payments::payments_manual_update)),)+ .service(+ web::resource("/{payment_id}/manual-status-update")+ .route(web::post().to(payments::payments_manual_status_update)),+ )}#[cfg(feature = "oltp")]{diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex f15a281392..679e93dbac 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -171,6 +171,7 @@ impl From<Flow> for ApiIdentifier {| Flow::GetExtendedCardInfo| Flow::PaymentsCompleteAuthorize| Flow::PaymentsManualUpdate+ | Flow::PaymentsManualStatusUpdate| Flow::SessionUpdateTaxCalculation| Flow::PaymentsConfirmIntent| Flow::PaymentsCreateIntentdiff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex 98949bcb44..1c12c6a6ca 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -2761,6 +2761,39 @@ pub async fn payments_manual_update(.await}+#[cfg(all(feature = "olap", feature = "v1"))]+/// Manually update payment status from Review to Succeeded or Failed (Dashboard API with JWT auth)+#[instrument(skip_all, fields(flow = ?Flow::PaymentsManualStatusUpdate, payment_id))]+pub async fn payments_manual_status_update(+ state: web::Data<app::AppState>,+ req: actix_web::HttpRequest,+ json_payload: web::Json<api_models::payments::PaymentsManualStatusUpdateRequest>,+ path: web::Path<common_utils::id_type::PaymentId>,+) -> impl Responder {+ let flow = Flow::PaymentsManualStatusUpdate;+ let payload = json_payload.into_inner();+ let payment_id = path.into_inner();++ tracing::Span::current().record("payment_id", payment_id.get_string_repr());++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ payload,+ |state, auth: auth::AuthenticationData, req, _req_state| {+ payments::payments_manual_status_update(state, auth.platform, payment_id.clone(), req)+ },+ &auth::JWTAuth {+ permission: Permission::ProfilePaymentWrite,+ allow_connected: true,+ allow_platform: true,+ },+ api_locking::LockAction::NotApplicable,+ ))+ .await+}+#[cfg(feature = "v1")]/// Retrieve endpoint for merchant to fetch the encrypted customer payment method data#[instrument(skip_all, fields(flow = ?Flow::GetExtendedCardInfo, payment_id))]diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 93b119c1f7..d08c7e4c83 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -623,6 +623,8 @@ pub enum Flow {RefundsManualUpdate,/// Manually update the payment details like status, error code, error message etc.PaymentsManualUpdate,+ /// Manually update payment status from dashboard (Review → Succeeded/Failed)+ PaymentsManualStatusUpdate,#[cfg(feature = "payouts")]/// Manually update the payout details like status, error code, error message etc.PayoutsManualUpdate,