delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
//! The payment intent model.

use std::fmt;

use serde::Deserialize;
use serde_json::Value;

use crate::core::models::common::{
    AttemptStatus, Currency, ExternalRecordMarker, IntentStatus, PaymentMethod, PaymentMethodType,
    ProcessorCostEstimateBasis,
};
use crate::core::models::payment_detail::{BuyerRiskEvaluation, PaymentProductLine};

/// A payment intent as returned by the API.
///
/// Unmodeled fields are preserved in [`extra`](PaymentResponse::extra) so new
/// API fields never break deserialization.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentResponse {
    /// Unique payment intent ID.
    pub payment_id: String,
    /// Merchant account ID that owns this payment.
    pub merchant_id: String,
    /// Current lifecycle status.
    pub status: IntentStatus,
    /// Authorized amount in minor units.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,

    /// Net amount after discounts and tax, in minor units.
    #[serde(default)]
    pub net_amount: Option<i64>,
    /// Amount still available to capture, in minor units.
    #[serde(default)]
    pub amount_capturable: Option<i64>,
    /// Actual captured amount, in minor units (present after capture).
    #[serde(default)]
    pub amount_received: Option<i64>,
    /// Client secret for client-side confirmation. Do not log or share it:
    /// it authorises completing this payment. Redacted in `Debug`.
    #[serde(default)]
    pub client_secret: Option<String>,
    /// Connector used to process this payment.
    #[serde(default)]
    pub connector: Option<String>,
    /// Associated customer ID.
    #[serde(default)]
    pub customer_id: Option<String>,
    /// Shop (business profile) ID.
    #[serde(default)]
    pub profile_id: Option<String>,
    /// Payment method family used.
    #[serde(default)]
    pub payment_method: Option<PaymentMethod>,
    /// Gateway error code, if the payment failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, if the payment failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Instructions for additional customer action (3DS redirect, etc.).
    #[serde(default)]
    pub next_action: Option<Value>,
    /// ISO 8601 creation timestamp.
    #[serde(default)]
    pub created: Option<String>,
    /// When the payment (its client secret / hosted checkout link) expires —
    /// the backend's *resolved* `session_expiry`, which may differ from the
    /// requested one if it was omitted or clamped. RFC 3339. Absent on
    /// backends predating the field; `null` when no expiry applies.
    #[serde(default)]
    pub expires_on: Option<String>,
    /// Arbitrary metadata.
    #[serde(default)]
    pub metadata: Option<Value>,
    /// Which environment this payment ran in. Echoes the `test_mode` sent at
    /// create; filled in from the processor's own setting when none was sent,
    /// and `None` for a payment that never reached a processor. `None` counts
    /// as live wherever it is filtered on.
    #[serde(default)]
    pub test_mode: Option<bool>,
    /// The connector's own identifier for the payment on the rail, when one
    /// has been assigned. Published on list rows and on retrieve so an
    /// operator can copy it into the processor's dashboard.
    #[serde(default)]
    pub connector_transaction_id: Option<String>,
    /// What the rail says about settling the active attempt — see
    /// [`ConnectorSettlementStatus`]. Present on list rows and on retrieve;
    /// absent on create, confirm and update, and for a profile-scoped viewer,
    /// who is not shown the state at all. `None` is "not reported here",
    /// never "nothing to settle".
    #[serde(default)]
    pub connector_settlement_status: Option<ConnectorSettlementStatus>,
    /// The category of the routing decision that placed the latest attempt —
    /// see [`RoutingApproach`]. The category, never the rule that fired.
    #[serde(default)]
    pub routing_approach: Option<RoutingApproach>,
    /// The latest buyer risk evaluation of the payment, when it was scored.
    #[serde(default)]
    pub buyer_risk: Option<BuyerRiskEvaluation>,
    /// Whether the payment is marked as an integration test, which keeps it
    /// out of analytics. `false` from an older API.
    #[serde(default)]
    pub is_integration_test: bool,
    /// Why the payment failed or was declined, in one of a fixed set of
    /// words. Set exactly when the status is `failed` or `declined`; a word
    /// this crate does not know arrives verbatim.
    #[serde(default)]
    pub failure_substatus: Option<FailureSubstatus>,
    /// How the active attempt's card reached the processor.
    #[serde(default)]
    pub vault: Option<AttemptVaultUsage>,
    /// Why the payment failed, in words safe to show the buyer, e.g.
    /// `"insufficient_funds"` or `"try_again_later"`.
    #[serde(default)]
    pub buyer_failure_reason: Option<String>,
    /// On the create answer only: whether the buyer is blocked by the
    /// merchant's buyer blocklist.
    #[serde(default)]
    pub buyer_blocked: Option<bool>,
    /// On the create answer only: the merchant's note on the block.
    #[serde(default)]
    pub buyer_block_note: Option<String>,
    /// The processor's reference for the payment, as its dashboard shows it.
    #[serde(default)]
    pub processor_reference: Option<String>,
    /// The processor environment the payment ran in: `"sandbox"`, `"live"`
    /// or `"unknown"`.
    #[serde(default)]
    pub connector_environment: Option<String>,
    /// The payment's first product line and line count, for list rows.
    #[serde(default)]
    pub product_summary: Option<PaymentProductLineSummary>,
    /// URL the buyer may use to leave an unpaid hosted checkout.
    #[serde(default)]
    pub cancel_url: Option<String>,
    /// State recorded on the payment beyond its status.
    #[serde(default)]
    pub state_metadata: Option<PaymentIntentStateMetadata>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Why a payment failed or was declined, e.g. `"insufficient_funds"`. A
/// substatus this crate does not know reads as `declined_other` /
/// `failed_other` on the API side; here it arrives verbatim.
pub type FailureSubstatus = String;

/// How a payment attempt's card reached the processor: through a card vault,
/// directly, or not recorded.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct AttemptVaultUsage {
    /// `"vault"`, `"direct"` or `"not_recorded"`.
    pub status: String,
    /// Why the card went direct, e.g. `"no_vault"` or `"vault_switched_off"`.
    #[serde(default)]
    pub direct_reason: Option<String>,
    /// The vault's connector account. `None` for a caller who may not see
    /// that account.
    #[serde(default)]
    pub vault_connector_id: Option<String>,
    /// The vault account's name as it was when the payment ran.
    #[serde(default)]
    pub vault_connector_label: Option<String>,
    /// The vault provider.
    #[serde(default)]
    pub vault_connector: Option<String>,
    /// Whether the vault passed the card on: `"handed_over"` or `"failed"`.
    #[serde(default)]
    pub handover: Option<String>,
    /// What the vault answered when the hand-over failed.
    #[serde(default)]
    pub handover_error: Option<String>,
    /// ISO 8601 time the answer was recorded.
    #[serde(default)]
    pub recorded_at: Option<String>,
    /// ISO 8601 time recording began. Only on `not_recorded`.
    #[serde(default)]
    pub recorded_since: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// A payment's first product line and how many it has, for list rows.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentProductLineSummary {
    /// The first line.
    #[serde(default)]
    pub first_line: Option<PaymentProductLine>,
    /// How many lines the payment has.
    pub line_count: i32,
    /// `true` when the payment has at least one line and every line is
    /// attributed.
    pub attributed: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// State recorded on a payment beyond its status. Only the post-capture void
/// is modeled; the rest arrives in [`extra`](Self::extra).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentIntentStateMetadata {
    /// The post-capture void of the payment, when one was asked for.
    #[serde(default)]
    pub post_capture_void: Option<PostCaptureVoidResponse>,
    /// Any additional fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The state of a post-capture void.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PostCaptureVoidResponse {
    /// `"succeeded"`, `"pending"` or `"failed"`.
    #[serde(default)]
    pub status: Option<String>,
    /// The connector's reference for the void.
    #[serde(default)]
    pub connector_reference_id: Option<String>,
    /// A description of the void.
    #[serde(default)]
    pub description: Option<String>,
    /// ISO 8601 time the void was last updated.
    pub updated_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived: `client_secret` authorises client-side
// confirmation of this payment, so anything holding it can complete the
// charge. A `{:?}` on a payment is the most likely way it reaches a log, and
// payments are logged constantly. The field's presence is still visible --
// `Some("[redacted]")` vs `None` -- because whether a secret was issued is
// often what you are debugging.
//
// Only the *modeled* secret is covered: `extra` is printed in full, so a
// secret the API starts returning under an unmodeled key would still show up
// here until it is modeled.
impl fmt::Debug for PaymentResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PaymentResponse")
            .field("payment_id", &self.payment_id)
            .field("merchant_id", &self.merchant_id)
            .field("status", &self.status)
            .field("amount", &self.amount)
            .field("currency", &self.currency)
            .field("net_amount", &self.net_amount)
            .field("amount_capturable", &self.amount_capturable)
            .field("amount_received", &self.amount_received)
            .field(
                "client_secret",
                &self.client_secret.as_ref().map(|_| "[redacted]"),
            )
            .field("connector", &self.connector)
            .field("customer_id", &self.customer_id)
            .field("profile_id", &self.profile_id)
            .field("payment_method", &self.payment_method)
            .field("error_code", &self.error_code)
            .field("error_message", &self.error_message)
            .field("next_action", &self.next_action)
            .field("created", &self.created)
            .field("expires_on", &self.expires_on)
            .field("metadata", &self.metadata)
            .field("connector_transaction_id", &self.connector_transaction_id)
            .field(
                "connector_settlement_status",
                &self.connector_settlement_status,
            )
            .field("routing_approach", &self.routing_approach)
            .field("buyer_risk", &self.buyer_risk)
            .field("is_integration_test", &self.is_integration_test)
            .field("failure_substatus", &self.failure_substatus)
            .field("vault", &self.vault)
            .field("buyer_failure_reason", &self.buyer_failure_reason)
            .field("buyer_blocked", &self.buyer_blocked)
            .field("buyer_block_note", &self.buyer_block_note)
            .field("processor_reference", &self.processor_reference)
            .field("connector_environment", &self.connector_environment)
            .field("product_summary", &self.product_summary)
            .field("cancel_url", &self.cancel_url)
            .field("state_metadata", &self.state_metadata)
            .field("extra", &self.extra)
            .finish()
    }
}

/// A single attempt made on a payment, with its full failure detail. Returned
/// in the `data` array of `Payments::list_attempts` — useful for surfacing
/// retries across connectors (e.g. "attempt 1 stripe → insufficient_funds,
/// attempt 2 adyen → success").
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentAttemptResponse {
    /// Unique identifier for this attempt.
    pub attempt_id: String,
    /// Status of this attempt (distinct from the parent intent's status).
    pub status: AttemptStatus,

    /// Attempt amount in minor units.
    #[serde(default)]
    pub amount: Option<i64>,
    /// Three-letter ISO 4217 currency code.
    #[serde(default)]
    pub currency: Option<Currency>,
    /// Connector (gateway) this attempt was routed to, e.g. `"stripe"`.
    #[serde(default)]
    pub connector: Option<String>,
    /// Connector's transaction identifier for this attempt.
    #[serde(default)]
    pub connector_transaction_id: Option<String>,
    /// Payment method family used for this attempt.
    #[serde(default)]
    pub payment_method: Option<PaymentMethod>,
    /// Payment method sub-type used for this attempt.
    #[serde(default)]
    pub payment_method_type: Option<PaymentMethodType>,
    /// Raw connector error code, when the attempt failed.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message, when the attempt failed.
    #[serde(default)]
    pub error_message: Option<String>,
    /// Delopay-unified decline code (from the gateway status map).
    #[serde(default)]
    pub unified_code: Option<String>,
    /// Delopay-unified, human-readable decline message.
    #[serde(default)]
    pub unified_message: Option<String>,
    /// When the attempt was created (RFC 3339).
    #[serde(default)]
    pub created_at: Option<String>,
    /// When the attempt was last modified (RFC 3339).
    #[serde(default)]
    pub modified_at: Option<String>,
    /// The connector account this attempt ran on, when one was chosen.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// The category of the routing decision that placed this attempt — see
    /// [`RoutingApproach`].
    #[serde(default)]
    pub routing_approach: Option<RoutingApproach>,
    /// Why the attempt failed or was declined, in one of a fixed set of
    /// words.
    #[serde(default)]
    pub failure_substatus: Option<FailureSubstatus>,
    /// How the attempt's card reached the processor.
    #[serde(default)]
    pub vault: Option<AttemptVaultUsage>,
    /// The processor's reference for the attempt.
    #[serde(default)]
    pub processor_reference: Option<String>,
    /// The card network's transaction ID, for a later merchant-initiated
    /// charge.
    #[serde(default)]
    pub network_transaction_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One event on a payment's status timeline: the creation of, or a status
/// transition on, the payment intent or one of its attempts / refunds /
/// disputes.
///
/// [`entity_type`](Self::entity_type) is a plain `String` rather than an enum
/// so a new timeline event kind does not fail the whole response. The values
/// sent today are `"payment"`, `"attempt"`, `"refund"`, `"dispute"`, `"risk"`
/// and `"checkout"`. The last two are timeline events with **no underlying
/// status change**: `status` holds the event name rather than a payment state,
/// and `entity_id` names what it is about (the processor's risk-signal id, or
/// the native-pane method key).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentStatusHistoryEvent {
    /// What the event is about: `"payment"`, `"attempt"`, `"refund"`,
    /// `"dispute"`, `"risk"` or `"checkout"`.
    pub entity_type: String,
    /// RFC 3339 timestamp of the event.
    pub timestamp: String,

    /// Id of the attempt / refund / dispute the event belongs to. Absent for
    /// intent-level events.
    #[serde(default)]
    pub entity_id: Option<String>,
    /// The attempt this event is associated with, where known.
    #[serde(default)]
    pub attempt_id: Option<String>,
    /// The status before this event. Absent on creation and derived events.
    #[serde(default)]
    pub previous_status: Option<String>,
    /// The status after this event. Absent only on a derived creation event,
    /// where the initial status was not recorded.
    #[serde(default)]
    pub status: Option<String>,
    /// Connector involved in the event, where known.
    #[serde(default)]
    pub connector: Option<String>,
    /// Raw connector error code recorded with the event.
    #[serde(default)]
    pub error_code: Option<String>,
    /// Human-readable error message recorded with the event.
    #[serde(default)]
    pub error_message: Option<String>,
    /// `true` when this event records the creation of the entity.
    #[serde(default)]
    pub is_creation: bool,
    /// `true` when this event was reconstructed from current records (payments
    /// predating the persisted status log) — its timestamp is approximate and
    /// intermediate transitions may be missing.
    #[serde(default)]
    pub derived: bool,
    /// Who made the change, for a change a person made.
    #[serde(default)]
    pub actor: Option<PaymentHistoryActor>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Who made a payment history event.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentHistoryActor {
    /// `"merchant_user"` or `"operator"`.
    pub kind: String,
    /// The person's email address at the time, when it could be resolved.
    #[serde(default)]
    pub email: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The status timeline of a payment, returned by
/// [`Payments::list_status_history`](crate::resources::payments::Payments::list_status_history).
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentStatusHistoryResponse {
    /// The payment this timeline belongs to.
    pub payment_id: String,
    /// `true` when every event comes from the persisted status-transition log;
    /// `false` when any event had to be reconstructed from current records.
    #[serde(default)]
    pub complete: bool,
    /// The number of events returned.
    #[serde(default)]
    pub count: i64,
    /// All recorded events, oldest first.
    #[serde(default = "Vec::new")]
    pub events: Vec<PaymentStatusHistoryEvent>,
    /// The marker of a payment state recorded by hand, when there is one.
    #[serde(default)]
    pub external_record: Option<ExternalRecordMarker>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Outcome of soft-deleting a payment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentsDeleteResponse {
    /// The payment that was deleted.
    pub payment_id: String,
    /// The merchant it belonged to.
    pub merchant_id: String,
    /// Always `true` on success — the endpoint errors otherwise.
    pub deleted: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One client/device observation captured while the buyer interacted with a
/// payment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentClientContextEntry {
    /// Where it was captured: `checkout_open`, `confirm`, `redirect_return`,
    /// `client_signals`, …
    pub source: String,
    /// Browser-assigned device identifier.
    #[serde(default)]
    pub device_id: Option<String>,
    /// Partitioned (CHIPS) twin of [`device_id`](Self::device_id), scoped to
    /// the embedding site.
    #[serde(default)]
    pub partitioned_device_id: Option<String>,
    /// Observed IP address.
    #[serde(default)]
    pub ip_address: Option<String>,
    /// Country the IP resolved to.
    #[serde(default)]
    pub ip_country: Option<String>,
    /// Reported user agent.
    #[serde(default)]
    pub user_agent: Option<String>,
    /// Reported `Accept-Language`.
    #[serde(default)]
    pub accept_language: Option<String>,
    /// Best-effort hardware-model guess derived server-side. Display and
    /// analytics only — **never** make a decision on it.
    #[serde(default)]
    pub device_model: Option<String>,
    /// Capture-point-specific extras: client hints, screen size, referrer.
    ///
    /// The wire name is `extra`; renamed here because `extra` is this
    /// crate's catch-all for *unmodeled* fields, and one struct cannot mean
    /// both by that name.
    #[serde(rename = "extra", default)]
    pub extra_data: Option<Value>,
    /// ISO 8601 capture timestamp.
    pub created_at: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every client/device observation recorded for one payment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentClientContextListResponse {
    /// The payment the observations belong to.
    pub payment_id: String,
    /// How many observations were returned.
    #[serde(default)]
    pub count: i64,
    /// The observations, oldest first.
    #[serde(default = "Vec::new")]
    pub data: Vec<PaymentClientContextEntry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn payment_response_decodes_the_newer_fields() {
        let payment: PaymentResponse = serde_json::from_str(
            r#"{
                "payment_id": "pay_1", "merchant_id": "mer_1", "status": "failed",
                "amount": 1000, "currency": "EUR",
                "is_integration_test": true,
                "failure_substatus": "insufficient_funds",
                "buyer_failure_reason": "insufficient_funds",
                "buyer_blocked": false, "buyer_block_note": null,
                "processor_reference": "ch_1", "connector_environment": "sandbox",
                "cancel_url": "https://shop.test/cart",
                "vault": {"status": "direct", "direct_reason": "vault_switched_off"},
                "buyer_risk": {"score": 10, "band": "low", "action": "allow",
                    "applied_action": "allow", "reasons": [], "model_version": "p1",
                    "merchant_initiated": false, "evaluated_at": "2026-09-01T00:00:00Z"},
                "product_summary": {"line_count": 2, "attributed": true,
                    "first_line": {"id": "pli_1", "attributed": true, "name": "Hat",
                        "quantity": 1, "unit_amount": 500, "line_total": 500,
                        "currency": "EUR", "role": "product"}},
                "state_metadata": {"post_capture_void": {"status": "pending",
                    "updated_at": "2026-09-01T00:00:00Z"}, "required_connector_test_mode": true},
                "surprise_field": 1
            }"#,
        )
        .unwrap();
        assert!(payment.is_integration_test);
        assert_eq!(
            payment.failure_substatus.as_deref(),
            Some("insufficient_funds")
        );
        assert_eq!(payment.vault.as_ref().unwrap().status, "direct");
        assert_eq!(payment.buyer_risk.as_ref().unwrap().band, "low");
        let summary = payment.product_summary.as_ref().unwrap();
        assert_eq!(summary.line_count, 2);
        assert_eq!(summary.first_line.as_ref().unwrap().name, "Hat");
        let metadata = payment.state_metadata.as_ref().unwrap();
        assert_eq!(
            metadata
                .post_capture_void
                .as_ref()
                .unwrap()
                .status
                .as_deref(),
            Some("pending")
        );
        assert_eq!(metadata.extra["required_connector_test_mode"], true);
        assert_eq!(
            payment.cancel_url.as_deref(),
            Some("https://shop.test/cart")
        );
        assert_eq!(payment.extra["surprise_field"], 1);

        // An older payload without any of them still decodes.
        let older: PaymentResponse = serde_json::from_str(
            r#"{"payment_id":"pay_1","merchant_id":"mer_1","status":"succeeded","amount":1,"currency":"EUR"}"#,
        )
        .unwrap();
        assert!(!older.is_integration_test);
        assert!(older.vault.is_none());
    }

    #[test]
    fn attempt_history_settlement_and_replay_decode_the_newer_fields() {
        let attempt: PaymentAttemptResponse = serde_json::from_str(
            r#"{"attempt_id":"att_1","status":"failure","failure_substatus":"card_declined",
                "processor_reference":"ch_1","network_transaction_id":"ntid_1",
                "vault":{"status":"vault","vault_connector":"vgs","handover":"handed_over"}}"#,
        )
        .unwrap();
        assert_eq!(attempt.network_transaction_id.as_deref(), Some("ntid_1"));
        assert_eq!(
            attempt.vault.as_ref().unwrap().handover.as_deref(),
            Some("handed_over")
        );

        let history: PaymentStatusHistoryResponse = serde_json::from_str(
            r#"{"payment_id":"pay_1","events":[{"entity_type":"integration_test",
                "timestamp":"2026-09-01T00:00:00Z","status":"marked",
                "actor":{"kind":"merchant_user","email":"ada@example.com"}}],
                "external_record":{"recorded_by":"usr_1","recorded_at":"2026-09-01T00:00:00Z",
                "reason":"refunded in the processor dashboard","created_by_recording":false,
                "recording_count":1}}"#,
        )
        .unwrap();
        assert_eq!(
            history.events[0].actor.as_ref().unwrap().kind,
            "merchant_user"
        );
        assert_eq!(history.external_record.as_ref().unwrap().recording_count, 1);

        let settlement: ConnectorSettlementAttempt = serde_json::from_str(
            r#"{"attempt_id":"att_1","attempt_status":"charged","status":"paid_out",
                "processor_cost_amount":29,"processor_cost_currency":"EUR",
                "processor_cost_exponent":2,"processor_cost_source":"estimated",
                "processor_cost_basis":{"schedule_id":"fs_1","merchant_scoped":false,
                    "percentage":1.4,"effective_from":"2026-01-01T00:00:00Z"},
                "connector_method_code":"card"}"#,
        )
        .unwrap();
        assert_eq!(settlement.processor_cost_amount, Some(29));
        assert_eq!(
            settlement.processor_cost_basis.as_ref().unwrap().percentage,
            Some(1.4)
        );

        let playback: ReplayPlaybackResponse = serde_json::from_str(
            r#"{"playback_id":"pb_1","total_events":0,"has_redirect_gap":false,
                "slices":[{"sequence":0,"event_count":3,"byte_size":100,"first_event_at":1,
                    "last_event_at":2,"encoding":"gzip","stored_bytes":40}],
                "expired":{"swept_at":"2026-10-01T00:00:00Z","retention_days_applied":30}}"#,
        )
        .unwrap();
        assert_eq!(playback.slices[0].encoding, "gzip");
        assert_eq!(playback.slices[0].stored_bytes, 40);
        assert_eq!(
            playback.expired.as_ref().unwrap().retention_days_applied,
            30
        );
    }

    const WITH_SECRET: &str = r#"{
        "payment_id": "pay_1", "merchant_id": "mer_1", "status": "requires_confirmation",
        "amount": 1999, "currency": "EUR", "client_secret": "pay_1_secret_abc123"
    }"#;

    /// Kills a `Debug` that prints `&self.client_secret`, and a derived one.
    #[test]
    fn payment_response_debug_redacts_the_client_secret() {
        let res: PaymentResponse = serde_json::from_str(WITH_SECRET).unwrap();
        let printed = format!("{res:?}");

        assert!(!printed.contains("pay_1_secret_abc123"));
        assert!(printed.contains("client_secret: Some(\"[redacted]\")"));
        // Non-secret fields must still be readable, or the redaction has cost
        // more than it bought.
        assert!(printed.contains("pay_1"));
        assert!(printed.contains("1999"));
    }

    /// Kills a `Debug` that hard-codes `Some("[redacted]")` regardless of the
    /// field, which would hide whether a secret was ever issued.
    #[test]
    fn payment_response_debug_shows_none_when_no_client_secret() {
        let res: PaymentResponse = serde_json::from_str(
            r#"{"payment_id":"pay_1","merchant_id":"mer_1","status":"succeeded",
                "amount":1999,"currency":"EUR"}"#,
        )
        .unwrap();
        assert!(format!("{res:?}").contains("client_secret: None"));
    }

    /// A partially reconstructed timeline must stay readable, and a `risk` /
    /// `checkout` event — which carries an event name in `status` and no
    /// transition — must not be rejected. Mutation: typing `entity_type` as a
    /// closed enum makes the last two events fail to parse.
    #[test]
    fn status_history_parses_derived_and_non_status_events() {
        let history: PaymentStatusHistoryResponse = serde_json::from_str(
            r#"{
                "payment_id": "pay_1",
                "complete": false,
                "count": 3,
                "events": [
                    {
                        "entity_type": "payment",
                        "timestamp": "2026-08-01T10:00:00Z",
                        "status": "requires_confirmation",
                        "is_creation": true,
                        "derived": true
                    },
                    {
                        "entity_type": "attempt",
                        "entity_id": "pay_1_1",
                        "attempt_id": "pay_1_1",
                        "previous_status": "pending",
                        "status": "charged",
                        "connector": "stripe",
                        "timestamp": "2026-08-01T10:00:05Z",
                        "is_creation": false,
                        "derived": false
                    },
                    {
                        "entity_type": "checkout",
                        "entity_id": "apple_pay",
                        "status": "native_pane_selected",
                        "timestamp": "2026-08-01T10:00:03Z",
                        "is_creation": false,
                        "derived": false
                    }
                ]
            }"#,
        )
        .unwrap();

        assert_eq!(history.payment_id, "pay_1");
        assert!(!history.complete);
        assert_eq!(history.count, 3);
        assert!(history.events[0].derived);
        assert!(history.events[0].is_creation);
        assert_eq!(history.events[0].previous_status, None);
        assert_eq!(history.events[1].connector.as_deref(), Some("stripe"));
        assert_eq!(history.events[2].entity_type, "checkout");
        assert_eq!(
            history.events[2].status.as_deref(),
            Some("native_pane_selected")
        );
    }

    /// A timeline with no events must deserialize to an empty list rather than
    /// failing. Mutation: drop `#[serde(default = "Vec::new")]`.
    #[test]
    fn status_history_defaults_to_no_events() {
        let history: PaymentStatusHistoryResponse =
            serde_json::from_str(r#"{"payment_id":"pay_1"}"#).unwrap();
        assert!(history.events.is_empty());
        assert!(!history.complete);
    }
}

/// What the payment's rail says about settling one attempt.
///
/// Seven words, and the three that read like each other do not mean the same
/// thing:
///
/// - `"pending"` — the rail has the money and has not released it yet.
/// - `"available"` — released into the rail's own balance. **Not** paid out.
/// - `"paid_out"` — left the rail towards the merchant's bank.
/// - `"payout_failed"` — a payout was attempted and did not arrive.
/// - `"unavailable"` — this rail does not report settlement at all. Not
///   "not yet": nothing further will ever arrive for this attempt.
/// - `"unknown"` — the rail reports settlement but said nothing about this
///   attempt.
/// - `"not_recorded"` — there is no settlement row, e.g. an attempt that
///   never reached a rail.
///
/// A plain `String`, so a value the backend adds later is carried through
/// rather than dropped.
pub type ConnectorSettlementStatus = String;

/// The category of routing decision behind an attempt — never the rule that
/// fired.
///
/// The values the router records today: `"rule_based_routing"`,
/// `"volume_based_routing"`, `"straight_through_routing"`,
/// `"success_rate_exploitation"`, `"success_rate_exploration"`,
/// `"contract_based_routing"`, `"debit_routing"` and `"default_fallback"`.
/// `"default_fallback"` is a recorded decision like any other, not an absence.
///
/// A plain `String`: the set is open, and a new approach must reach a caller
/// rather than decode as nothing.
pub type RoutingApproach = String;

/// One attempt's settlement state on the rail that processed it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ConnectorSettlementAttempt {
    /// The attempt this line describes.
    pub attempt_id: String,
    /// The attempt's own payment status, so a caller need not join back to
    /// the attempt list to tell a settled capture from a failed authorization.
    pub attempt_status: AttemptStatus,
    /// Connector (gateway) the attempt ran on.
    #[serde(default)]
    pub connector: Option<String>,
    /// The connector account the attempt ran on.
    #[serde(default)]
    pub merchant_connector_id: Option<String>,
    /// What the rail says about settling this attempt.
    pub status: ConnectorSettlementStatus,
    /// When the funds become (or became) available in the rail's balance,
    /// RFC 3339. Absent when the rail does not say.
    #[serde(default)]
    pub available_on: Option<String>,
    /// The rail's own reference for the payout that carried this attempt.
    #[serde(default)]
    pub payout_reference: Option<String>,
    /// When that payout left the rail, RFC 3339.
    #[serde(default)]
    pub paid_out_at: Option<String>,
    /// When this settlement line was last written from the rail's report.
    #[serde(default)]
    pub last_recorded_at: Option<String>,
    /// What the processor charged for the attempt, in minor units of
    /// `processor_cost_currency`.
    #[serde(default)]
    pub processor_cost_amount: Option<i64>,
    /// Currency of `processor_cost_amount`.
    #[serde(default)]
    pub processor_cost_currency: Option<String>,
    /// Minor-unit exponent of `processor_cost_currency`.
    #[serde(default)]
    pub processor_cost_exponent: Option<i32>,
    /// Where the cost comes from: `"reported"`, `"estimated"` or
    /// `"unavailable"`; open.
    #[serde(default)]
    pub processor_cost_source: Option<String>,
    /// The fee schedule an estimated cost was priced from.
    #[serde(default)]
    pub processor_cost_basis: Option<ProcessorCostEstimateBasis>,
    /// The processor's own code for the payment method.
    #[serde(default)]
    pub connector_method_code: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// Every settlement line the caller may see for one payment.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentConnectorSettlementResponse {
    /// The payment these lines belong to.
    pub payment_id: String,
    /// How many attempts are in [`attempts`](Self::attempts) — the number
    /// **returned**, never a denominator. A caller narrowed to specific
    /// connector accounts sees only the attempts on connectors it may read,
    /// with nothing marking what was left out.
    pub count: u64,
    /// One line per attempt, **oldest attempt first**. An attempt with no
    /// settlement record is listed too, as `"not_recorded"`.
    pub attempts: Vec<ConnectorSettlementAttempt>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The manifest of a payment's stored checkout recording, answered when a
/// playback is opened.
///
/// A payment that was never recorded answers with an empty
/// [`slices`](Self::slices) and no [`session_id`](Self::session_id) — the
/// ordinary case for every payment made before the checkout started
/// recording — rather than an error.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ReplayPlaybackResponse {
    /// The playback this manifest belongs to; every slice read carries it.
    pub playback_id: String,
    /// The recording session, when the payment has one.
    #[serde(default)]
    pub session_id: Option<String>,
    /// Epoch milliseconds of the first recorded event.
    #[serde(default)]
    pub first_event_at: Option<i64>,
    /// Epoch milliseconds of the last recorded event.
    #[serde(default)]
    pub last_event_at: Option<i64>,
    /// How many events the whole recording holds.
    pub total_events: u64,
    /// Whether the recording has a gap where the buyer left for a redirect.
    /// A gap is expected, not a loss.
    pub has_redirect_gap: bool,
    /// The slices that exist, in no guaranteed order. Read them by ascending
    /// `sequence`; a number missing from this list is a gap, not the end.
    pub slices: Vec<ReplaySliceInfo>,
    /// Set when the recording was removed after its retention period.
    #[serde(default)]
    pub expired: Option<ReplayExpiry>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One slice named in a playback manifest.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ReplaySliceInfo {
    /// The slice's number, as passed to the slice read.
    pub sequence: u64,
    /// How many events the slice holds.
    pub event_count: u64,
    /// The slice's stored size in bytes.
    pub byte_size: u64,
    /// Epoch milliseconds of the slice's first event.
    pub first_event_at: i64,
    /// Epoch milliseconds of the slice's last event.
    pub last_event_at: i64,
    /// How the slice is stored, e.g. `"json"` or `"gzip"`. Empty from an
    /// older API.
    #[serde(default)]
    pub encoding: String,
    /// The slice's size as stored, in bytes. `0` from an older API.
    #[serde(default)]
    pub stored_bytes: i64,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// When and why a checkout recording was removed.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ReplayExpiry {
    /// ISO 8601 time the recording was removed.
    pub swept_at: String,
    /// The retention period that applied, in days.
    pub retention_days_applied: i32,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// One slice's recorded events, read against an open playback.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ReplaySliceResponse {
    /// The slice's number.
    pub sequence: u64,
    /// The recorded events, in the recorder's own shape.
    pub events: Vec<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What the recorder is told about one stored slice.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct ReplayIngestResponse {
    /// The slice number that was stored.
    pub sequence: u64,
    /// Whether this slice number was already stored, in which case nothing
    /// was written. A retry after a lost response is safe and lands here.
    pub duplicate: bool,
    /// Whether the recording has reached its storage budget. Once `true`,
    /// stop sending: further slices are refused.
    pub full: bool,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What abandoning an open attempt did.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentAbandonAttemptResponse {
    /// The payment.
    pub payment_id: String,
    /// The payment's status afterwards — `requires_payment_method`, the fresh
    /// attempt awaiting a method.
    pub status: IntentStatus,
    /// The new attempt now awaiting a payment method.
    pub attempt_id: String,
    /// The attempt that was dropped. `None` when the payment was already
    /// awaiting a method, which is the idempotent no-op.
    #[serde(default)]
    pub abandoned_attempt_id: Option<String>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// What reopening a switched-away attempt did: the attempt is the payment's
/// active one again, and [`redirect_url`](Self::redirect_url) sends the buyer
/// back to its provider session.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentReopenAttemptResponse {
    /// The payment.
    pub payment_id: String,
    /// The payment's status afterwards: `requires_customer_action`.
    pub status: IntentStatus,
    /// The attempt that is active again.
    pub attempt_id: String,
    /// Where the buyer continues the reopened session.
    pub redirect_url: String,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}

/// The processor-side session a browser SDK completes.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PaymentPostSessionTokensResponse {
    /// The payment the session belongs to.
    pub payment_id: String,
    /// The payment's status.
    pub status: IntentStatus,
    /// What the page must do next. For PayPal Card Fields the order id is at
    /// `next_action.next_action_data.order_id`. Open shape: the next-action
    /// union is the router's own and grows.
    #[serde(default)]
    pub next_action: Option<Value>,
    /// Any additional response fields not modeled above.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, Value>,
}