-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
payments.rs
5295 lines (4681 loc) · 199 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
use std::{
collections::{HashMap, HashSet},
fmt,
num::NonZeroI64,
};
use cards::CardNumber;
use common_utils::{
consts::default_payments_list_limit,
crypto,
ext_traits::{ConfigExt, Encode},
id_type,
pii::{self, Email},
types::MinorUnit,
};
use masking::{PeekInterface, Secret};
use router_derive::Setter;
use serde::{
de::{self, Unexpected, Visitor},
ser::Serializer,
Deserialize, Deserializer, Serialize,
};
use time::PrimitiveDateTime;
use url::Url;
use utoipa::ToSchema;
use crate::{
admin::{self, MerchantConnectorInfo},
disputes, enums as api_enums,
ephemeral_key::EphemeralKeyCreateResponse,
mandates::RecurringDetails,
refunds,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PaymentOp {
Create,
Update,
Confirm,
}
use crate::enums;
#[derive(serde::Deserialize)]
pub struct BankData {
pub payment_method_type: api_enums::PaymentMethodType,
pub code_information: Vec<BankCodeInformation>,
}
#[derive(serde::Deserialize)]
pub struct BankCodeInformation {
pub bank_name: common_enums::BankNames,
pub connector_codes: Vec<ConnectorCode>,
}
#[derive(serde::Deserialize)]
pub struct ConnectorCode {
pub connector: api_enums::Connector,
pub code: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)]
pub struct BankCodeResponse {
pub bank_name: Vec<common_enums::BankNames>,
pub eligible_connectors: Vec<String>,
}
#[derive(Debug, PartialEq)]
pub struct ClientSecret {
pub payment_id: String,
pub secret: String,
}
impl<'de> Deserialize<'de> for ClientSecret {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ClientSecretVisitor;
impl<'de> Visitor<'de> for ClientSecretVisitor {
type Value = ClientSecret;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a string in the format '{payment_id}_secret_{secret}'")
}
fn visit_str<E>(self, value: &str) -> Result<ClientSecret, E>
where
E: de::Error,
{
let (payment_id, secret) = value.rsplit_once("_secret_").ok_or_else(|| {
E::invalid_value(Unexpected::Str(value), &"a string with '_secret_'")
})?;
Ok(ClientSecret {
payment_id: payment_id.to_owned(),
secret: secret.to_owned(),
})
}
}
deserializer.deserialize_str(ClientSecretVisitor)
}
}
impl Serialize for ClientSecret {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let combined = format!("{}_secret_{}", self.payment_id, self.secret);
serializer.serialize_str(&combined)
}
}
#[cfg(test)]
mod client_secret_tests {
#![allow(clippy::expect_used)]
use serde_json;
use super::*;
#[test]
fn test_serialize_client_secret() {
let client_secret1 = ClientSecret {
payment_id: "pay_3TgelAms4RQec8xSStjF".to_string(),
secret: "fc34taHLw1ekPgNh92qr".to_string(),
};
let client_secret2 = ClientSecret {
payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF".to_string(),
secret: "fc34taHLw1ekPgNh92qr".to_string(),
};
let expected_str1 = r#""pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#;
let expected_str2 = r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#;
let actual_str1 =
serde_json::to_string(&client_secret1).expect("Failed to serialize client_secret1");
let actual_str2 =
serde_json::to_string(&client_secret2).expect("Failed to serialize client_secret2");
assert_eq!(expected_str1, actual_str1);
assert_eq!(expected_str2, actual_str2);
}
#[test]
fn test_deserialize_client_secret() {
let client_secret_str1 = r#""pay_3TgelAms4RQec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#;
let client_secret_str2 =
r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_fc34taHLw1ekPgNh92qr""#;
let client_secret_str3 =
r#""pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret__secret_fc34taHLw1ekPgNh92qr""#;
let expected1 = ClientSecret {
payment_id: "pay_3TgelAms4RQec8xSStjF".to_string(),
secret: "fc34taHLw1ekPgNh92qr".to_string(),
};
let expected2 = ClientSecret {
payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF".to_string(),
secret: "fc34taHLw1ekPgNh92qr".to_string(),
};
let expected3 = ClientSecret {
payment_id: "pay_3Tgel__Ams4RQ_secret_ec8xSStjF_secret_".to_string(),
secret: "fc34taHLw1ekPgNh92qr".to_string(),
};
let actual1: ClientSecret = serde_json::from_str(client_secret_str1)
.expect("Failed to deserialize client_secret_str1");
let actual2: ClientSecret = serde_json::from_str(client_secret_str2)
.expect("Failed to deserialize client_secret_str2");
let actual3: ClientSecret = serde_json::from_str(client_secret_str3)
.expect("Failed to deserialize client_secret_str3");
assert_eq!(expected1, actual1);
assert_eq!(expected2, actual2);
assert_eq!(expected3, actual3);
}
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)]
pub struct CustomerDetails {
/// The identifier for the customer.
#[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub id: id_type::CustomerId,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "John Doe")]
pub name: Option<Secret<String>>,
/// The customer's email address
#[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
pub email: Option<Email>,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 10, example = "3141592653")]
pub phone: Option<Secret<String>>,
/// The country code for the customer's phone number
#[schema(max_length = 2, example = "+1")]
pub phone_country_code: Option<String>,
}
#[derive(Debug, serde::Serialize, Clone, ToSchema, PartialEq)]
pub struct CustomerDetailsResponse {
/// The identifier for the customer.
#[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub id: id_type::CustomerId,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "John Doe")]
pub name: Option<Secret<String>>,
/// The customer's email address
#[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")]
pub email: Option<Email>,
/// The customer's phone number
#[schema(value_type = Option<String>, max_length = 10, example = "3141592653")]
pub phone: Option<Secret<String>>,
/// The country code for the customer's phone number
#[schema(max_length = 2, example = "+1")]
pub phone_country_code: Option<String>,
}
#[derive(
Default,
Debug,
serde::Deserialize,
serde::Serialize,
Clone,
ToSchema,
router_derive::PolymorphicSchema,
)]
#[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)]
#[serde(deny_unknown_fields)]
pub struct PaymentsRequest {
/// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and ¥100 since ¥ is a zero-decimal currency
#[schema(value_type = Option<u64>, example = 6540)]
#[serde(default, deserialize_with = "amount::deserialize_option")]
#[mandatory_in(PaymentsCreateRequest = u64)]
// Makes the field mandatory in PaymentsCreateRequest
pub amount: Option<Amount>,
/// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars
#[schema(example = "USD", value_type = Option<Currency>)]
#[mandatory_in(PaymentsCreateRequest = Currency)]
pub currency: Option<api_enums::Currency>,
/// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount.
#[schema(value_type = Option<i64>, example = 6540)]
pub amount_to_capture: Option<MinorUnit>,
/// Unique identifier for the payment. This ensures idempotency for multiple payments
/// that have been done by a single merchant. This field is auto generated and is returned in the API response.
#[schema(
value_type = Option<String>,
min_length = 30,
max_length = 30,
example = "pay_mbabizu24mvu3mela5njyhpit4"
)]
#[serde(default, deserialize_with = "payment_id_type::deserialize_option")]
pub payment_id: Option<PaymentIdType>,
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
#[schema(max_length = 255, example = "merchant_1668273825")]
pub merchant_id: Option<String>,
#[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({
"type": "single",
"data": {"connector": "stripe", "merchant_connector_id": "mca_123"}
}))]
pub routing: Option<serde_json::Value>,
/// This allows to manually select a connector with which the payment can go through
#[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))]
pub connector: Option<Vec<api_enums::Connector>>,
/// Default value if not passed is set to 'automatic' which results in Auth and Capture in one single API request. Pass 'manual' or 'manual_multiple' in case you want do a separate Auth and Capture by first authorizing and placing a hold on your customer's funds so that you can use the Payments/Capture endpoint later to capture the authorized amount. Pass 'manual' if you want to only capture the amount later once or 'manual_multiple' if you want to capture the funds multiple times later. Both 'manual' and 'manual_multiple' are only supported by a specific list of processors
#[schema(value_type = Option<CaptureMethod>, example = "automatic")]
pub capture_method: Option<api_enums::CaptureMethod>,
/// Pass this parameter to force 3DS or non 3DS auth for this payment. Some connectors will still force 3DS auth even in case of passing 'no_three_ds' here and vice versa. Default value is 'no_three_ds' if not set
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")]
pub authentication_type: Option<api_enums::AuthenticationType>,
/// The billing details of the payment. This address will be used for invoicing.
pub billing: Option<Address>,
/// A timestamp (ISO 8601 code) that determines when the payment should be captured.
/// Providing this field will automatically set `capture` to true
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
/// Whether to confirm the payment (if applicable)
#[schema(default = false, example = true)]
pub confirm: Option<bool>,
/// Passing this object creates a new customer or attaches an existing customer to the payment
pub customer: Option<CustomerDetails>,
/// The identifier for the customer
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
pub customer_id: Option<id_type::CustomerId>,
/// The customer's email address.
/// This field will be deprecated soon, use the customer object instead
#[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub email: Option<Email>,
/// The customer's name.
/// This field will be deprecated soon, use the customer object instead.
#[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub name: Option<Secret<String>>,
/// The customer's phone number
/// This field will be deprecated soon, use the customer object instead
#[schema(value_type = Option<String>, max_length = 255, example = "3141592653", deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub phone: Option<Secret<String>>,
/// The country code for the customer phone number
/// This field will be deprecated soon, use the customer object instead
#[schema(max_length = 255, example = "+1", deprecated)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
pub phone_country_code: Option<String>,
/// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory
#[schema(example = true)]
pub off_session: Option<bool>,
/// A description for the payment
#[schema(example = "It's my first payment request")]
pub description: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, example = "https://hyperswitch.io")]
pub return_url: Option<Url>,
/// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.
#[schema(value_type = Option<FutureUsage>, example = "off_session")]
pub setup_future_usage: Option<api_enums::FutureUsage>,
/// The payment method information provided for making a payment
#[schema(example = "bank_transfer")]
#[serde(with = "payment_method_data_serde", default)]
pub payment_method_data: Option<PaymentMethodDataRequest>,
/// The payment method that is to be used
#[schema(value_type = Option<PaymentMethod>, example = "card")]
pub payment_method: Option<api_enums::PaymentMethod>,
/// Provide a reference to a stored payment method
#[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")]
pub payment_token: Option<String>,
/// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead
#[schema(value_type = Option<String>, deprecated)]
pub card_cvc: Option<Secret<String>>,
/// The shipping address for the payment
pub shipping: Option<Address>,
/// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.
#[schema(max_length = 255, example = "Hyperswitch Router")]
pub statement_descriptor_name: Option<String>,
/// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.
#[schema(max_length = 255, example = "Payment for shoes purchase")]
pub statement_descriptor_suffix: Option<String>,
/// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount
#[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{
"product_name": "Apple iPhone 16",
"quantity": 1,
"amount" : 69000
"product_img_link" : "https://dummy-img-link.com"
}]"#)]
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
/// It's a token used for client side verification.
#[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)]
pub client_secret: Option<String>,
/// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server.
pub mandate_data: Option<MandateData>,
/// Passing this object during payments confirm . The customer_acceptance sub object is usually passed by the SDK or client
#[schema(value_type = Option<CustomerAcceptance>)]
pub customer_acceptance: Option<CustomerAcceptance>,
/// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data
#[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")]
#[remove_in(PaymentsUpdateRequest)]
pub mandate_id: Option<String>,
/// Additional details required by 3DS 2.0
#[schema(value_type = Option<BrowserInformation>, example = r#"{
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
"accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": true,
"java_script_enabled":true
}"#)]
pub browser_info: Option<serde_json::Value>,
/// To indicate the type of payment experience that the payment method would go through
#[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")]
pub payment_experience: Option<api_enums::PaymentExperience>,
/// Payment Method Type
#[schema(value_type = Option<PaymentMethodType>, example = "google_pay")]
pub payment_method_type: Option<api_enums::PaymentMethodType>,
/// Business country of the merchant for this payment.
/// To be deprecated soon. Pass the profile_id instead
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
#[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)]
pub business_country: Option<api_enums::CountryAlpha2>,
/// Business label of the merchant for this payment.
/// To be deprecated soon. Pass the profile_id instead
#[schema(example = "food")]
#[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)]
pub business_label: Option<String>,
/// Merchant connector details used to make payments.
#[schema(value_type = Option<MerchantConnectorDetailsWrap>)]
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
/// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent
#[schema(value_type = Option<Vec<PaymentMethodType>>)]
pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>,
/// Business sub label for the payment
#[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)]
pub business_sub_label: Option<String>,
/// Denotes the retry action
#[schema(value_type = Option<RetryAction>)]
pub retry_action: Option<api_enums::RetryAction>,
/// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// additional data related to some connectors
pub connector_metadata: Option<ConnectorMetadata>,
/// additional data that might be required by hyperswitch
pub feature_metadata: Option<FeatureMetadata>,
/// Whether to get the payment link (if applicable)
#[schema(default = false, example = true)]
pub payment_link: Option<bool>,
/// custom payment link config for the particular payment
#[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)]
pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>,
/// The business profile to use for this payment, if not passed the default business profile
/// associated with the merchant account will be used.
#[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)]
pub profile_id: Option<String>,
/// surcharge_details for this payment
#[remove_in(PaymentsConfirmRequest)]
#[schema(value_type = Option<RequestSurchargeDetails>)]
pub surcharge_details: Option<RequestSurchargeDetails>,
/// The type of the payment that differentiates between normal and various types of mandate payments
#[schema(value_type = Option<PaymentType>)]
pub payment_type: Option<api_enums::PaymentType>,
///Request for an incremental authorization
pub request_incremental_authorization: Option<bool>,
///Will be used to expire client secret after certain amount of time to be supplied in seconds
///(900) for 15 mins
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// additional data related to some frm connectors
#[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)]
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// Whether to perform external authentication (if applicable)
#[schema(example = true)]
pub request_external_three_ds_authentication: Option<bool>,
/// Details required for recurring payment
pub recurring_details: Option<RecurringDetails>,
/// Fee information to be charged on the payment being collected
pub charges: Option<PaymentChargeRequest>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub struct PaymentChargeRequest {
/// Stripe's charge type
#[schema(value_type = PaymentChargeType, example = "direct")]
pub charge_type: api_enums::PaymentChargeType,
/// Platform fees to be collected on the payment
pub fees: i64,
/// Identifier for the reseller's account to send the funds to
pub transfer_account_id: String,
}
impl PaymentsRequest {
pub fn get_total_capturable_amount(&self) -> Option<MinorUnit> {
let surcharge_amount = self
.surcharge_details
.map(|surcharge_details| surcharge_details.get_total_surcharge_amount())
.unwrap_or_default();
self.amount
.map(|amount| MinorUnit::from(amount) + surcharge_amount)
}
}
#[derive(
Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq,
)]
pub struct RequestSurchargeDetails {
#[schema(value_type = i64, example = 6540)]
pub surcharge_amount: MinorUnit,
pub tax_amount: Option<MinorUnit>,
}
/// Browser information to be used for 3DS 2.0
#[derive(ToSchema)]
pub struct BrowserInformation {
/// Color depth supported by the browser
pub color_depth: Option<u8>,
/// Whether java is enabled in the browser
pub java_enabled: Option<bool>,
/// Whether javascript is enabled in the browser
pub java_script_enabled: Option<bool>,
/// Language supported
pub language: Option<String>,
/// The screen height in pixels
pub screen_height: Option<u32>,
/// The screen width in pixels
pub screen_width: Option<u32>,
/// Time zone of the client
pub time_zone: Option<i32>,
/// Ip address of the client
#[schema(value_type = Option<String>)]
pub ip_address: Option<std::net::IpAddr>,
/// List of headers that are accepted
#[schema(
example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
)]
pub accept_header: Option<String>,
/// User-agent of the browser
pub user_agent: Option<String>,
}
impl RequestSurchargeDetails {
pub fn is_surcharge_zero(&self) -> bool {
self.surcharge_amount == MinorUnit::new(0)
&& self.tax_amount.unwrap_or_default() == MinorUnit::new(0)
}
pub fn get_total_surcharge_amount(&self) -> MinorUnit {
self.surcharge_amount + self.tax_amount.unwrap_or_default()
}
}
#[derive(Default, Debug, Clone)]
pub struct HeaderPayload {
pub payment_confirm_source: Option<api_enums::PaymentSource>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub x_hs_latency: Option<bool>,
}
impl HeaderPayload {
pub fn with_source(payment_confirm_source: api_enums::PaymentSource) -> Self {
Self {
payment_confirm_source: Some(payment_confirm_source),
..Default::default()
}
}
}
#[derive(
Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema,
)]
pub struct PaymentAttemptResponse {
/// Unique identifier for the attempt
pub attempt_id: String,
/// The status of the attempt
#[schema(value_type = AttemptStatus, example = "charged")]
pub status: enums::AttemptStatus,
/// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
#[schema(value_type = i64, example = 6540)]
pub amount: MinorUnit,
/// The currency of the amount of the payment attempt
#[schema(value_type = Option<Currency>, example = "USD")]
pub currency: Option<enums::Currency>,
/// The connector used for the payment
pub connector: Option<String>,
/// If there was an error while calling the connector the error message is received here
pub error_message: Option<String>,
/// The payment method that is to be used
#[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")]
pub payment_method: Option<enums::PaymentMethod>,
/// A unique identifier for a payment provided by the connector
pub connector_transaction_id: Option<String>,
/// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method.
#[schema(value_type = Option<CaptureMethod>, example = "scheduled")]
pub capture_method: Option<enums::CaptureMethod>,
/// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS
#[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")]
pub authentication_type: Option<enums::AuthenticationType>,
/// If the payment was cancelled the reason provided here
pub cancellation_reason: Option<String>,
/// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data
pub mandate_id: Option<String>,
/// If there was an error while calling the connectors the code is received here
pub error_code: Option<String>,
/// Provide a reference to a stored payment method
pub payment_token: Option<String>,
/// additional data related to some connectors
pub connector_metadata: Option<serde_json::Value>,
/// Payment Experience for the current payment
#[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")]
pub payment_experience: Option<enums::PaymentExperience>,
/// Payment Method Type
#[schema(value_type = Option<PaymentMethodType>, example = "google_pay")]
pub payment_method_type: Option<enums::PaymentMethodType>,
/// reference to the payment at connector side
#[schema(value_type = Option<String>, example = "993672945374576J")]
pub reference_id: Option<String>,
/// error code unified across the connectors is received here if there was an error while calling connector
pub unified_code: Option<String>,
/// error message unified across the connectors is received here if there was an error while calling connector
pub unified_message: Option<String>,
/// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client
pub client_source: Option<String>,
/// Value passed in X-CLIENT-VERSION header during payments confirm request by the client
pub client_version: Option<String>,
}
#[derive(
Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema,
)]
pub struct CaptureResponse {
/// unique identifier for the capture
pub capture_id: String,
/// The status of the capture
#[schema(value_type = CaptureStatus, example = "charged")]
pub status: enums::CaptureStatus,
/// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
#[schema(value_type = i64, example = 6540)]
pub amount: MinorUnit,
/// The currency of the amount of the capture
#[schema(value_type = Option<Currency>, example = "USD")]
pub currency: Option<enums::Currency>,
/// The connector used for the payment
pub connector: String,
/// unique identifier for the parent attempt on which this capture is made
pub authorized_attempt_id: String,
/// A unique identifier for a capture provided by the connector
pub connector_capture_id: Option<String>,
/// sequence number of this capture
pub capture_sequence: i16,
/// If there was an error while calling the connector the error message is received here
pub error_message: Option<String>,
/// If there was an error while calling the connectors the code is received here
pub error_code: Option<String>,
/// If there was an error while calling the connectors the reason is received here
pub error_reason: Option<String>,
/// reference to the capture at connector side
pub reference_id: Option<String>,
}
impl PaymentsRequest {
pub fn get_feature_metadata_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<serde_json::Value>,
common_utils::errors::ParsingError,
> {
self.feature_metadata
.as_ref()
.map(Encode::encode_to_value)
.transpose()
}
pub fn get_connector_metadata_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<serde_json::Value>,
common_utils::errors::ParsingError,
> {
self.connector_metadata
.as_ref()
.map(Encode::encode_to_value)
.transpose()
}
pub fn get_allowed_payment_method_types_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<serde_json::Value>,
common_utils::errors::ParsingError,
> {
self.allowed_payment_method_types
.as_ref()
.map(Encode::encode_to_value)
.transpose()
}
pub fn get_order_details_as_value(
&self,
) -> common_utils::errors::CustomResult<
Option<Vec<pii::SecretSerdeValue>>,
common_utils::errors::ParsingError,
> {
self.order_details
.as_ref()
.map(|od| {
od.iter()
.map(|order| order.encode_to_value().map(Secret::new))
.collect::<Result<Vec<_>, _>>()
})
.transpose()
}
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)]
pub enum Amount {
Value(NonZeroI64),
#[default]
Zero,
}
impl From<Amount> for MinorUnit {
fn from(amount: Amount) -> Self {
match amount {
Amount::Value(val) => Self::new(val.get()),
Amount::Zero => Self::new(0),
}
}
}
impl From<MinorUnit> for Amount {
fn from(minor_unit: MinorUnit) -> Self {
match minor_unit.get_amount_as_i64() {
0 => Self::Zero,
val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value),
}
}
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct PaymentsRedirectRequest {
pub payment_id: String,
pub merchant_id: String,
pub connector: String,
pub param: String,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct VerifyRequest {
// The merchant_id is generated through api key
// and is later passed in the struct
pub merchant_id: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub email: Option<Email>,
pub name: Option<Secret<String>>,
pub phone: Option<Secret<String>>,
pub phone_country_code: Option<String>,
pub payment_method: Option<api_enums::PaymentMethod>,
pub payment_method_data: Option<PaymentMethodData>,
pub payment_token: Option<String>,
pub mandate_data: Option<MandateData>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MandateTransactionType {
NewMandateTransaction,
RecurringMandateTransaction,
}
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct MandateIds {
pub mandate_id: Option<String>,
pub mandate_reference_id: Option<MandateReferenceId>,
}
#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
pub enum MandateReferenceId {
ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector
NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)]
pub struct ConnectorMandateReferenceId {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
pub update_history: Option<Vec<UpdateHistory>>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct UpdateHistory {
pub connector_mandate_id: Option<String>,
pub payment_method_id: String,
pub original_payment_id: Option<String>,
}
impl MandateIds {
pub fn new(mandate_id: String) -> Self {
Self {
mandate_id: Some(mandate_id),
mandate_reference_id: None,
}
}
}
// The fields on this struct are optional, as we want to allow the merchant to provide partial
// information about creating mandates
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct MandateData {
/// A way to update the mandate's payment method details
pub update_mandate_id: Option<String>,
/// A concent from the customer to store the payment method
pub customer_acceptance: Option<CustomerAcceptance>,
/// A way to select the type of mandate used
pub mandate_type: Option<MandateType>,
}
#[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct SingleUseMandate {
pub amount: MinorUnit,
pub currency: api_enums::Currency,
}
#[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)]
pub struct MandateAmountData {
/// The maximum amount to be debited for the mandate transaction
#[schema(value_type = i64, example = 6540)]
pub amount: MinorUnit,
/// The currency for the transaction
#[schema(value_type = Currency, example = "USD")]
pub currency: api_enums::Currency,
/// Specifying start date of the mandate
#[schema(example = "2022-09-10T00:00:00Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub start_date: Option<PrimitiveDateTime>,
/// Specifying end date of the mandate
#[schema(example = "2023-09-10T23:59:59Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub end_date: Option<PrimitiveDateTime>,
/// Additional details required by mandate
#[schema(value_type = Option<Object>, example = r#"{
"frequency": "DAILY"
}"#)]
pub metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum MandateType {
/// If the mandate should only be valid for 1 off-session use
SingleUse(MandateAmountData),
/// If the mandate should be valid for multiple debits
MultiUse(Option<MandateAmountData>),
}
impl Default for MandateType {
fn default() -> Self {
Self::MultiUse(None)
}
}
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CustomerAcceptance {
/// Type of acceptance provided by the
#[schema(example = "online")]
pub acceptance_type: AcceptanceType,
/// Specifying when the customer acceptance was provided
#[schema(example = "2022-09-10T10:11:12Z")]
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub accepted_at: Option<PrimitiveDateTime>,
/// Information required for online mandate generation
pub online: Option<OnlineMandate>,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)]
#[serde(rename_all = "lowercase")]
/// This is used to indicate if the mandate was accepted online or offline
pub enum AcceptanceType {
Online,
#[default]
Offline,
}
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct OnlineMandate {
/// Ip address of the customer machine from which the mandate was created
#[schema(value_type = String, example = "123.32.25.123")]
pub ip_address: Option<Secret<String, pii::IpAddress>>,
/// The user-agent of the customer's browser
pub user_agent: String,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct Card {
/// The card number
#[schema(value_type = String, example = "4242424242424242")]
pub card_number: CardNumber,
/// The card's expiry month
#[schema(value_type = String, example = "24")]
pub card_exp_month: Secret<String>,
/// The card's expiry year
#[schema(value_type = String, example = "24")]
pub card_exp_year: Secret<String>,
/// The card holder's name
#[schema(value_type = String, example = "John Test")]
pub card_holder_name: Option<Secret<String>>,
/// The CVC number for the card
#[schema(value_type = String, example = "242")]
pub card_cvc: Secret<String>,
/// The name of the issuer of card
#[schema(example = "chase")]
pub card_issuer: Option<String>,
/// The card network for the card
#[schema(value_type = Option<CardNetwork>, example = "Visa")]
pub card_network: Option<api_enums::CardNetwork>,
#[schema(example = "CREDIT")]
pub card_type: Option<String>,
#[schema(example = "INDIA")]
pub card_issuing_country: Option<String>,
#[schema(example = "JP_AMEX")]
pub bank_code: Option<String>,
/// The card holder's nick name
#[schema(value_type = Option<String>, example = "John Test")]
pub nick_name: Option<Secret<String>>,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ExtendedCardInfo {
/// The card number
#[schema(value_type = String, example = "4242424242424242")]
pub card_number: CardNumber,
/// The card's expiry month
#[schema(value_type = String, example = "24")]
pub card_exp_month: Secret<String>,
/// The card's expiry year
#[schema(value_type = String, example = "24")]
pub card_exp_year: Secret<String>,
/// The card holder's name
#[schema(value_type = String, example = "John Test")]
pub card_holder_name: Option<Secret<String>>,
/// The CVC number for the card
#[schema(value_type = String, example = "242")]
pub card_cvc: Secret<String>,