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
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
//! The `connectors` resource: merchant connector accounts, the per-shop
//! bindings between a merchant account and an upstream payment processor.
use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::connector::{
ConnectorResponse, ConnectorWebhookListResponse, ConnectorWebhookRegisterResponse,
ConnectorWebhookSyncResponse, StripePaymentMethodDomainsRegisterResponse,
};
use crate::core::panes::PanesCatalogResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
/// The `connectors` resource, obtained via [`crate::Delopay::connectors`].
#[derive(Debug, Clone)]
pub struct Connectors {
inner: Arc<Inner>,
}
impl Connectors {
pub(crate) fn new(inner: Arc<Inner>) -> Self {
Self { inner }
}
/// Create a connector under a merchant account.
/// `POST /account/{account_id}/connectors`
pub async fn create(
&self,
account_id: &str,
params: &ConnectorCreateRequest,
) -> Result<ConnectorResponse> {
params.validate()?;
let path = format!("/account/{}/connectors", encode_segment(account_id));
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
/// Every connector's pane capabilities, as the router itself knows them —
/// which rails a connector supports, and which methods it can publish as a
/// pane, with the confirm routing keys each one carries.
///
/// Capability facts only: no label, sublabel or category comes back. Render
/// a method's copy from your own locale files, keyed by
/// [`crate::panes::PaneCapability::key`], and take the routing keys from here verbatim
/// rather than deriving them.
///
/// This is what the helpers in [`crate::panes`] should be driven from —
/// [`crate::panes::default_pane`] and [`crate::panes::validate_panes`] both
/// take a [`crate::panes::PanesConnectorCatalog`] out of this response, so a connector
/// the router starts publishing panes for needs no SDK release.
///
/// `GET /account/{account_id}/connectors/native-panes/catalog`
///
/// The path keeps the `native-panes` spelling deliberately: the router's
/// route was never renamed, and pointing at a new name would 404.
///
/// A router predating the endpoint answers 404. That is the case
/// [`crate::panes::STRIPE_FALLBACK_PANE_CATALOG`] exists for — degrade to
/// it rather than offering a caller nothing.
pub async fn panes_catalog(&self, account_id: &str) -> Result<PanesCatalogResponse> {
let path = format!(
"/account/{}/connectors/native-panes/catalog",
encode_segment(account_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
/// Retrieve one connector.
/// `GET /account/{account_id}/connectors/{connector_id}`
///
/// The credential-bearing fields come back `null` here whatever is stored:
/// `connector_webhook_details`, `connector_wallets_details`,
/// `pm_auth_config` and `additional_merchant_data`. They are dropped
/// rather than masked, because an editor that prefills from this response
/// and writes the field back would otherwise save a mask over a live
/// signing secret. Send one only when an operator typed a new value; an
/// omitted field leaves the stored one alone.
///
/// This is the retrieve path alone — [`Self::create`] and [`Self::update`]
/// echo back what the caller sent, and [`Self::clone_connector`] returns
/// the copied secrets.
pub async fn retrieve(
&self,
account_id: &str,
connector_id: &str,
) -> Result<ConnectorResponse> {
let path = format!(
"/account/{}/connectors/{}",
encode_segment(account_id),
encode_segment(connector_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
/// List a merchant account's connectors.
/// `GET /account/{account_id}/connectors`
///
/// Never wider than the caller: an API key pinned to one shop lists that
/// shop's connectors only, not every sibling shop's.
pub async fn list(&self, account_id: &str) -> Result<Vec<ConnectorResponse>> {
let path = format!("/account/{}/connectors", encode_segment(account_id));
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
/// Update a connector.
/// `POST /account/{account_id}/connectors/{connector_id}`
pub async fn update(
&self,
account_id: &str,
connector_id: &str,
params: &ConnectorUpdateRequest,
) -> Result<ConnectorResponse> {
params.validate()?;
let path = format!(
"/account/{}/connectors/{}",
encode_segment(account_id),
encode_segment(connector_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
/// Delete a connector.
/// `DELETE /account/{account_id}/connectors/{connector_id}`
///
/// A shop-scoped role may remove a connector of its own shop — the shop is
/// re-checked server-side — so creating processors and removing them are
/// one rung of access rather than two.
pub async fn delete(&self, account_id: &str, connector_id: &str) -> Result<ConnectorResponse> {
let path = format!(
"/account/{}/connectors/{}",
encode_segment(account_id),
encode_segment(connector_id)
);
self.inner
.request(HttpMethod::Delete, &path, None, &[], None)
.await
}
/// Clone a connector into another shop (business profile) of the same
/// merchant. `POST /account/{account_id}/connectors/{connector_id}/clone`
///
/// Credentials are copied server-side, re-encrypted under the same merchant
/// key, so the caller never has to *supply* them — [`Self::retrieve`]
/// returns `null` for the credential fields, which is what makes a
/// client-side copy impossible in the first place.
///
/// The response, however, is the unredacted connector:
/// `connector_account_details` is masked, but `connector_webhook_details`,
/// `connector_wallets_details`, `pm_auth_config` and
/// `additional_merchant_data` come back carrying the copied secrets —
/// values this caller never sent. Do not log or echo it; read
/// `merchant_connector_id` and drop the rest.
///
/// Named `clone_connector`, not `clone`: an inherent `clone` taking three
/// arguments would shadow [`Clone::clone`] and make `connectors.clone()`
/// fail to compile.
pub async fn clone_connector(
&self,
account_id: &str,
connector_id: &str,
params: &ConnectorCloneRequest,
) -> Result<ConnectorResponse> {
let path = format!(
"/account/{}/connectors/{}/clone",
encode_segment(account_id),
encode_segment(connector_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
/// Verify connector credentials. `POST /account/connectors/verify`
///
/// Open body shape — see the API reference.
pub async fn verify(&self, params: &Value) -> Result<Value> {
let body = to_json_vec(params)?;
self.inner
.request(
HttpMethod::Post,
"/account/connectors/verify",
Some(&body),
&[],
None,
)
.await
}
/// Register a webhook for a connector.
/// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}`
///
/// Pass `None` to send no body, which the server treats as
/// `{ "event_type": "all_events" }`; pass
/// [`ConnectorWebhookRegisterRequest::specific_event`] to scope the
/// registration to a single event.
pub async fn register_webhook(
&self,
merchant_id: &str,
connector_id: &str,
params: Option<&ConnectorWebhookRegisterRequest>,
) -> Result<ConnectorWebhookRegisterResponse> {
let path = format!(
"/account/{}/connectors/webhooks/{}",
encode_segment(merchant_id),
encode_segment(connector_id)
);
match params {
// The TypeScript SDK omits the body entirely when no params are
// given; the server's default only applies to a bodyless call.
None => {
self.inner
.request(HttpMethod::Post, &path, None, &[], None)
.await
}
Some(p) => {
let body = to_json_vec(p)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
}
}
/// Get the webhooks registered for a connector.
/// `GET /account/{merchant_id}/connectors/webhooks/{connector_id}`
pub async fn webhook(
&self,
merchant_id: &str,
connector_id: &str,
) -> Result<ConnectorWebhookListResponse> {
let path = format!(
"/account/{}/connectors/webhooks/{}",
encode_segment(merchant_id),
encode_segment(connector_id)
);
self.inner
.request(HttpMethod::Get, &path, None, &[], None)
.await
}
/// Bring an already-registered webhook's event subscription up to date
/// with the events Delopay handles.
/// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}/sync-events`
///
/// A PSP freezes an endpoint's event list at registration time, so an
/// endpoint created before an event type was added never receives it —
/// silently, with no error anywhere. [`webhook`](Self::webhook) reports the
/// gap as
/// [`missing_events`](crate::core::models::connector::ConnectorWebhookEntry::missing_events);
/// this repairs it.
///
/// Unlike re-registering, the endpoints are updated **in place**: the
/// endpoint id and its signing secret are preserved, so signature
/// verification keeps working across the change. Stripe connectors only;
/// idempotent, so it is safe on a schedule or after every deploy.
///
/// ```no_run
/// # use delopay::Delopay;
/// # async fn run(client: Delopay) -> delopay::Result<()> {
/// let sync = client
/// .connectors()
/// .sync_webhook_events("mer_abc", "mca_xyz")
/// .await?;
/// for endpoint in &sync.endpoints {
/// match &endpoint.error_message {
/// Some(err) => eprintln!("{}: {err}", endpoint.connector_webhook_id),
/// None if endpoint.updated => println!("subscribed {:?}", endpoint.added_events),
/// None => {}
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn sync_webhook_events(
&self,
merchant_id: &str,
connector_id: &str,
) -> Result<ConnectorWebhookSyncResponse> {
let path = format!(
"/account/{}/connectors/webhooks/{}/sync-events",
encode_segment(merchant_id),
encode_segment(connector_id)
);
self.inner
.request(HttpMethod::Post, &path, None, &[], None)
.await
}
/// Register checkout/shop domains as Stripe *payment method domains*, so
/// Apple Pay renders on those pages.
/// `POST /account/{merchant_id}/connectors/{connector_id}/stripe/payment-method-domains`
///
/// Stripe hides the Apple Pay button silently on an unregistered domain, so
/// a missing registration looks like "Apple Pay is unavailable" rather than
/// an error. Stripe connectors only. One call registers against a single
/// credential set
/// ([`environment`](StripePaymentMethodDomainsRegisterRequest::environment),
/// default `"live"`) — call it twice to cover live and sandbox. Per-URL
/// outcomes come back in
/// [`results`](StripePaymentMethodDomainsRegisterResponse::results); a
/// missing sandbox credential set is a request-level 400.
pub async fn register_stripe_payment_method_domains(
&self,
merchant_id: &str,
connector_id: &str,
params: &StripePaymentMethodDomainsRegisterRequest,
) -> Result<StripePaymentMethodDomainsRegisterResponse> {
let path = format!(
"/account/{}/connectors/{}/stripe/payment-method-domains",
encode_segment(merchant_id),
encode_segment(connector_id)
);
let body = to_json_vec(params)?;
self.inner
.request(HttpMethod::Post, &path, Some(&body), &[], None)
.await
}
/// List the payment methods the platform supports.
/// `GET /account/payment-methods`
pub async fn list_payment_methods(&self) -> Result<Vec<Value>> {
self.inner
.request(HttpMethod::Get, "/account/payment-methods", None, &[], None)
.await
}
}
/// Parameters for [`Connectors::create`].
///
/// `Debug` is hand-written: `connector_account_details`,
/// `connector_webhook_details` and `additional_merchant_data` carry live
/// gateway credentials (API keys, signing secrets, acquirer merchant data), so
/// a derived `Debug` would leak them into logs. They print as
/// `Some("[redacted]")`.
#[derive(Clone, Default, Serialize)]
pub struct ConnectorCreateRequest {
/// Connector category, e.g. `"payment_processor"` or `"payout_processor"`.
pub connector_type: String,
/// Snake-case connector identifier, e.g. `"stripe"`, `"adyen"`.
pub connector_name: String,
/// Human-readable label, unique within the merchant account.
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_label: Option<String>,
/// Shop (business profile) the connector belongs to.
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_id: Option<String>,
/// Gateway credentials (open shape — see the API reference). **Secret.**
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_account_details: Option<Value>,
/// Payment methods to enable on this connector (open shapes).
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_methods_enabled: Option<Vec<Value>>,
/// Arbitrary key-value metadata.
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
/// Whether the connector runs against the gateway's test environment.
#[serde(skip_serializing_if = "Option::is_none")]
pub test_mode: Option<bool>,
/// Whether the connector is disabled on creation.
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled: Option<bool>,
/// Incoming-webhook verification details. **Secret** (holds the shared
/// verification secret).
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_webhook_details: Option<Value>,
/// Additional merchant data required by some connectors. **Secret.**
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_merchant_data: Option<Value>,
/// Connector status, e.g. `"active"` or `"inactive"`.
#[serde(skip_serializing_if = "Option::is_none")]
pub status: Option<String>,
/// Any additional fields, merged verbatim.
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
/// Placeholder printed in place of a credential-bearing field.
const REDACTED: &str = "[redacted]";
/// `Some("[redacted]")` when the credential field is set, `None` when it is
/// not — enough to debug "did I set this?" without printing the secret.
fn redact(v: Option<&Value>) -> Option<&'static str> {
v.map(|_| REDACTED)
}
impl std::fmt::Debug for ConnectorCreateRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConnectorCreateRequest")
.field("connector_type", &self.connector_type)
.field("connector_name", &self.connector_name)
.field("connector_label", &self.connector_label)
.field("profile_id", &self.profile_id)
.field(
"connector_account_details",
&redact(self.connector_account_details.as_ref()),
)
.field("payment_methods_enabled", &self.payment_methods_enabled)
.field("metadata", &self.metadata)
.field("test_mode", &self.test_mode)
.field("disabled", &self.disabled)
.field(
"connector_webhook_details",
&redact(self.connector_webhook_details.as_ref()),
)
.field(
"additional_merchant_data",
&redact(self.additional_merchant_data.as_ref()),
)
.field("status", &self.status)
.field("extra", &self.extra)
.finish()
}
}
/// Names of `ConnectorCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded).
const CONNECTOR_CREATE_REQUEST_NAMED: &[&str] = &[
"connector_type",
"connector_name",
"connector_label",
"profile_id",
"connector_account_details",
"payment_methods_enabled",
"metadata",
"test_mode",
"disabled",
"connector_webhook_details",
"additional_merchant_data",
"status",
];
impl ValidateRequest for ConnectorCreateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if CONNECTOR_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ConnectorCreateRequest"
)));
}
}
Ok(())
}
}
impl ConnectorCreateRequest {
/// A request creating a connector of the given category and name, e.g.
/// `ConnectorCreateRequest::new("payment_processor", "stripe")`.
pub fn new(connector_type: impl Into<String>, connector_name: impl Into<String>) -> Self {
Self {
connector_type: connector_type.into(),
connector_name: connector_name.into(),
..Default::default()
}
}
/// Set the shop (business profile) the connector belongs to.
#[must_use]
pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
self.profile_id = Some(profile_id.into());
self
}
/// Set the connector's label.
#[must_use]
pub fn connector_label(mut self, label: impl Into<String>) -> Self {
self.connector_label = Some(label.into());
self
}
/// Set the gateway credentials.
#[must_use]
pub fn connector_account_details(mut self, details: Value) -> Self {
self.connector_account_details = Some(details);
self
}
/// Set whether the connector runs in the gateway's test environment.
#[must_use]
pub fn test_mode(mut self, test_mode: bool) -> Self {
self.test_mode = Some(test_mode);
self
}
}
/// Parameters for [`Connectors::update`].
///
/// `Debug` is hand-written for the same reason as
/// [`ConnectorCreateRequest`]: the credential-bearing fields are redacted.
#[derive(Clone, Default, Serialize)]
pub struct ConnectorUpdateRequest {
/// Connector category, e.g. `"payment_processor"`. Required by the API.
pub connector_type: String,
/// Connector status, e.g. `"active"` or `"inactive"`. Required by the API.
pub status: String,
/// Human-readable label, unique within the merchant account.
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_label: Option<String>,
/// Gateway credentials (open shape — see the API reference). **Secret.**
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_account_details: Option<Value>,
/// Payment methods enabled on this connector (open shapes).
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_methods_enabled: Option<Vec<Value>>,
/// Arbitrary key-value metadata.
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Value>,
/// Whether the connector runs against the gateway's test environment.
#[serde(skip_serializing_if = "Option::is_none")]
pub test_mode: Option<bool>,
/// Whether the connector is disabled.
#[serde(skip_serializing_if = "Option::is_none")]
pub disabled: Option<bool>,
/// Incoming-webhook verification details. **Secret**, and **merged key by
/// key** — unlike every other field on this request.
///
/// Send only the keys an operator actually typed. See
/// [`ConnectorWebhookDetailsUpdate`] for what an omitted key, a value and
/// an empty string each do; padding the environment you are not editing
/// with empty strings clears its live signing secret.
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_webhook_details: Option<ConnectorWebhookDetailsUpdate>,
/// Additional merchant data required by some connectors. **Secret.**
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_merchant_data: Option<Value>,
/// Any additional fields, merged verbatim.
#[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
pub extra: serde_json::Map<String, Value>,
}
/// The incoming-webhook signing secrets of one connector account, as an
/// **update**.
///
/// The server merges this key by key, which the sibling secret fields on
/// [`ConnectorUpdateRequest`] do not do:
///
/// | What you send | What happens |
/// |---|---|
/// | the key omitted (`None`) | the stored secret is kept |
/// | a value | it is written |
/// | an empty string | the stored secret is **cleared** |
///
/// So send only the keys an operator actually typed. A caller that fills in
/// the whole block and pads the environment it is not editing with `""`
/// clears that environment's live signing secret, and inbound webhooks stop
/// verifying with nothing on screen to say why.
///
/// Typing the four keys catches a misspelling (`merchant_secrets`) and a
/// non-string value, both of which an open JSON value accepted in silence. It
/// cannot catch the destructive case — clearing a secret with `""` is the
/// intended way to clear one, so the call that means it and the call that
/// pads are the same call. That guard is the calling convention above.
///
/// `Debug` is hand-written: every field here is a live signing secret.
#[derive(Clone, Default, Serialize)]
pub struct ConnectorWebhookDetailsUpdate {
/// Live signing secret.
#[serde(skip_serializing_if = "Option::is_none")]
pub merchant_secret: Option<String>,
/// Second live secret, for connectors that sign with a pair.
#[serde(skip_serializing_if = "Option::is_none")]
pub additional_secret: Option<String>,
/// Sandbox signing secret.
#[serde(skip_serializing_if = "Option::is_none")]
pub sandbox_merchant_secret: Option<String>,
/// Second sandbox secret.
#[serde(skip_serializing_if = "Option::is_none")]
pub sandbox_additional_secret: Option<String>,
}
impl std::fmt::Debug for ConnectorWebhookDetailsUpdate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mask = |v: &Option<String>| v.as_ref().map(|_| REDACTED);
f.debug_struct("ConnectorWebhookDetailsUpdate")
.field("merchant_secret", &mask(&self.merchant_secret))
.field("additional_secret", &mask(&self.additional_secret))
.field(
"sandbox_merchant_secret",
&mask(&self.sandbox_merchant_secret),
)
.field(
"sandbox_additional_secret",
&mask(&self.sandbox_additional_secret),
)
.finish()
}
}
impl std::fmt::Debug for ConnectorUpdateRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConnectorUpdateRequest")
.field("connector_type", &self.connector_type)
.field("status", &self.status)
.field("connector_label", &self.connector_label)
.field(
"connector_account_details",
&redact(self.connector_account_details.as_ref()),
)
.field("payment_methods_enabled", &self.payment_methods_enabled)
.field("metadata", &self.metadata)
.field("test_mode", &self.test_mode)
.field("disabled", &self.disabled)
.field("connector_webhook_details", &self.connector_webhook_details)
.field(
"additional_merchant_data",
&redact(self.additional_merchant_data.as_ref()),
)
.field("extra", &self.extra)
.finish()
}
}
/// Names of `ConnectorUpdateRequest`'s fields, as they appear on the wire
/// (`extra` excluded).
const CONNECTOR_UPDATE_REQUEST_NAMED: &[&str] = &[
"connector_type",
"status",
"connector_label",
"connector_account_details",
"payment_methods_enabled",
"metadata",
"test_mode",
"disabled",
"connector_webhook_details",
"additional_merchant_data",
];
impl ValidateRequest for ConnectorUpdateRequest {
fn validate(&self) -> Result<()> {
for key in self.extra.keys() {
if CONNECTOR_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
return Err(DelopayError::InvalidRequest(format!(
"`extra` key `{key}` collides with a named field on ConnectorUpdateRequest"
)));
}
}
Ok(())
}
}
impl ConnectorUpdateRequest {
/// A request setting the connector's category and status, e.g.
/// `ConnectorUpdateRequest::new("payment_processor", "active")`.
pub fn new(connector_type: impl Into<String>, status: impl Into<String>) -> Self {
Self {
connector_type: connector_type.into(),
status: status.into(),
..Default::default()
}
}
/// Set the gateway credentials.
#[must_use]
pub fn connector_account_details(mut self, details: Value) -> Self {
self.connector_account_details = Some(details);
self
}
/// Set whether the connector is disabled.
#[must_use]
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = Some(disabled);
self
}
}
/// Parameters for [`Connectors::clone_connector`].
///
/// Carries no credentials — the copy happens server-side — so `Debug` is
/// derived.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorCloneRequest {
/// Target shop (business profile) to clone the connector into. Must belong
/// to the same merchant; it cannot be the source connector's own shop.
pub profile_id: String,
/// Label for the clone. Omit to let the server derive one from the source
/// connector's label.
#[serde(skip_serializing_if = "Option::is_none")]
pub connector_label: Option<String>,
}
impl ConnectorCloneRequest {
/// A request cloning into the given shop (business profile).
pub fn new(profile_id: impl Into<String>) -> Self {
Self {
profile_id: profile_id.into(),
connector_label: None,
}
}
/// Set the clone's label.
#[must_use]
pub fn connector_label(mut self, label: impl Into<String>) -> Self {
self.connector_label = Some(label.into());
self
}
}
/// Parameters for [`Connectors::register_webhook`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorWebhookRegisterRequest {
/// Event scope: the string `"all_events"`, or
/// `{"specific_event": "…"}`. Omit to let the server default to all
/// events.
#[serde(skip_serializing_if = "Option::is_none")]
pub event_type: Option<Value>,
/// Credential set to register with: `"live"` or `"sandbox"`. Defaults to
/// `"live"` server-side.
#[serde(skip_serializing_if = "Option::is_none")]
pub environment: Option<String>,
/// Endpoint URL to register (plain `/webhooks/…` or obfuscated
/// `/webhooks_base/…` form). When omitted the server derives the canonical
/// plain form. Must route back to the connector account — the path has to
/// end with the `mca_…` id.
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook_url: Option<String>,
}
impl ConnectorWebhookRegisterRequest {
/// Register for every event the connector emits.
pub fn all_events() -> Self {
Self {
event_type: Some(Value::String("all_events".to_string())),
..Default::default()
}
}
/// Register for one named event only.
pub fn specific_event(event: impl Into<String>) -> Self {
Self {
event_type: Some(serde_json::json!({ "specific_event": event.into() })),
..Default::default()
}
}
/// Register against the `"live"` or `"sandbox"` credential set.
#[must_use]
pub fn environment(mut self, environment: impl Into<String>) -> Self {
self.environment = Some(environment.into());
self
}
/// Register a specific endpoint URL instead of the server-derived one.
#[must_use]
pub fn webhook_url(mut self, url: impl Into<String>) -> Self {
self.webhook_url = Some(url.into());
self
}
}
/// Parameters for [`Connectors::register_stripe_payment_method_domains`].
///
/// `urls` is serialized even when empty: an empty list is a caller mistake the
/// server should reject explicitly, not a field the SDK quietly drops into a
/// different request.
#[derive(Debug, Clone, Default, Serialize)]
pub struct StripePaymentMethodDomainsRegisterRequest {
/// Absolute URLs (or bare hostnames) whose hosts are registered — the
/// hosted-checkout origin first, plus any of the merchant's own shop URLs.
/// At most 10 per request; duplicates by resolved host are collapsed
/// server-side but still receive their own result row.
pub urls: Vec<String>,
/// Credential set to register with: `"live"` or `"sandbox"`. Defaults to
/// `"live"` server-side.
#[serde(skip_serializing_if = "Option::is_none")]
pub environment: Option<String>,
}
impl StripePaymentMethodDomainsRegisterRequest {
/// Register the given URLs against the connector's live credential set.
pub fn new<I, S>(urls: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
urls: urls.into_iter().map(Into::into).collect(),
environment: None,
}
}
/// Register against the `"live"` or `"sandbox"` credential set instead of
/// the server default (`"live"`).
#[must_use]
pub fn environment(mut self, environment: impl Into<String>) -> Self {
self.environment = Some(environment.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::mock::{Step, client_with};
use serde_json::json;
const CONNECTOR_JSON: &str = r#"{
"merchant_connector_id": "mca_1",
"connector_type": "payment_processor",
"connector_name": "stripe",
"profile_id": "pro_1",
"status": "active"
}"#;
fn full_create_request() -> ConnectorCreateRequest {
ConnectorCreateRequest {
connector_type: "payment_processor".to_string(),
connector_name: "stripe".to_string(),
connector_label: Some("stripe_uk".to_string()),
profile_id: Some("pro_1".to_string()),
connector_account_details: Some(json!({"api_key": "sk_live_supersecret"})),
payment_methods_enabled: Some(vec![json!({"payment_method": "card"})]),
metadata: Some(json!({"team": "payments"})),
test_mode: Some(false),
disabled: Some(false),
connector_webhook_details: Some(json!({"merchant_secret": "whsec_topsecret"})),
additional_merchant_data: Some(json!({"acquirer": "acq_1"})),
status: Some("active".to_string()),
extra: serde_json::Map::new(),
}
}
fn full_update_request() -> ConnectorUpdateRequest {
ConnectorUpdateRequest {
connector_type: "payment_processor".to_string(),
status: "active".to_string(),
connector_label: Some("stripe_uk".to_string()),
connector_account_details: Some(json!({"api_key": "sk_live_supersecret"})),
payment_methods_enabled: Some(vec![json!({"payment_method": "card"})]),
metadata: Some(json!({"team": "payments"})),
test_mode: Some(false),
disabled: Some(false),
connector_webhook_details: Some(ConnectorWebhookDetailsUpdate {
merchant_secret: Some("whsec_topsecret".to_string()),
additional_secret: None,
sandbox_merchant_secret: None,
sandbox_additional_secret: None,
}),
additional_merchant_data: Some(json!({"acquirer": "acq_1"})),
extra: serde_json::Map::new(),
}
}
/// The catalogue route keeps the router's own spelling of the path.
///
/// Mutation: rename the segment to `panes` — which is what the SDK's own
/// identifiers were renamed to — and this fails, as it would 404 in
/// production.
#[tokio::test]
async fn panes_catalog_gets_the_routers_own_path_and_decodes() {
let (client, mock) = client_with(vec![Step::ok(
r#"{
"connectors": [{
"connector": "stripe",
"allowed_rails": ["wallet", "redirect"],
"methods": [{
"key": "klarna",
"rail": "redirect",
"payment_method": "pay_later",
"payment_method_type": "klarna",
"requires_billing_country": true
}]
}]
}"#,
)]);
let catalog = client.connectors().panes_catalog("acct/1").await.unwrap();
assert_eq!(catalog.connectors[0].connector, "stripe");
let method = &catalog.connectors[0].methods[0];
assert_eq!(method.payment_method, "pay_later");
assert!(method.requires_billing_country);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "GET");
assert_eq!(
seen[0].url,
"https://api.test/account/acct%2F1/connectors/native-panes/catalog"
);
}
/// Drift guard: catches a new field added to `ConnectorCreateRequest`
/// without a matching update to `CONNECTOR_CREATE_REQUEST_NAMED`.
#[test]
fn connector_create_request_named_fields_are_complete() {
let value = serde_json::to_value(full_create_request()).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
CONNECTOR_CREATE_REQUEST_NAMED.contains(&key.as_str()),
"CONNECTOR_CREATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
/// Only the keys a caller set reach the wire.
///
/// The server merges this block key by key, so an omitted key keeps the
/// stored secret and an explicit empty string clears it. Serializing the
/// unset keys — as `null`, or as `""` — would turn "I am changing the live
/// secret" into "I am also clearing both sandbox secrets", and inbound
/// webhooks would stop verifying with nothing on screen to say why.
///
/// Mutation: drop the `skip_serializing_if` on any field of
/// `ConnectorWebhookDetailsUpdate` and this fails.
#[test]
fn a_webhook_secret_update_sends_only_the_keys_it_sets() {
let request = ConnectorUpdateRequest {
connector_webhook_details: Some(ConnectorWebhookDetailsUpdate {
sandbox_merchant_secret: Some("whsec_sandbox".to_string()),
..ConnectorWebhookDetailsUpdate::default()
}),
..ConnectorUpdateRequest::new("payment_processor", "active")
};
let value = serde_json::to_value(&request).unwrap();
let details = value
.get("connector_webhook_details")
.and_then(Value::as_object)
.expect("the block serializes");
assert_eq!(
details.keys().collect::<Vec<_>>(),
["sandbox_merchant_secret"]
);
}
/// An empty string is a deliberate clear and does reach the wire — the
/// only way to remove a stored secret. The type cannot tell that call from
/// a caller padding the block, which is why the calling convention is
/// "send only what an operator typed".
#[test]
fn an_explicit_empty_secret_is_sent_because_it_means_clear_it() {
let request = ConnectorUpdateRequest {
connector_webhook_details: Some(ConnectorWebhookDetailsUpdate {
merchant_secret: Some(String::new()),
..ConnectorWebhookDetailsUpdate::default()
}),
..ConnectorUpdateRequest::new("payment_processor", "active")
};
let value = serde_json::to_value(&request).unwrap();
assert_eq!(value["connector_webhook_details"]["merchant_secret"], "");
}
/// Every secret in the block prints redacted.
///
/// Mutation: derive `Debug` on `ConnectorWebhookDetailsUpdate` and this
/// fails — a request struct is exactly what lands in a debug log when a
/// save goes wrong.
#[test]
fn a_webhook_secret_update_debug_redacts_every_secret() {
let printed = format!(
"{:?}",
ConnectorWebhookDetailsUpdate {
merchant_secret: Some("whsec_live".to_string()),
additional_secret: Some("whsec_extra".to_string()),
sandbox_merchant_secret: Some("whsec_sandbox".to_string()),
sandbox_additional_secret: Some("whsec_sandbox_extra".to_string()),
}
);
assert!(!printed.contains("whsec_"), "printed: {printed}");
assert_eq!(printed.matches(REDACTED).count(), 4);
}
/// Drift guard for `CONNECTOR_UPDATE_REQUEST_NAMED`.
#[test]
fn connector_update_request_named_fields_are_complete() {
let value = serde_json::to_value(full_update_request()).unwrap();
for key in value.as_object().expect("serializes to an object").keys() {
assert!(
CONNECTOR_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
"CONNECTOR_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
);
}
}
#[test]
fn create_validate_rejects_colliding_extra_key() {
let mut req = ConnectorCreateRequest::new("payment_processor", "stripe");
req.extra.insert("profile_id".to_string(), json!("pro_2"));
match req.validate().unwrap_err() {
DelopayError::InvalidRequest(msg) => assert!(msg.contains("profile_id")),
other => panic!("expected InvalidRequest, got {other:?}"),
}
}
#[test]
fn update_validate_rejects_colliding_extra_key() {
let mut req = ConnectorUpdateRequest::new("payment_processor", "active");
req.extra.insert("status".to_string(), json!("inactive"));
assert!(matches!(
req.validate().unwrap_err(),
DelopayError::InvalidRequest(_)
));
}
/// The credential fields must never reach a log line. A mutation replacing
/// `redact(...)` with the field itself makes this red.
#[test]
fn debug_redacts_connector_credentials() {
let rendered = format!("{:?}", full_create_request());
assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
assert!(!rendered.contains("acq_1"), "{rendered}");
assert!(rendered.contains("connector_account_details: Some(\"[redacted]\")"));
// Non-secret fields still print, or the impl would be useless.
assert!(rendered.contains("stripe"), "{rendered}");
let rendered = format!("{:?}", full_update_request());
assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
assert!(!rendered.contains("acq_1"), "{rendered}");
assert!(rendered.contains("connector_account_details: Some(\"[redacted]\")"));
}
/// An unset credential field must be distinguishable from a set one.
#[test]
fn debug_shows_none_for_unset_credentials() {
let rendered = format!(
"{:?}",
ConnectorCreateRequest::new("payment_processor", "stripe")
);
assert!(
rendered.contains("connector_account_details: None"),
"{rendered}"
);
}
#[tokio::test]
async fn create_posts_to_the_account_connectors_path() {
let (client, mock) = client_with(vec![Step::ok(CONNECTOR_JSON)]);
let req = ConnectorCreateRequest::new("payment_processor", "stripe")
.profile_id("pro_1")
.connector_account_details(json!({"api_key": "sk_test"}));
let created = client.connectors().create("mer/1", &req).await.unwrap();
assert_eq!(created.merchant_connector_id, "mca_1");
assert_eq!(created.connector_name.as_deref(), Some("stripe"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/account/mer%2F1/connectors");
let body = seen[0].body_json();
assert_eq!(body["connector_name"], "stripe");
assert_eq!(body["connector_account_details"]["api_key"], "sk_test");
}
#[tokio::test]
async fn retrieve_list_and_delete_hit_their_paths() {
let (client, mock) = client_with(vec![
Step::ok(CONNECTOR_JSON),
Step::ok("[]"),
Step::ok(CONNECTOR_JSON),
]);
let connectors = client.connectors();
let retrieved = connectors.retrieve("mer_1", "mca/1").await.unwrap();
assert_eq!(retrieved.status.as_deref(), Some("active"));
assert!(connectors.list("mer_1").await.unwrap().is_empty());
connectors.delete("mer_1", "mca_1").await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
("GET", "https://api.test/account/mer_1/connectors/mca%2F1")
);
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
("GET", "https://api.test/account/mer_1/connectors")
);
assert_eq!(
(seen[2].method, seen[2].url.as_str()),
("DELETE", "https://api.test/account/mer_1/connectors/mca_1")
);
}
#[tokio::test]
async fn update_posts_the_status_to_the_connector_path() {
let (client, mock) = client_with(vec![Step::ok(CONNECTOR_JSON)]);
let req = ConnectorUpdateRequest::new("payment_processor", "inactive").disabled(true);
client
.connectors()
.update("mer_1", "mca_1", &req)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/account/mer_1/connectors/mca_1"
);
let body = seen[0].body_json();
assert_eq!(body["status"], "inactive");
assert_eq!(body["disabled"], true);
}
#[tokio::test]
async fn clone_connector_posts_the_target_profile() {
let (client, mock) = client_with(vec![Step::ok(CONNECTOR_JSON)]);
let req = ConnectorCloneRequest::new("pro_2").connector_label("stripe_de");
client
.connectors()
.clone_connector("mer_1", "mca_1", &req)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/account/mer_1/connectors/mca_1/clone"
);
let body = seen[0].body_json();
assert_eq!(body["profile_id"], "pro_2");
assert_eq!(body["connector_label"], "stripe_de");
}
#[tokio::test]
async fn verify_posts_the_open_body() {
let (client, mock) = client_with(vec![Step::ok(r#"{"status":"ok"}"#)]);
client
.connectors()
.verify(&json!({"connector_name": "stripe"}))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(seen[0].url, "https://api.test/account/connectors/verify");
assert_eq!(seen[0].body_json()["connector_name"], "stripe");
}
#[tokio::test]
async fn register_webhook_omits_the_body_when_no_params() {
// The server only applies its `all_events` default to a bodyless call,
// so a mutation sending `{}` here must fail.
let (client, mock) = client_with(vec![Step::ok(
r#"{"webhook_registration_status":"success"}"#,
)]);
let registered = client
.connectors()
.register_webhook("mer_1", "mca_1", None)
.await
.unwrap();
assert_eq!(registered.webhook_registration_status, "success");
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/account/mer_1/connectors/webhooks/mca_1"
);
assert!(seen[0].body.is_none(), "expected no request body");
}
#[tokio::test]
async fn register_webhook_sends_a_specific_event_scope() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"webhook_registration_status":"success"}"#,
)]);
let req = ConnectorWebhookRegisterRequest::specific_event("payment_intent.succeeded")
.environment("sandbox");
client
.connectors()
.register_webhook("mer_1", "mca_1", Some(&req))
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
let body = seen[0].body_json();
assert_eq!(
body["event_type"]["specific_event"],
"payment_intent.succeeded"
);
assert_eq!(body["environment"], "sandbox");
}
#[tokio::test]
async fn webhook_and_payment_methods_get_their_paths() {
let (client, mock) = client_with(vec![
Step::ok(r#"{"connector":"stripe","webhooks":[{"connector_webhook_id":"we_1"}]}"#),
Step::ok("[]"),
]);
let connectors = client.connectors();
let listed = connectors.webhook("mer_1", "mca_1").await.unwrap();
assert_eq!(listed.connector, "stripe");
assert_eq!(listed.webhooks.len(), 1);
assert_eq!(listed.webhooks[0].connector_webhook_id, "we_1");
connectors.list_payment_methods().await.unwrap();
let seen = mock.seen.lock().unwrap();
assert_eq!(
(seen[0].method, seen[0].url.as_str()),
(
"GET",
"https://api.test/account/mer_1/connectors/webhooks/mca_1"
)
);
assert_eq!(
(seen[1].method, seen[1].url.as_str()),
("GET", "https://api.test/account/payment-methods")
);
}
/// Sync is a bodyless POST on its own path — a mutation dropping the
/// `/sync-events` suffix would silently re-register the endpoint instead,
/// minting a new signing secret.
#[tokio::test]
async fn sync_webhook_events_posts_to_the_sync_path() {
let (client, mock) = client_with(vec![Step::ok(
r#"{
"connector": "stripe",
"expected_events": ["refund.succeeded"],
"endpoints": [
{"connector_webhook_id":"we_1","updated":true,"added_events":["refund.succeeded"]}
]
}"#,
)]);
let synced = client
.connectors()
.sync_webhook_events("mer_1", "mca_1")
.await
.unwrap();
assert_eq!(synced.endpoints[0].added_events, ["refund.succeeded"]);
assert!(synced.endpoints[0].updated);
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/account/mer_1/connectors/webhooks/mca_1/sync-events"
);
assert!(seen[0].body.is_none(), "expected no request body");
}
#[tokio::test]
async fn register_stripe_payment_method_domains_sends_urls_and_environment() {
let (client, mock) = client_with(vec![Step::ok(
r#"{"environment":"sandbox","results":[{"url":"https://shop.example","status":"registered"}]}"#,
)]);
let req = StripePaymentMethodDomainsRegisterRequest::new(["https://shop.example"])
.environment("sandbox");
let registered = client
.connectors()
.register_stripe_payment_method_domains("mer_1", "mca_1", &req)
.await
.unwrap();
assert_eq!(registered.results[0].status.as_deref(), Some("registered"));
let seen = mock.seen.lock().unwrap();
assert_eq!(seen[0].method, "POST");
assert_eq!(
seen[0].url,
"https://api.test/account/mer_1/connectors/mca_1/stripe/payment-method-domains"
);
let body = seen[0].body_json();
assert_eq!(body["urls"][0], "https://shop.example");
assert_eq!(body["environment"], "sandbox");
}
/// The default request must not pin an environment — omitting it is what
/// lets the server apply its own `"live"` default.
#[tokio::test]
async fn register_stripe_payment_method_domains_omits_an_unset_environment() {
let (client, mock) = client_with(vec![Step::ok(r#"{"environment":"live","results":[]}"#)]);
let req = StripePaymentMethodDomainsRegisterRequest::new(["shop.example"]);
client
.connectors()
.register_stripe_payment_method_domains("mer_1", "mca_1", &req)
.await
.unwrap();
let seen = mock.seen.lock().unwrap();
let body = seen[0].body_json();
assert!(body.get("environment").is_none(), "{body}");
}
}