-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
payments.rs
1424 lines (1272 loc) · 49.6 KB
/
payments.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub mod access_token;
pub mod customers;
pub mod flows;
pub mod helpers;
pub mod operations;
pub mod tokenization;
pub mod transformers;
use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant};
use api_models::payments::Metadata;
use common_utils::pii;
use error_stack::{IntoReport, ResultExt};
use futures::future::join_all;
use masking::Secret;
use router_env::{instrument, tracing};
use storage_models::ephemeral_key;
use time;
pub use self::operations::{
PaymentCancel, PaymentCapture, PaymentConfirm, PaymentCreate, PaymentMethodValidate,
PaymentResponse, PaymentSession, PaymentStatus, PaymentUpdate,
};
use self::{
flows::{ConstructFlowSpecificData, Feature},
helpers::authenticate_client_secret,
operations::{payment_complete_authorize, BoxedOperation, Operation},
};
use super::errors::StorageErrorExt;
use crate::{
configs::settings::PaymentMethodTypeTokenFilter,
core::{
errors::{self, CustomResult, RouterResponse, RouterResult},
payment_methods::vault,
},
db::StorageInterface,
logger,
routes::{metrics, AppState},
scheduler::utils as pt_utils,
services::{self, api::Authenticate},
types::{
self, api, domain,
storage::{self, enums as storage_enums},
},
utils::{Encode, OptionExt, ValueExt},
};
#[instrument(skip_all, fields(payment_id, merchant_id))]
pub async fn payments_operation_core<F, Req, Op, FData>(
state: &AppState,
merchant_account: domain::MerchantAccount,
operation: Op,
req: Req,
call_connector_action: CallConnectorAction,
) -> RouterResult<(PaymentData<F>, Req, Option<domain::Customer>)>
where
F: Send + Clone + Sync,
Req: Authenticate,
Op: Operation<F, Req> + Send + Sync,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn types::api::Connector:
services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData>,
FData: Send + Sync,
{
let operation: BoxedOperation<'_, F, Req> = Box::new(operation);
tracing::Span::current().record("merchant_id", merchant_account.merchant_id.as_str());
let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, &merchant_account)?;
tracing::Span::current().record("payment_id", &format!("{}", validate_result.payment_id));
let (operation, mut payment_data, customer_details) = operation
.to_get_tracker()?
.get_trackers(
state,
&validate_result.payment_id,
&req,
validate_result.mandate_type.to_owned(),
&merchant_account,
)
.await?;
authenticate_client_secret(
req.get_client_secret(),
&payment_data.payment_intent,
merchant_account.intent_fulfillment_time,
)?;
let (operation, customer) = operation
.to_domain()?
.get_or_create_customer_details(
&*state.store,
&mut payment_data,
customer_details,
validate_result.merchant_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Failed while fetching/creating customer")?;
let connector = get_connector_choice(
&operation,
state,
&req,
&merchant_account,
&mut payment_data,
)
.await?;
let (mut payment_data, tokenization_action) =
get_connector_tokenization_action(state, &operation, payment_data, &validate_result)
.await?;
let updated_customer = call_create_connector_customer_if_required(
state,
&customer,
&merchant_account,
&mut payment_data,
)
.await?;
if let Some(connector_details) = connector {
if should_add_task_to_process_tracker(&payment_data) {
operation
.to_domain()?
.add_task_to_process_tracker(state, &payment_data.payment_attempt)
.await?;
}
payment_data = match connector_details {
api::ConnectorCallType::Single(connector) => {
let router_data = call_connector_service(
state,
&merchant_account,
connector,
&operation,
&mut payment_data,
&customer,
call_connector_action,
tokenization_action,
updated_customer,
)
.await?;
let operation = Box::new(PaymentResponse);
let db = &*state.store;
operation
.to_post_update_tracker()?
.update_tracker(
db,
&validate_result.payment_id,
payment_data,
router_data,
merchant_account.storage_scheme,
)
.await?
}
api::ConnectorCallType::Multiple(connectors) => {
call_multiple_connectors_service(
state,
&merchant_account,
connectors,
&operation,
payment_data,
&customer,
)
.await?
}
};
if should_delete_pm_from_locker(payment_data.payment_intent.status) {
vault::Vault::delete_locker_payment_method_by_lookup_key(state, &payment_data.token)
.await
}
} else {
(_, payment_data) = operation
.to_update_tracker()?
.update_trackers(
&*state.store,
payment_data.clone(),
customer.clone(),
validate_result.storage_scheme,
updated_customer,
)
.await?;
}
Ok((payment_data, req, customer))
}
#[allow(clippy::too_many_arguments)]
pub async fn payments_core<F, Res, Req, Op, FData>(
state: &AppState,
merchant_account: domain::MerchantAccount,
operation: Op,
req: Req,
auth_flow: services::AuthFlow,
call_connector_action: CallConnectorAction,
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
FData: Send + Sync,
Op: Operation<F, Req> + Send + Sync + Clone,
Req: Debug + Authenticate,
Res: transformers::ToResponse<Req, PaymentData<F>, Op>,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn types::api::Connector:
services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData>,
{
let (payment_data, req, customer) = payments_operation_core(
state,
merchant_account,
operation.clone(),
req,
call_connector_action,
)
.await?;
Res::generate_response(
Some(req),
payment_data,
customer,
auth_flow,
&state.conf.server,
operation,
)
}
fn is_start_pay<Op: Debug>(operation: &Op) -> bool {
format!("{operation:?}").eq("PaymentStart")
}
#[derive(Clone, Debug)]
pub struct PaymentsRedirectResponseData {
pub connector: Option<String>,
pub param: Option<String>,
pub merchant_id: Option<String>,
pub json_payload: Option<serde_json::Value>,
pub resource_id: api::PaymentIdType,
pub force_sync: bool,
pub creds_identifier: Option<String>,
}
#[async_trait::async_trait]
pub trait PaymentRedirectFlow: Sync {
async fn call_payment_flow(
&self,
state: &AppState,
merchant_account: domain::MerchantAccount,
req: PaymentsRedirectResponseData,
connector_action: CallConnectorAction,
) -> RouterResponse<api::PaymentsResponse>;
fn get_payment_action(&self) -> services::PaymentAction;
fn generate_response(
&self,
payments_response: api_models::payments::PaymentsResponse,
merchant_account: types::domain::MerchantAccount,
payment_id: String,
connector: String,
) -> RouterResult<api::RedirectionResponse>;
#[allow(clippy::too_many_arguments)]
async fn handle_payments_redirect_response(
&self,
state: &AppState,
merchant_account: domain::MerchantAccount,
req: PaymentsRedirectResponseData,
) -> RouterResponse<api::RedirectionResponse> {
metrics::REDIRECTION_TRIGGERED.add(
&metrics::CONTEXT,
1,
&[
metrics::request::add_attributes(
"connector",
req.connector.to_owned().unwrap_or("null".to_string()),
),
metrics::request::add_attributes(
"merchant_id",
merchant_account.merchant_id.to_owned(),
),
],
);
let connector = req.connector.clone().get_required_value("connector")?;
let query_params = req.param.clone().get_required_value("param")?;
let resource_id = api::PaymentIdTypeExt::get_payment_intent_id(&req.resource_id)
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_id",
})?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector,
api::GetToken::Connector,
)?;
let flow_type = connector_data
.connector
.get_flow_type(
&query_params,
req.json_payload.clone(),
self.get_payment_action(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to decide the response flow")?;
let response = self
.call_payment_flow(state, merchant_account.clone(), req.clone(), flow_type)
.await;
let payments_response = match response? {
services::ApplicationResponse::Json(response) => Ok(response),
_ => Err(errors::ApiErrorResponse::InternalServerError)
.into_report()
.attach_printable("Failed to get the response in json"),
}?;
let result =
self.generate_response(payments_response, merchant_account, resource_id, connector)?;
Ok(services::ApplicationResponse::JsonForRedirection(result))
}
}
#[derive(Clone, Debug)]
pub struct PaymentRedirectCompleteAuthorize;
#[async_trait::async_trait]
impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {
async fn call_payment_flow(
&self,
state: &AppState,
merchant_account: domain::MerchantAccount,
req: PaymentsRedirectResponseData,
connector_action: CallConnectorAction,
) -> RouterResponse<api::PaymentsResponse> {
let payment_confirm_req = api::PaymentsRequest {
payment_id: Some(req.resource_id.clone()),
merchant_id: req.merchant_id.clone(),
metadata: Some(Metadata {
order_details: None,
redirect_response: Some(api_models::payments::RedirectResponse {
param: req.param.map(Secret::new),
json_payload: Some(req.json_payload.unwrap_or(serde_json::json!({})).into()),
}),
allowed_payment_method_types: None,
order_category: None,
}),
..Default::default()
};
payments_core::<api::CompleteAuthorize, api::PaymentsResponse, _, _, _>(
state,
merchant_account,
payment_complete_authorize::CompleteAuthorize,
payment_confirm_req,
services::api::AuthFlow::Merchant,
connector_action,
)
.await
}
fn get_payment_action(&self) -> services::PaymentAction {
services::PaymentAction::CompleteAuthorize
}
fn generate_response(
&self,
payments_response: api_models::payments::PaymentsResponse,
merchant_account: types::domain::MerchantAccount,
payment_id: String,
connector: String,
) -> RouterResult<api::RedirectionResponse> {
// There might be multiple redirections needed for some flows
// If the status is requires customer action, then send the startpay url again
// The redirection data must have been provided and updated by the connector
match payments_response.status {
api_models::enums::IntentStatus::RequiresCustomerAction => {
let startpay_url = payments_response
.next_action
.and_then(|next_action_data| match next_action_data {
api_models::payments::NextActionData::RedirectToUrl { redirect_to_url } => Some(redirect_to_url),
api_models::payments::NextActionData::DisplayBankTransferInformation { .. } => None,
api_models::payments::NextActionData::ThirdPartySdkSessionToken { .. } => None
})
.ok_or(errors::ApiErrorResponse::InternalServerError)
.into_report()
.attach_printable(
"did not receive redirect to url when status is requires customer action",
)?;
Ok(api::RedirectionResponse {
return_url: String::new(),
params: vec![],
return_url_with_query_params: startpay_url,
http_method: "GET".to_string(),
headers: vec![],
})
}
// If the status is terminal status, then redirect to merchant return url to provide status
api_models::enums::IntentStatus::Succeeded
| api_models::enums::IntentStatus::Failed
| api_models::enums::IntentStatus::Cancelled | api_models::enums::IntentStatus::RequiresCapture=> helpers::get_handle_response_url(
payment_id,
&merchant_account,
payments_response,
connector,
),
_ => Err(errors::ApiErrorResponse::InternalServerError).into_report().attach_printable_lazy(|| format!("Could not proceed with payment as payment status {} cannot be handled during redirection",payments_response.status))?
}
}
}
#[derive(Clone, Debug)]
pub struct PaymentRedirectSync;
#[async_trait::async_trait]
impl PaymentRedirectFlow for PaymentRedirectSync {
async fn call_payment_flow(
&self,
state: &AppState,
merchant_account: domain::MerchantAccount,
req: PaymentsRedirectResponseData,
connector_action: CallConnectorAction,
) -> RouterResponse<api::PaymentsResponse> {
let payment_sync_req = api::PaymentsRetrieveRequest {
resource_id: req.resource_id,
merchant_id: req.merchant_id,
param: req.param,
force_sync: req.force_sync,
connector: req.connector,
merchant_connector_details: req.creds_identifier.map(|creds_id| {
api::MerchantConnectorDetailsWrap {
creds_identifier: creds_id,
encoded_data: None,
}
}),
};
payments_core::<api::PSync, api::PaymentsResponse, _, _, _>(
state,
merchant_account,
PaymentStatus,
payment_sync_req,
services::api::AuthFlow::Merchant,
connector_action,
)
.await
}
fn generate_response(
&self,
payments_response: api_models::payments::PaymentsResponse,
merchant_account: types::domain::MerchantAccount,
payment_id: String,
connector: String,
) -> RouterResult<api::RedirectionResponse> {
helpers::get_handle_response_url(
payment_id,
&merchant_account,
payments_response,
connector,
)
}
fn get_payment_action(&self) -> services::PaymentAction {
services::PaymentAction::PSync
}
}
#[allow(clippy::too_many_arguments)]
pub async fn call_connector_service<F, RouterDReq, ApiRequest>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest>,
payment_data: &mut PaymentData<F>,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
tokenization_action: TokenizationAction,
updated_customer: Option<storage::CustomerUpdate>,
) -> RouterResult<types::RouterData<F, RouterDReq, types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, types::PaymentsResponseData>,
types::RouterData<F, RouterDReq, types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, types::PaymentsResponseData>,
{
let stime_connector = Instant::now();
let mut router_data = payment_data
.construct_router_data(state, connector.connector.id(), merchant_account, customer)
.await?;
let add_access_token_result = router_data
.add_access_token(state, &connector, merchant_account)
.await?;
let mut should_continue_further = access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&call_connector_action,
);
let pm_token = router_data
.add_payment_method_token(state, &connector, &tokenization_action)
.await?;
if let Some(payment_method_token) = pm_token {
router_data.payment_method_token = Some(payment_method_token);
};
(router_data, should_continue_further) = complete_preprocessing_steps_if_required(
state,
&connector,
payment_data,
router_data,
should_continue_further,
)
.await?;
if let Ok(types::PaymentsResponseData::PreProcessingResponse {
session_token: Some(session_token),
..
}) = router_data.response.to_owned()
{
payment_data.sessions_token.push(session_token);
};
let connector_request = if should_continue_further {
// Check if the actual flow specific request can be built with available data
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
None
};
// Update the payment trackers just before calling the connector
// Since the request is already built in the previous step,
// there should be no error in request construction from hyperswitch end
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
&*state.store,
payment_data.clone(),
customer.clone(),
merchant_account.storage_scheme,
updated_customer,
)
.await?;
// The status of payment_attempt and intent will be updated in the previous step
// This field will be used by the connector
router_data.status = payment_data.payment_attempt.status;
let router_data_res = if should_continue_further {
router_data
.decide_flows(
state,
&connector,
customer,
call_connector_action,
merchant_account,
connector_request,
)
.await
} else {
Ok(router_data)
};
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
router_data_res
}
pub async fn call_multiple_connectors_service<F, Op, Req>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
connectors: Vec<api::SessionConnectorData>,
_operation: &Op,
mut payment_data: PaymentData<F>,
customer: &Option<domain::Customer>,
) -> RouterResult<PaymentData<F>>
where
Op: Debug,
F: Send + Clone,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, Req, types::PaymentsResponseData>,
types::RouterData<F, Req, types::PaymentsResponseData>: Feature<F, Req>,
// To construct connector flow specific api
dyn api::Connector: services::api::ConnectorIntegration<F, Req, types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, Req>,
{
let call_connectors_start_time = Instant::now();
let mut join_handlers = Vec::with_capacity(connectors.len());
for session_connector_data in connectors.iter() {
let connector_id = session_connector_data.connector.connector.id();
let router_data = payment_data
.construct_router_data(state, connector_id, merchant_account, customer)
.await?;
let res = router_data.decide_flows(
state,
&session_connector_data.connector,
customer,
CallConnectorAction::Trigger,
merchant_account,
None,
);
join_handlers.push(res);
}
let result = join_all(join_handlers).await;
for (connector_res, session_connector) in result.into_iter().zip(connectors) {
let connector_name = session_connector.connector.connector_name.to_string();
match connector_res {
Ok(connector_response) => {
if let Ok(types::PaymentsResponseData::SessionResponse { session_token, .. }) =
connector_response.response
{
// If session token is NoSessionTokenReceived, it is not pushed into the sessions_token as there is no response or there can be some error
// In case of error, that error is already logged
if !matches!(
session_token,
api_models::payments::SessionToken::NoSessionTokenReceived,
) {
payment_data.sessions_token.push(session_token);
}
}
}
Err(connector_error) => {
logger::error!(
"sessions_connector_error {} {:?}",
connector_name,
connector_error
);
}
}
}
let call_connectors_end_time = Instant::now();
let call_connectors_duration =
call_connectors_end_time.saturating_duration_since(call_connectors_start_time);
tracing::info!(duration = format!("Duration taken: {}", call_connectors_duration.as_millis()));
Ok(payment_data)
}
pub async fn call_create_connector_customer_if_required<F, Req>(
state: &AppState,
customer: &Option<domain::Customer>,
merchant_account: &domain::MerchantAccount,
payment_data: &mut PaymentData<F>,
) -> RouterResult<Option<storage::CustomerUpdate>>
where
F: Send + Clone + Sync,
Req: Send + Sync,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, Req, types::PaymentsResponseData>,
types::RouterData<F, Req, types::PaymentsResponseData>: Feature<F, Req> + Send,
// To construct connector flow specific api
dyn api::Connector: services::api::ConnectorIntegration<F, Req, types::PaymentsResponseData>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, Req>,
{
let connector_name = payment_data.payment_attempt.connector.clone();
match connector_name {
Some(connector_name) => {
let connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
)?;
let connector_label = helpers::get_connector_label(
payment_data.payment_intent.business_country,
&payment_data.payment_intent.business_label,
payment_data.payment_attempt.business_sub_label.as_ref(),
&connector_name,
);
let (should_call_connector, existing_connector_customer_id) =
customers::should_call_connector_create_customer(
state,
&connector,
customer,
&connector_label,
);
if should_call_connector {
// Create customer at connector and update the customer table to store this data
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_account,
customer,
)
.await?;
let connector_customer_id = router_data
.create_connector_customer(state, &connector)
.await?;
let customer_update = customers::update_connector_customer_in_customers(
&connector_label,
customer.as_ref(),
&connector_customer_id,
)
.await;
payment_data.connector_customer_id = connector_customer_id;
Ok(customer_update)
} else {
// Customer already created in previous calls use the same value, no need to update
payment_data.connector_customer_id =
existing_connector_customer_id.map(ToOwned::to_owned);
Ok(None)
}
}
None => Ok(None),
}
}
async fn complete_preprocessing_steps_if_required<F, Req>(
state: &AppState,
connector: &api::ConnectorData,
payment_data: &PaymentData<F>,
router_data: types::RouterData<F, Req, types::PaymentsResponseData>,
should_continue_payment: bool,
) -> RouterResult<(types::RouterData<F, Req, types::PaymentsResponseData>, bool)>
where
F: Send + Clone + Sync,
Req: Send + Sync,
types::RouterData<F, Req, types::PaymentsResponseData>: Feature<F, Req> + Send,
dyn api::Connector: services::api::ConnectorIntegration<F, Req, types::PaymentsResponseData>,
{
//TODO: For ACH transfers, if preprocessing_step is not required for connectors encountered in future, add the check
let router_data_and_should_continue_payment = match payment_data.payment_method_data.clone() {
Some(api_models::payments::PaymentMethodData::BankTransfer(data)) => match data.deref() {
api_models::payments::BankTransferData::AchBankTransfer { .. } => {
if payment_data.payment_attempt.preprocessing_step_id.is_none() {
(
router_data.preprocessing_steps(state, connector).await?,
false,
)
} else {
(router_data, should_continue_payment)
}
}
_ => (router_data, should_continue_payment),
},
Some(api_models::payments::PaymentMethodData::Wallet(_)) => {
if connector.connector_name.to_string() == *"trustpay" {
(
router_data.preprocessing_steps(state, connector).await?,
false,
)
} else {
(router_data, should_continue_payment)
}
}
_ => (router_data, should_continue_payment),
};
Ok(router_data_and_should_continue_payment)
}
fn is_payment_method_tokenization_enabled_for_connector(
state: &AppState,
connector_name: &str,
payment_method: &storage::enums::PaymentMethod,
payment_method_type: &Option<storage::enums::PaymentMethodType>,
) -> RouterResult<bool> {
let connector_tokenization_filter = state.conf.tokenization.0.get(connector_name);
Ok(connector_tokenization_filter
.map(|connector_filter| {
connector_filter
.payment_method
.clone()
.contains(payment_method)
&& is_payment_method_type_allowed_for_connector(
payment_method_type,
connector_filter.payment_method_type.clone(),
)
})
.unwrap_or(false))
}
fn is_payment_method_type_allowed_for_connector(
current_pm_type: &Option<storage::enums::PaymentMethodType>,
pm_type_filter: Option<PaymentMethodTypeTokenFilter>,
) -> bool {
match current_pm_type.clone().zip(pm_type_filter) {
Some((pm_type, type_filter)) => match type_filter {
PaymentMethodTypeTokenFilter::AllAccepted => true,
PaymentMethodTypeTokenFilter::EnableOnly(enabled) => enabled.contains(&pm_type),
PaymentMethodTypeTokenFilter::DisableOnly(disabled) => !disabled.contains(&pm_type),
},
None => true, // Allow all types if payment_method_type is not present
}
}
async fn decide_payment_method_tokenize_action(
state: &AppState,
connector_name: &str,
payment_method: &storage::enums::PaymentMethod,
pm_parent_token: Option<&String>,
is_connector_tokenization_enabled: bool,
) -> RouterResult<TokenizationAction> {
match pm_parent_token {
None => {
if is_connector_tokenization_enabled {
Ok(TokenizationAction::TokenizeInConnectorAndRouter)
} else {
Ok(TokenizationAction::TokenizeInRouter)
}
}
Some(token) => {
let redis_conn = state.store.get_redis_conn();
let key = format!(
"pm_token_{}_{}_{}",
token.to_owned(),
payment_method,
connector_name
);
let connector_token_option = redis_conn
.get_key::<Option<String>>(&key)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?;
match connector_token_option {
Some(connector_token) => Ok(TokenizationAction::ConnectorToken(connector_token)),
None => {
if is_connector_tokenization_enabled {
Ok(TokenizationAction::TokenizeInConnector)
} else {
Ok(TokenizationAction::TokenizeInRouter)
}
}
}
}
}
}
#[derive(Clone)]
pub enum TokenizationAction {
TokenizeInRouter,
TokenizeInConnector,
TokenizeInConnectorAndRouter,
ConnectorToken(String),
SkipConnectorTokenization,
}
#[allow(clippy::too_many_arguments)]
pub async fn get_connector_tokenization_action<F, Req>(
state: &AppState,
operation: &BoxedOperation<'_, F, Req>,
mut payment_data: PaymentData<F>,
validate_result: &operations::ValidateResult<'_>,
) -> RouterResult<(PaymentData<F>, TokenizationAction)>
where
F: Send + Clone,
{
let connector = payment_data.payment_attempt.connector.to_owned();
let is_mandate = payment_data
.mandate_id
.as_ref()
.and_then(|inner| inner.mandate_reference_id.as_ref())
.map(|mandate_reference| match mandate_reference {
api_models::payments::MandateReferenceId::ConnectorMandateId(_) => true,
api_models::payments::MandateReferenceId::NetworkMandateId(_) => false,
})
.unwrap_or(false);
let payment_data_and_tokenization_action = match connector {
Some(_) if is_mandate => (payment_data, TokenizationAction::SkipConnectorTokenization),
Some(connector) if is_operation_confirm(&operation) => {
let payment_method = &payment_data
.payment_attempt
.payment_method
.get_required_value("payment_method")?;
let payment_method_type = &payment_data.payment_attempt.payment_method_type;
let is_connector_tokenization_enabled =
is_payment_method_tokenization_enabled_for_connector(
state,
&connector,
payment_method,
payment_method_type,
)?;
let payment_method_action = decide_payment_method_tokenize_action(
state,
&connector,
payment_method,
payment_data.token.as_ref(),
is_connector_tokenization_enabled,
)
.await?;
let connector_tokenization_action = match payment_method_action {
TokenizationAction::TokenizeInRouter => {
let (_operation, payment_method_data) = operation
.to_domain()?
.make_pm_data(state, &mut payment_data, validate_result.storage_scheme)
.await?;
payment_data.payment_method_data = payment_method_data;
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::TokenizeInConnector => TokenizationAction::TokenizeInConnector,
TokenizationAction::TokenizeInConnectorAndRouter => {
let (_operation, payment_method_data) = operation
.to_domain()?
.make_pm_data(state, &mut payment_data, validate_result.storage_scheme)
.await?;
payment_data.payment_method_data = payment_method_data;
TokenizationAction::TokenizeInConnector
}
TokenizationAction::ConnectorToken(token) => {
payment_data.pm_token = Some(token);
TokenizationAction::SkipConnectorTokenization
}
TokenizationAction::SkipConnectorTokenization => {
TokenizationAction::SkipConnectorTokenization
}
};
(payment_data, connector_tokenization_action)
}
_ => {
let (_operation, payment_method_data) = operation
.to_domain()?
.make_pm_data(state, &mut payment_data, validate_result.storage_scheme)
.await?;
payment_data.payment_method_data = payment_method_data;
(payment_data, TokenizationAction::SkipConnectorTokenization)
}
};
Ok(payment_data_and_tokenization_action)
}
#[derive(Clone)]
pub enum CallConnectorAction {
Trigger,
Avoid,
StatusUpdate {
status: storage_enums::AttemptStatus,
error_code: Option<String>,
error_message: Option<String>,
},
HandleResponse(Vec<u8>),
}
#[derive(Clone, Default, Debug)]