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
//! Buyer-side checkout models: the rail catalogs the hosted checkout renders,
//! the vault handshake that captures a card without it touching this process,
//! and the checkout-event receipt.
//!
//! These belong to the `/payment-link/*` surface, which a buyer's browser can
//! reach with a payment's client secret — see
//! [`crate::CheckoutSession`].
use serde::Deserialize;
use serde_json::Value;
use crate::core::models::product::ProductPriceTaxBehavior;
/// One rail the buyer can pick, from a vendor catalog.
///
/// `payment_method`, `payment_method_type` and `payment_method_data` are
/// echoed **verbatim** on the confirm call. Never derive them from
/// [`category`](Self::category): the mapping is not one-to-one, and guessing
/// it produces a confirm the connector rejects.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct CheckoutRail {
/// Vendor code. The wire field is `type`.
#[serde(rename = "type")]
pub rail_type: String,
/// Buyer-facing name of the rail.
pub display_name: String,
/// Tile grouping: `card_redirect`, `wallet`, `bank_transfer`,
/// `bank_redirect`, `voucher`, `gift_card`, `reward` or `cash`.
pub category: String,
/// Payment method to send on confirm.
pub payment_method: String,
/// Payment method type to send on confirm.
pub payment_method_type: String,
/// Pre-built `payment_method_data` body to echo on confirm; merge the
/// buyer's `billing` into it.
#[serde(default)]
pub payment_method_data: Value,
/// Minimum accepted amount, minor units of the catalog's currency.
#[serde(default)]
pub pmin: Option<i64>,
/// Maximum accepted amount, minor units of the catalog's currency.
#[serde(default)]
pub pmax: Option<i64>,
/// Country to forward for country-pinned vendors. `None` for universal
/// rails, where the buyer's billing country is the right value.
#[serde(default)]
pub pinned_country: Option<String>,
/// Sanitised inline SVG for the tile icon, when the merchant set one.
/// e-Payouts only.
#[serde(default)]
pub icon_svg: Option<String>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// The e-Payouts rail catalog for one country.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct EpayoutsMethodsResponse {
/// The country the catalog was built for.
pub country: String,
/// Currency the amounts in [`methods`](Self::methods) are denominated in.
pub currency: String,
/// The rails, in display order.
#[serde(default)]
pub methods: Vec<CheckoutRail>,
/// Lowercase ISO 3166-1 alpha-2 codes of every country the catalog can
/// mint some method for — what the pane's country picker offers.
#[serde(default)]
pub supported_countries: Vec<String>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// Receipt for a recorded buyer-side checkout event.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct RecordCheckoutEventResponse {
/// `false` when the event was deduplicated or the per-payment cap was
/// reached. Informational — a checkout must not branch on it.
pub recorded: bool,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// What a checkout page needs to stand up a VGS Collect form.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultCollectSessionResponse {
/// VGS tenant id (`tnt…`), the first argument to `VGSCollect.create`.
pub vault_id: String,
/// `sandbox` or `live`, the second argument to `VGSCollect.create`.
pub environment: String,
/// Inbound route the Collect form posts through, when one is configured.
#[serde(default)]
pub route_id: Option<String>,
/// Write-only bearer token for `form.createAliases({ access_token })`.
pub access_token: String,
/// Remaining lifetime in seconds.
pub expires_in: i64,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// The registered vault card, plus the one-shot token that pays with it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct VaultPaymentMethodResponse {
/// `None` for a guest checkout, which stores no payment method.
#[serde(default)]
pub payment_method_id: Option<String>,
/// Last four of the format-preserving alias — the real card's last four.
pub last4: String,
/// Card network, when the vault could determine it.
#[serde(default)]
pub card_network: Option<String>,
/// One-shot spendable token: send it on confirm as `payment_token`,
/// alongside `payment_method: "card"`.
pub payment_token: String,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// The hosted checkout's bootstrap payload for a one-time payment, from
/// `GET /payment-link/data/{merchant_id}/{payment_id}`.
///
/// One of three shapes, told apart by [`kind`](Self::kind) (the wire field
/// `type`): `checkout` while the payment is payable, `status` once it settled
/// or expired, and `addon_choice` while the buyer still picks the add-ons of a
/// catalog payment. All three are successful answers.
///
/// The fields every shape carries are typed; the rest of each shape (layout,
/// collection policy, provider-specific data) is kept in
/// [`extra`](Self::extra). `Debug` prints only the keys of `extra`, and
/// redacts the client secret, because the payload carries credentials.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct CheckoutDataResponse {
/// `checkout`, `status` or `addon_choice`.
#[serde(rename = "type")]
pub kind: String,
/// The payment.
pub payment_id: String,
/// The amount as a decimal string in **major** units of
/// [`currency`](Self::currency), e.g. `"38.02"`. Not minor units: this is
/// the display figure the checkout renders.
pub amount: String,
/// ISO 4217 currency code.
pub currency: String,
/// The payment's status.
#[serde(default)]
pub status: Option<String>,
/// Display name of the seller.
#[serde(default)]
pub merchant_name: Option<String>,
/// Address of the seller's logo.
#[serde(default)]
pub merchant_logo: Option<String>,
/// Surface theme token.
#[serde(default)]
pub theme: Option<String>,
/// Layout of the checkout form.
#[serde(default)]
pub sdk_layout: Option<String>,
/// Publishable key the checkout's payment calls authenticate with.
/// Present on `checkout` and `addon_choice`; on `status` only while an
/// open attempt can still be resumed.
#[serde(default)]
pub pub_key: Option<String>,
/// The payment's client secret. Present on `checkout` and
/// `addon_choice`; on `status` only while an open attempt can still be
/// resumed. Redacted in `Debug`.
#[serde(default)]
pub client_secret: Option<String>,
/// When the checkout session expires. Present on `checkout` and
/// `addon_choice`.
#[serde(default)]
pub session_expiry: Option<String>,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
impl std::fmt::Debug for CheckoutDataResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CheckoutDataResponse")
.field("kind", &self.kind)
.field("payment_id", &self.payment_id)
.field("amount", &self.amount)
.field("currency", &self.currency)
.field("status", &self.status)
.field("merchant_name", &self.merchant_name)
.field("theme", &self.theme)
.field("pub_key", &self.pub_key)
.field(
"client_secret",
&self.client_secret.as_ref().map(|_| "[redacted]"),
)
.field("session_expiry", &self.session_expiry)
.field("extra_keys", &self.extra.keys().collect::<Vec<_>>())
.finish()
}
}
/// The hosted checkout's bootstrap payload for a subscription, from
/// `GET /subscriptions/data/{merchant_id}/{subscription_id}`.
///
/// [`kind`](Self::kind) (the wire field `type`) is `subscription`. The buyer
/// confirms with [`pub_key`](Self::pub_key),
/// [`client_secret`](Self::client_secret) and
/// [`profile_id`](Self::profile_id). Both secrets are redacted in `Debug`.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionCheckoutResponse {
/// `subscription`.
#[serde(rename = "type")]
pub kind: String,
/// The subscription.
pub subscription_id: String,
/// The subscription's status.
pub status: String,
/// The shop the subscription belongs to.
pub profile_id: String,
/// Publishable key the confirm call authenticates with.
pub pub_key: String,
/// The buyer's session secret, passed back on confirm. Redacted in
/// `Debug`.
pub client_secret: String,
/// Secret the buyer confirms at the processor in the browser (a Stripe
/// Billing first-invoice payment). `None` for redirect-based processors
/// such as PayPal. Redacted in `Debug`.
#[serde(default)]
pub connector_client_secret: Option<String>,
/// Minor units, qualified by [`amount_source`](Self::amount_source): a
/// `plan_list_price` figure is not what the buyer will be charged.
pub amount: i64,
/// ISO 4217 currency code.
pub currency: String,
/// Where `amount` comes from.
pub amount_source: String,
/// `exclusive` when the billing processor adds tax on top of `amount`
/// (only a Creem list price can): show the amount as "plus tax"; the tax
/// depends on the buyer's country and is shown on the processor's page.
/// `None` from an older API, where it is never added.
#[serde(default)]
pub tax_behavior: Option<ProductPriceTaxBehavior>,
/// Billing interval unit.
#[serde(default)]
pub interval: Option<String>,
/// Number of interval units per cycle, when known.
#[serde(default)]
pub interval_count: Option<i64>,
/// The billing processor's plan or price id.
#[serde(default)]
pub item_price_id: Option<String>,
/// The billing processor, e.g. `paypal`. `None` while
/// [`method_choice_pending`](Self::method_choice_pending) is `true`.
#[serde(default)]
pub billing_connector: Option<String>,
/// `true` while the buyer has to pick a payment method first: read the
/// methods with `subscription_method_options` and bind one with
/// `select_subscription_method`.
pub method_choice_pending: bool,
/// Where the buyer goes after approval, when configured.
#[serde(default)]
pub return_url: Option<String>,
/// Display name: the branding seller name, else the shop name.
pub merchant_name: String,
/// Address of the seller's logo.
#[serde(default)]
pub merchant_logo: Option<String>,
/// Seller description.
#[serde(default)]
pub merchant_description: Option<String>,
/// Surface theme token.
pub theme: String,
/// Layout of the checkout form.
pub sdk_layout: String,
/// Whether the "Powered by" footer shows.
#[serde(default)]
pub branding_visibility: Option<bool>,
/// Any additional response fields not modeled above (the remaining
/// branding fields among them).
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
impl std::fmt::Debug for SubscriptionCheckoutResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SubscriptionCheckoutResponse")
.field("kind", &self.kind)
.field("subscription_id", &self.subscription_id)
.field("status", &self.status)
.field("profile_id", &self.profile_id)
.field("pub_key", &self.pub_key)
.field("client_secret", &"[redacted]")
.field(
"connector_client_secret",
&self.connector_client_secret.as_ref().map(|_| "[redacted]"),
)
.field("amount", &self.amount)
.field("currency", &self.currency)
.field("amount_source", &self.amount_source)
.field("interval", &self.interval)
.field("interval_count", &self.interval_count)
.field("item_price_id", &self.item_price_id)
.field("billing_connector", &self.billing_connector)
.field("method_choice_pending", &self.method_choice_pending)
.field("merchant_name", &self.merchant_name)
.field("theme", &self.theme)
.field("sdk_layout", &self.sdk_layout)
.field("extra_keys", &self.extra.keys().collect::<Vec<_>>())
.finish()
}
}
/// What a buyer coming back from the processor's checkout may read about
/// their subscription with the return token alone.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionReturnStatusResponse {
/// The subscription.
pub subscription_id: String,
/// The subscription's status.
pub status: String,
/// The processor has not reported the subscription yet: the buyer may
/// have paid, and its webhook is still on the way.
pub awaiting_processor: bool,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// One method a buyer may pick for a subscription waiting for the choice.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionMethodOption {
/// `card`, `paypal` or `processor_page`.
pub method: String,
/// The billing processor the method bills on, e.g. `paypal`.
pub billing_connector: String,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
/// The methods a buyer may pick for a subscription, in the shop's order,
/// judged by the shop's currencies, amount limits and sell-to policies for
/// the country of the request's own connection.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct SubscriptionMethodOptionsResponse {
/// The subscription.
pub subscription_id: String,
/// The methods on offer, in display order.
#[serde(default)]
pub options: Vec<SubscriptionMethodOption>,
/// Set when `options` is empty, saying why: `sell_to`, `currency`,
/// `amount` or `unavailable`.
#[serde(default)]
pub no_method_reason: Option<String>,
/// The country the buyer was judged from: an ISO 3166-1 alpha-2 code,
/// `unresolved` when their address names none, `unverified` when it could
/// not be trusted.
pub buyer_country: String,
/// Any additional response fields not modeled above.
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_rail_reads_its_vendor_code_from_the_wire_field_type() {
let rail: CheckoutRail = serde_json::from_str(
r#"{"type":"ideal","display_name":"iDEAL","category":"bank_redirect",
"payment_method":"bank_redirect","payment_method_type":"ideal",
"payment_method_data":{"bank_redirect":{"ideal":{}}},"pmin":100}"#,
)
.unwrap();
// The field is `type` on the wire and `rail_type` in Rust; a missing
// rename would fail the decode outright.
assert_eq!(rail.rail_type, "ideal");
assert_eq!(rail.payment_method_type, "ideal");
assert_eq!(rail.pmin, Some(100));
assert_eq!(rail.pinned_country, None);
assert!(rail.payment_method_data["bank_redirect"]["ideal"].is_object());
}
#[test]
fn a_subscription_checkout_says_whether_tax_is_added_on_top() {
let checkout: SubscriptionCheckoutResponse = serde_json::from_str(
r#"{"type":"subscription","subscription_id":"sub_1","status":"created",
"profile_id":"pro_1","pub_key":"pk_1","client_secret":"cs_1",
"amount":1000,"currency":"EUR","amount_source":"plan_list_price",
"tax_behavior":"exclusive","method_choice_pending":false,
"merchant_name":"Shop","theme":"light","sdk_layout":"tabs"}"#,
)
.unwrap();
assert_eq!(
checkout.tax_behavior,
Some(ProductPriceTaxBehavior::Exclusive)
);
}
#[test]
fn epayouts_carries_the_country_list() {
let response: EpayoutsMethodsResponse = serde_json::from_str(
r#"{"country":"de","currency":"EUR","methods":[],
"supported_countries":["de","fr"]}"#,
)
.unwrap();
assert_eq!(response.supported_countries, ["de", "fr"]);
}
#[test]
fn a_guest_vault_registration_has_no_payment_method_id() {
let response: VaultPaymentMethodResponse = serde_json::from_str(
r#"{"last4":"4242","payment_token":"tok_1","card_network":"Visa"}"#,
)
.unwrap();
assert_eq!(response.payment_method_id, None);
assert_eq!(response.payment_token, "tok_1");
}
}