-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathpayment_methods.rs
2652 lines (2408 loc) · 99.7 KB
/
payment_methods.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 cards;
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
pub mod migration;
pub mod network_tokenization;
pub mod surcharge_decision_configs;
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
pub mod tokenize;
pub mod transformers;
pub mod utils;
mod validator;
pub mod vault;
use std::borrow::Cow;
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use std::collections::HashSet;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use std::str::FromStr;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
pub use api_models::enums as api_enums;
pub use api_models::enums::Connector;
use api_models::payment_methods;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use common_utils::ext_traits::{Encode, OptionExt};
use common_utils::{consts::DEFAULT_LOCALE, id_type};
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use common_utils::{
crypto::Encryptable,
ext_traits::{AsyncExt, Encode, ValueExt},
fp_utils::when,
generate_id, types as util_types,
};
use diesel_models::{
enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData,
};
use error_stack::{report, ResultExt};
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
use hyperswitch_domain_models::api::{GenericLinks, GenericLinksData};
#[cfg(all(
feature = "v2",
feature = "payment_methods_v2",
feature = "customer_v2"
))]
use hyperswitch_domain_models::mandates::CommonMandateReference;
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use hyperswitch_domain_models::payment_method_data;
use hyperswitch_domain_models::payments::{
payment_attempt::PaymentAttempt, PaymentIntent, VaultData,
};
use masking::{PeekInterface, Secret};
use router_env::{instrument, tracing};
use time::Duration;
use super::{
errors::{RouterResponse, StorageErrorExt},
pm_auth,
};
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
use crate::{
configs::settings,
core::{payment_methods::transformers as pm_transforms, payments as payments_core},
headers, logger,
routes::{self, payment_methods as pm_routes},
services::encryption,
types::{
api::{self, payment_methods::PaymentMethodCreateExt},
domain::types as domain_types,
payment_methods as pm_types,
storage::{ephemeral_key, PaymentMethodListContext},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::ext_traits::OptionExt,
};
use crate::{
consts,
core::{
errors::{self, RouterResult},
payments::helpers as payment_helpers,
},
routes::{app::StorageInterface, SessionState},
services,
types::{
domain,
storage::{self, enums as storage_enums},
},
};
const PAYMENT_METHOD_STATUS_UPDATE_TASK: &str = "PAYMENT_METHOD_STATUS_UPDATE";
const PAYMENT_METHOD_STATUS_TAG: &str = "PAYMENT_METHOD_STATUS";
#[instrument(skip_all)]
pub async fn retrieve_payment_method_core(
pm_data: &Option<domain::PaymentMethodData>,
state: &SessionState,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<(Option<domain::PaymentMethodData>, Option<String>)> {
match pm_data {
pm_opt @ Some(pm @ domain::PaymentMethodData::Card(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::Card,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::BankDebit(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::BankDebit,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
pm @ Some(domain::PaymentMethodData::PayLater(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Crypto(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Upi(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Voucher(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::Reward) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::RealTimePayment(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::CardRedirect(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::GiftCard(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::OpenBanking(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::MobilePayment(_)) => Ok((pm.to_owned(), None)),
pm @ Some(domain::PaymentMethodData::NetworkToken(_)) => Ok((pm.to_owned(), None)),
pm_opt @ Some(pm @ domain::PaymentMethodData::BankTransfer(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::BankTransfer,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::Wallet(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::Wallet,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
pm_opt @ Some(pm @ domain::PaymentMethodData::BankRedirect(_)) => {
let payment_token = payment_helpers::store_payment_method_data_in_vault(
state,
payment_attempt,
payment_intent,
enums::PaymentMethod::BankRedirect,
pm,
merchant_key_store,
business_profile,
)
.await?;
Ok((pm_opt.to_owned(), payment_token))
}
_ => Ok((None, None)),
}
}
pub async fn initiate_pm_collect_link(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payment_methods::PaymentMethodCollectLinkRequest,
) -> RouterResponse<payment_methods::PaymentMethodCollectLinkResponse> {
// Validate request and initiate flow
let pm_collect_link_data =
validator::validate_request_and_initiate_payment_method_collect_link(
&state,
&merchant_account,
&key_store,
&req,
)
.await?;
// Create DB entries
let pm_collect_link = create_pm_collect_db_entry(
&state,
&merchant_account,
&pm_collect_link_data,
req.return_url.clone(),
)
.await?;
let customer_id = id_type::CustomerId::try_from(Cow::from(pm_collect_link.primary_reference))
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})?;
// Return response
let url = pm_collect_link.url.peek();
let response = payment_methods::PaymentMethodCollectLinkResponse {
pm_collect_link_id: pm_collect_link.link_id,
customer_id,
expiry: pm_collect_link.expiry,
link: url::Url::parse(url)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!("Failed to parse the payment method collect link - {}", url)
})?
.into(),
return_url: pm_collect_link.return_url,
ui_config: pm_collect_link.link_data.ui_config,
enabled_payment_methods: pm_collect_link.link_data.enabled_payment_methods,
};
Ok(services::ApplicationResponse::Json(response))
}
pub async fn create_pm_collect_db_entry(
state: &SessionState,
merchant_account: &domain::MerchantAccount,
pm_collect_link_data: &PaymentMethodCollectLinkData,
return_url: Option<String>,
) -> RouterResult<PaymentMethodCollectLink> {
let db: &dyn StorageInterface = &*state.store;
let link_data = serde_json::to_value(pm_collect_link_data)
.map_err(|_| report!(errors::ApiErrorResponse::InternalServerError))
.attach_printable("Failed to convert PaymentMethodCollectLinkData to Value")?;
let pm_collect_link = GenericLinkNew {
link_id: pm_collect_link_data.pm_collect_link_id.to_string(),
primary_reference: pm_collect_link_data
.customer_id
.get_string_repr()
.to_string(),
merchant_id: merchant_account.get_id().to_owned(),
link_type: common_enums::GenericLinkType::PaymentMethodCollect,
link_data,
url: pm_collect_link_data.link.clone(),
return_url,
expiry: common_utils::date_time::now()
+ Duration::seconds(pm_collect_link_data.session_expiry.into()),
..Default::default()
};
db.insert_pm_collect_link(pm_collect_link)
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "payment method collect link already exists".to_string(),
})
}
#[cfg(all(feature = "v2", feature = "customer_v2"))]
pub async fn render_pm_collect_link(
_state: SessionState,
_merchant_account: domain::MerchantAccount,
_key_store: domain::MerchantKeyStore,
_req: payment_methods::PaymentMethodCollectLinkRenderRequest,
) -> RouterResponse<services::GenericLinkFormData> {
todo!()
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
pub async fn render_pm_collect_link(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payment_methods::PaymentMethodCollectLinkRenderRequest,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
// Fetch pm collect link
let pm_collect_link = db
.find_pm_collect_link_by_link_id(&req.pm_collect_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment method collect link not found".to_string(),
})?;
// Check status and return form data accordingly
let has_expired = common_utils::date_time::now() > pm_collect_link.expiry;
let status = pm_collect_link.link_status;
let link_data = pm_collect_link.link_data;
let default_config = &state.conf.generic_link.payment_method_collect;
let default_ui_config = default_config.ui_config.clone();
let ui_config_data = common_utils::link_utils::GenericLinkUiConfigFormData {
merchant_name: link_data
.ui_config
.merchant_name
.unwrap_or(default_ui_config.merchant_name),
logo: link_data.ui_config.logo.unwrap_or(default_ui_config.logo),
theme: link_data
.ui_config
.theme
.clone()
.unwrap_or(default_ui_config.theme.clone()),
};
match status {
common_utils::link_utils::PaymentMethodCollectStatus::Initiated => {
// if expired, send back expired status page
if has_expired {
let expired_link_data = services::GenericExpiredLinkData {
title: "Payment collect link has expired".to_string(),
message: "This payment collect link has expired.".to_string(),
theme: link_data.ui_config.theme.unwrap_or(default_ui_config.theme),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::ExpiredLink(expired_link_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
// else, send back form link
} else {
let customer_id = id_type::CustomerId::try_from(Cow::from(
pm_collect_link.primary_reference.clone(),
))
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "customer_id",
})?;
// Fetch customer
let customer = db
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
&req.merchant_id,
&key_store,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Customer [{}] not found for link_id - {}",
pm_collect_link.primary_reference, pm_collect_link.link_id
),
})
.attach_printable(format!(
"customer [{}] not found",
pm_collect_link.primary_reference
))?;
let js_data = payment_methods::PaymentMethodCollectLinkDetails {
publishable_key: Secret::new(merchant_account.publishable_key),
client_secret: link_data.client_secret.clone(),
pm_collect_link_id: pm_collect_link.link_id,
customer_id: customer.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link.return_url,
ui_config: ui_config_data,
enabled_payment_methods: link_data.enabled_payment_methods,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize PaymentMethodCollectLinkDetails")?
);
let generic_form_data = services::GenericLinkFormData {
js_data: serialized_js_content,
css_data: serialized_css_content,
sdk_url: default_config.sdk_url.to_string(),
html_meta_tags: String::new(),
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollect(generic_form_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
// Send back status page
status => {
let js_data = payment_methods::PaymentMethodCollectLinkStatusDetails {
pm_collect_link_id: pm_collect_link.link_id,
customer_id: link_data.customer_id,
session_expiry: pm_collect_link.expiry,
return_url: pm_collect_link
.return_url
.as_ref()
.map(|url| url::Url::parse(url))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to parse return URL for payment method collect's status link",
)?,
ui_config: ui_config_data,
status,
};
let serialized_css_content = String::new();
let serialized_js_content = format!(
"window.__PM_COLLECT_DETAILS = {}",
js_data
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to serialize PaymentMethodCollectLinkStatusDetails"
)?
);
let generic_status_data = services::GenericLinkStatusData {
js_data: serialized_js_content,
css_data: serialized_css_content,
};
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data),
locale: DEFAULT_LOCALE.to_string(),
},
)))
}
}
}
fn generate_task_id_for_payment_method_status_update_workflow(
key_id: &str,
runner: storage::ProcessTrackerRunner,
task: &str,
) -> String {
format!("{runner}_{task}_{key_id}")
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
pub async fn add_payment_method_status_update_task(
db: &dyn StorageInterface,
payment_method: &domain::PaymentMethod,
prev_status: enums::PaymentMethodStatus,
curr_status: enums::PaymentMethodStatus,
merchant_id: &id_type::MerchantId,
) -> Result<(), errors::ProcessTrackerError> {
let created_at = payment_method.created_at;
let schedule_time =
created_at.saturating_add(Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
let tracking_data = storage::PaymentMethodStatusTrackingData {
payment_method_id: payment_method.get_id().clone(),
prev_status,
curr_status,
merchant_id: merchant_id.to_owned(),
};
let runner = storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow;
let task = PAYMENT_METHOD_STATUS_UPDATE_TASK;
let tag = [PAYMENT_METHOD_STATUS_TAG];
let process_tracker_id = generate_task_id_for_payment_method_status_update_workflow(
payment_method.get_id().as_str(),
runner,
task,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
process_tracker_id,
task,
runner,
tag,
tracking_data,
None,
schedule_time,
hyperswitch_domain_models::consts::API_VERSION,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct PAYMENT_METHOD_STATUS_UPDATE process tracker task")?;
db
.insert_process(process_tracker_entry)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while inserting PAYMENT_METHOD_STATUS_UPDATE reminder to process_tracker for payment_method_id: {}",
payment_method.get_id().clone()
)
})?;
Ok(())
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn retrieve_payment_method_with_token(
_state: &SessionState,
_merchant_key_store: &domain::MerchantKeyStore,
_token_data: &storage::PaymentTokenData,
_payment_intent: &PaymentIntent,
_card_token_data: Option<&domain::CardToken>,
_customer: &Option<domain::Customer>,
_storage_scheme: common_enums::enums::MerchantStorageScheme,
_mandate_id: Option<api_models::payments::MandateIds>,
_payment_method_info: Option<domain::PaymentMethod>,
_business_profile: &domain::Profile,
) -> RouterResult<storage::PaymentMethodDataWithId> {
todo!()
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_payment_method_with_token(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
card_token_data: Option<&domain::CardToken>,
customer: &Option<domain::Customer>,
storage_scheme: common_enums::enums::MerchantStorageScheme,
mandate_id: Option<api_models::payments::MandateIds>,
payment_method_info: Option<domain::PaymentMethod>,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
vault_data: Option<&VaultData>,
) -> RouterResult<storage::PaymentMethodDataWithId> {
let token = match token_data {
storage::PaymentTokenData::TemporaryGeneric(generic_token) => {
payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
payment_attempt,
merchant_key_store,
card_token_data,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::Temporary(generic_token) => {
payment_helpers::retrieve_payment_method_with_temporary_token(
state,
&generic_token.token,
payment_intent,
payment_attempt,
merchant_key_store,
card_token_data,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::Permanent(card_token) => {
payment_helpers::retrieve_payment_method_data_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token),
payment_intent,
card_token_data,
merchant_key_store,
storage_scheme,
mandate_id,
payment_method_info
.get_required_value("PaymentMethod")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("PaymentMethod not found")?,
business_profile,
payment_attempt.connector.clone(),
should_retry_with_pan,
vault_data,
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: Some(
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token)
.to_string(),
),
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::PermanentCard(card_token) => {
payment_helpers::retrieve_payment_method_data_with_permanent_token(
state,
card_token.locker_id.as_ref().unwrap_or(&card_token.token),
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token),
payment_intent,
card_token_data,
merchant_key_store,
storage_scheme,
mandate_id,
payment_method_info
.get_required_value("PaymentMethod")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("PaymentMethod not found")?,
business_profile,
payment_attempt.connector.clone(),
should_retry_with_pan,
vault_data,
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: Some(
card_token
.payment_method_id
.as_ref()
.unwrap_or(&card_token.token)
.to_string(),
),
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::AuthBankDebit(auth_token) => {
pm_auth::retrieve_payment_method_from_auth_service(
state,
merchant_key_store,
auth_token,
payment_intent,
customer,
)
.await?
.map(
|(payment_method_data, payment_method)| storage::PaymentMethodDataWithId {
payment_method_data: Some(payment_method_data),
payment_method: Some(payment_method),
payment_method_id: None,
},
)
.unwrap_or_default()
}
storage::PaymentTokenData::WalletToken(_) => storage::PaymentMethodDataWithId {
payment_method: None,
payment_method_data: None,
payment_method_id: None,
},
};
Ok(token)
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
pub(crate) fn get_payment_method_create_request(
payment_method_data: &api_models::payments::PaymentMethodData,
payment_method_type: storage_enums::PaymentMethod,
payment_method_subtype: Option<storage_enums::PaymentMethodType>,
customer_id: id_type::GlobalCustomerId,
billing_address: Option<&api_models::payments::Address>,
payment_method_session: Option<&domain::payment_methods::PaymentMethodSession>,
) -> RouterResult<payment_methods::PaymentMethodCreate> {
match payment_method_data {
api_models::payments::PaymentMethodData::Card(card) => {
let card_detail = payment_methods::CardDetail {
card_number: card.card_number.clone(),
card_exp_month: card.card_exp_month.clone(),
card_exp_year: card.card_exp_year.clone(),
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
card_issuing_country: card
.card_issuing_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten(),
card_network: card.card_network.clone(),
card_issuer: card.card_issuer.clone(),
card_type: card
.card_type
.as_ref()
.map(|c| payment_methods::CardType::from_str(c))
.transpose()
.ok()
.flatten(),
card_cvc: Some(card.card_cvc.clone()),
};
let payment_method_request = payment_methods::PaymentMethodCreate {
payment_method_type,
payment_method_subtype,
metadata: None,
customer_id: customer_id.clone(),
payment_method_data: payment_methods::PaymentMethodCreateData::Card(card_detail),
billing: billing_address.map(ToOwned::to_owned),
psp_tokenization: payment_method_session
.and_then(|pm_session| pm_session.psp_tokenization.clone()),
network_tokenization: payment_method_session
.and_then(|pm_session| pm_session.network_tokenization.clone()),
};
Ok(payment_method_request)
}
_ => Err(report!(errors::ApiErrorResponse::UnprocessableEntity {
message: "only card payment methods are supported for tokenization".to_string()
})
.attach_printable("Payment method data is incorrect")),
}
}
#[cfg(all(
any(feature = "v1", feature = "v2"),
not(feature = "payment_methods_v2")
))]
#[instrument(skip_all)]
pub(crate) async fn get_payment_method_create_request(
payment_method_data: Option<&domain::PaymentMethodData>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
customer_id: &Option<id_type::CustomerId>,
billing_name: Option<Secret<String>>,
payment_method_billing_address: Option<&hyperswitch_domain_models::address::Address>,
) -> RouterResult<payment_methods::PaymentMethodCreate> {
match payment_method_data {
Some(pm_data) => match payment_method {
Some(payment_method) => match pm_data {
domain::PaymentMethodData::Card(card) => {
let card_detail = payment_methods::CardDetail {
card_number: card.card_number.clone(),
card_exp_month: card.card_exp_month.clone(),
card_exp_year: card.card_exp_year.clone(),
card_holder_name: billing_name,
nick_name: card.nick_name.clone(),
card_issuing_country: card.card_issuing_country.clone(),
card_network: card.card_network.clone(),
card_issuer: card.card_issuer.clone(),
card_type: card.card_type.clone(),
};
let payment_method_request = payment_methods::PaymentMethodCreate {
payment_method: Some(payment_method),
payment_method_type,
payment_method_issuer: card.card_issuer.clone(),
payment_method_issuer_code: None,
#[cfg(feature = "payouts")]
bank_transfer: None,
#[cfg(feature = "payouts")]
wallet: None,
card: Some(card_detail),
metadata: None,
customer_id: customer_id.clone(),
card_network: card
.card_network
.as_ref()
.map(|card_network| card_network.to_string()),
client_secret: None,
payment_method_data: None,
//TODO: why are we using api model in router internally
billing: payment_method_billing_address.cloned().map(From::from),
connector_mandate_details: None,
network_transaction_id: None,
};
Ok(payment_method_request)
}
_ => {
let payment_method_request = payment_methods::PaymentMethodCreate {
payment_method: Some(payment_method),
payment_method_type,
payment_method_issuer: None,
payment_method_issuer_code: None,
#[cfg(feature = "payouts")]
bank_transfer: None,
#[cfg(feature = "payouts")]
wallet: None,
card: None,
metadata: None,
customer_id: customer_id.clone(),
card_network: None,
client_secret: None,
payment_method_data: None,
billing: None,
connector_mandate_details: None,
network_transaction_id: None,
};
Ok(payment_method_request)
}
},
None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_type"
})
.attach_printable("PaymentMethodType Required")),
},
None => Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data"
})
.attach_printable("PaymentMethodData required Or Card is already saved")),
}
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
pub async fn create_payment_method(
state: &SessionState,
request_state: &routes::app::ReqState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
profile: &domain::Profile,
) -> RouterResponse<api::PaymentMethodResponse> {
let response = create_payment_method_core(
state,
request_state,
req,
merchant_account,
key_store,
profile,
)
.await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(all(feature = "v2", feature = "payment_methods_v2"))]
#[instrument(skip_all)]
pub async fn create_payment_method_core(
state: &SessionState,
_request_state: &routes::app::ReqState,
req: api::PaymentMethodCreate,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
profile: &domain::Profile,
) -> RouterResult<api::PaymentMethodResponse> {
use common_utils::ext_traits::ValueExt;
req.validate()?;
let db = &*state.store;
let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.to_owned();
let key_manager_state = &(state).into();
db.find_customer_by_global_id(
key_manager_state,
&customer_id,
merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.attach_printable("Customer not found for the payment method")?;
let payment_method_billing_address = req
.billing
.clone()
.async_map(|billing| cards::create_encrypted_data(key_manager_state, key_store, billing))
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method billing address")?
.map(|encoded_address| {
encoded_address.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to parse Payment method billing address")?;
let payment_method_id =
id_type::GlobalPaymentMethodId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = create_payment_method_for_intent(
state,
req.metadata.clone(),
&customer_id,
payment_method_id,
merchant_id,
key_store,
merchant_account.storage_scheme,
payment_method_billing_address,
)
.await
.attach_printable("Failed to add Payment method to DB")?;
let payment_method_data = domain::PaymentMethodVaultingData::from(req.payment_method_data)
.populate_bin_details_for_payment_method(state)
.await;
let vaulting_result = vault_payment_method(
state,
&payment_method_data,
merchant_account,
key_store,
None,
&customer_id,
)
.await;
let network_tokenization_resp = network_tokenize_and_vault_the_pmd(
state,
&payment_method_data,
merchant_account,
key_store,
req.network_tokenization.clone(),
profile.is_network_tokenization_enabled,
&customer_id,
)
.await;
let (response, payment_method) = match vaulting_result {
Ok((vaulting_resp, fingerprint_id)) => {
let pm_update = create_pm_additional_data_update(
Some(&payment_method_data),
state,
key_store,
Some(vaulting_resp.vault_id.get_string_repr().clone()),
Some(fingerprint_id),
&payment_method,
None,
network_tokenization_resp,
Some(req.payment_method_type),
req.payment_method_subtype,
)
.await
.attach_printable("Unable to create Payment method data")?;
let payment_method = db
.update_payment_method(
&(state.into()),
key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
let resp = pm_transforms::generate_payment_method_response(&payment_method)?;
Ok((resp, payment_method))
}
Err(e) => {
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(