From 2239fc542edb29e75f39c8d03a41e0f97139999d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tibor=20Heged=C5=B1s?= Date: Thu, 3 Dec 2026 16:48:05 +0100 Subject: [PATCH 1/3] Send the optional fields of the official SDK samples --- AGENTS.md | 1 + README.md | 7 +- src/dto.rs | 4 +- src/dto/auto_payment.rs | 55 ++++++++++ src/dto/card_storage.rs | 6 ++ src/dto/payment.rs | 65 ++++++++++++ src/dto/rtp.rs | 224 +++++++++++++++++++++++++++++++++++++++- src/lib.rs | 4 +- src/rtp.rs | 43 ++++---- tests/auto_payment.rs | 15 ++- tests/card_storage.rs | 4 +- tests/payment.rs | 45 ++++++++ tests/rtp.rs | 185 ++++++++++++++++++++++++++++++--- 13 files changed, 605 insertions(+), 53 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cfcceeb..14e3a57 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,7 @@ This repository is a Laravel Rust package: a library crate that integrates with - The PHP package is the reference for behavior and for the wire format. Request bodies carry the field names of the official SimplePay SDK samples; when porting a request, take the expected body from the PHP package's `tests/Unit/RequestPayloadTest.php`. - Keep the `SIMPLEPAY_*` environment variable names of the PHP package, so an existing `.env` keeps working. +- The official SimplePay SDK samples and documentation are the reference for fields the PHP package doesn't have. The port sends those too: `maySelectEmail`, `maySelectInvoice`, `maySelectDelivery`, `mobilApp`, `onlyCardReg`, `legacyCardRegister` and `legacyRecurring` on a start; `legacyRecurring` on a OneClick payment; `3DSecExternal`, `shippingCost`, `discount` and `pocket` on an auto payment; the optional fields and query filters of Request to Pay. - SimplePay signs the exact bytes of a body (HMAC-SHA384, base64). Serialize a body once, sign those bytes, and send the same bytes; verify signatures over the raw bytes received. - Do not port the PHP package's deprecated constructor parameters. diff --git a/README.md b/README.md index eb935b7..ca31b0a 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,8 @@ pub async fn examples(simplepay: &SimplePay, apple_token: &str, google_token: &s ```rust use netipar_simplepay::{ - Currency, Error, RtpDoRequest, RtpPayment, RtpQuery, RtpRefundRequest, RtpStartRequest, SimplePay, + Currency, Error, RtpDoRequest, RtpPayment, RtpQuery, RtpRef, RtpRefundRequest, RtpStartRequest, + SimplePay, }; pub async fn examples(simplepay: &SimplePay) -> Result<(), Error> { @@ -313,9 +314,9 @@ pub async fn examples(simplepay: &SimplePay) -> Result<(), Error> { )) .await?; - rtp.query(Currency::Huf, RtpQuery::OrderRef("RTP-001".to_owned())).await?; + rtp.query(Currency::Huf, &RtpQuery::order_ref("RTP-001").detailed(true)).await?; rtp.refund(&RtpRefundRequest::new(Currency::Huf, "102264132", 15)).await?; - rtp.reverse(Currency::Huf, "102264204").await?; + rtp.reverse(Currency::Huf, RtpRef::Transaction("102264204".to_owned())).await?; Ok(()) } diff --git a/src/dto.rs b/src/dto.rs index 30d7a9c..376c738 100644 --- a/src/dto.rs +++ b/src/dto.rs @@ -55,7 +55,7 @@ mod transaction_ref; pub use address::Address; pub use apple_pay::{ApplePayDoRequest, ApplePayStartRequest}; -pub use auto_payment::{AutoPaymentRequest, CardData}; +pub use auto_payment::{AutoPaymentRequest, CardData, ThreeDsExternal}; pub use back::BackResponse; pub use browser::BrowserData; pub use card_storage::{CardStorageDoRequest, RecurringRequest}; @@ -69,6 +69,6 @@ pub use query::QueryResponse; pub use recurring::Recurring; pub use redirect_urls::RedirectUrls; pub use refund::{RefundRequest, RefundResponse}; -pub use rtp::{RtpDoRequest, RtpPayment, RtpQuery, RtpRefundRequest, RtpStartRequest}; +pub use rtp::{RtpDoRequest, RtpPayment, RtpQuery, RtpRef, RtpRefundRequest, RtpStartRequest}; pub use status::StatusResponse; pub use transaction_ref::TransactionRef; diff --git a/src/dto/auto_payment.rs b/src/dto/auto_payment.rs index 2fc8ca5..e6dd824 100644 --- a/src/dto/auto_payment.rs +++ b/src/dto/auto_payment.rs @@ -44,6 +44,35 @@ impl CardData { } } +/// The result of a 3D Secure check your own system ran before the payment (with its own MPI), +/// sent as `3DSecExternal`. +/// +/// ``` +/// use netipar_simplepay::ThreeDsExternal; +/// +/// let result = ThreeDsExternal::new("01234567980123456789", "01", "ABCDEF"); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ThreeDsExternal { + xid: String, + eci: String, + cavv: String, +} + +impl ThreeDsExternal { + /// The result of a check: `xid` is the identifier generated for the authentication request, + /// `eci` is the security level of the transaction (the e-commerce indicator), and `cavv` is + /// the cryptogram that proves the authentication or its attempt. + #[must_use] + pub fn new(xid: impl Into, eci: impl Into, cavv: impl Into) -> Self { + Self { + xid: xid.into(), + eci: eci.into(), + cavv: cavv.into(), + } + } +} + /// A payment with card data your own page collected, for /// [`AutoPaymentService::auto`](crate::AutoPaymentService::auto). /// @@ -91,6 +120,20 @@ pub struct AutoPaymentRequest { delivery: Option
, #[serde(skip_serializing_if = "Option::is_none")] items: Option>, + #[serde(rename = "3DSecExternal", skip_serializing_if = "Option::is_none")] + three_ds_external: Option, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "rust_decimal::serde::float_option::serialize" + )] + shipping_cost: Option, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "rust_decimal::serde::float_option::serialize" + )] + discount: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pocket: Option, } impl AutoPaymentRequest { @@ -119,6 +162,10 @@ impl AutoPaymentRequest { invoice: None, delivery: None, items: None, + three_ds_external: None, + shipping_cost: None, + discount: None, + pocket: None, } } @@ -145,5 +192,13 @@ impl AutoPaymentRequest { invoice: Address, /// The delivery address. delivery: Address, + /// The result of a 3D Secure check your own system ran before the payment. + three_ds_external: ThreeDsExternal, + /// The shipping cost, which SimplePay adds to the amount to pay. + shipping_cost: Decimal, + /// The discount, which SimplePay takes off the amount to pay. + discount: Decimal, + /// The pocket of an OTP SZÉP card. SimplePay no longer needs it, and only accepts `09`. + pocket: String, } } diff --git a/src/dto/card_storage.rs b/src/dto/card_storage.rs index b6f18da..eb38d82 100644 --- a/src/dto/card_storage.rs +++ b/src/dto/card_storage.rs @@ -49,6 +49,8 @@ pub struct CardStorageDoRequest { customer: Option, #[serde(skip_serializing_if = "Option::is_none")] invoice: Option
, + #[serde(skip_serializing_if = "Option::is_none")] + legacy_recurring: Option, } impl CardStorageDoRequest { @@ -79,6 +81,7 @@ impl CardStorageDoRequest { browser: None, customer: None, invoice: None, + legacy_recurring: None, } } @@ -112,6 +115,9 @@ impl CardStorageDoRequest { customer: String, /// The billing address. invoice: Address, + /// Marks the payment as recurring. Send it when the card was registered with + /// `legacy_recurring`. Sent as `legacyRecurring`. + legacy_recurring: bool, } } diff --git a/src/dto/payment.rs b/src/dto/payment.rs index 1ac0cd1..8ddc39d 100644 --- a/src/dto/payment.rs +++ b/src/dto/payment.rs @@ -30,6 +30,8 @@ pub struct PaymentRequest { #[serde(serialize_with = "rust_decimal::serde::float::serialize")] total: Decimal, order_ref: String, + // Left out when empty: `may_select_email` lets the customer give it on the payment page. + #[serde(skip_serializing_if = "String::is_empty")] customer_email: String, language: String, url: String, @@ -68,6 +70,27 @@ pub struct PaymentRequest { customer: Option, #[serde(skip_serializing_if = "Option::is_none")] urls: Option, + #[serde(skip_serializing_if = "Option::is_none")] + may_select_email: Option, + #[serde(skip_serializing_if = "Option::is_none")] + may_select_invoice: Option, + #[serde(skip_serializing_if = "Option::is_none")] + may_select_delivery: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + mobil_app: Option, + #[serde(skip_serializing_if = "Option::is_none")] + only_card_reg: Option, + #[serde(skip_serializing_if = "Option::is_none")] + legacy_card_register: Option, + #[serde(skip_serializing_if = "Option::is_none")] + legacy_recurring: Option, +} + +/// The `mobilApp` object of a start request. +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +struct MobileApp { + simple_app_back_url: String, } impl PaymentRequest { @@ -105,6 +128,13 @@ impl PaymentRequest { discount: None, customer: None, urls: None, + may_select_email: None, + may_select_invoice: None, + may_select_delivery: None, + mobil_app: None, + only_card_reg: None, + legacy_card_register: None, + legacy_recurring: None, } } @@ -129,9 +159,44 @@ impl PaymentRequest { self } + /// Lets the customer give a delivery address on the payment page, when you don't know it. + /// List the two-letter codes of every country you deliver to; the customer chooses from them. + #[must_use] + pub fn may_select_delivery( + mut self, + countries: impl IntoIterator>, + ) -> Self { + self.may_select_delivery = Some(countries.into_iter().map(Into::into).collect()); + self + } + + /// The deeplink where the Simple application sends the customer back to your mobile + /// application, sent as `mobilApp.simpleAppBackUrl`. + #[must_use] + pub fn mobile_app_back_url(mut self, url: impl Into) -> Self { + self.mobil_app = Some(MobileApp { + simple_app_back_url: url.into(), + }); + self + } + setters! { /// How long the payment stays open, instead of the configured timeout. timeout: Duration, + /// Lets the customer give their email address on the payment page, when you don't know + /// it. Start the request with an empty email address then. + may_select_email: bool, + /// Lets the customer give their billing data on the payment page, when you don't know it. + may_select_invoice: bool, + /// Marks a payment whose only purpose is to register the card: you won't charge its + /// amount. Sent as `onlyCardReg`. + only_card_reg: bool, + /// Registers the card the legacy way, for one-off payments you start later with or + /// without the customer. Sent as `legacyCardRegister`. + legacy_card_register: bool, + /// Registers the card the legacy way, for payments that repeat regularly. Sent as + /// `legacyRecurring`. + legacy_recurring: bool, /// The billing address. invoice: Address, /// The delivery address. diff --git a/src/dto/rtp.rs b/src/dto/rtp.rs index 2069288..dd448ce 100644 --- a/src/dto/rtp.rs +++ b/src/dto/rtp.rs @@ -27,6 +27,8 @@ pub struct RtpStartRequest { #[serde(serialize_with = "rust_decimal::serde::float::serialize")] total: Decimal, order_ref: String, + // Left out when empty: `may_select_email` lets the customer give it on the payment page. + #[serde(skip_serializing_if = "String::is_empty")] customer_email: String, url: String, customer: String, @@ -39,11 +41,29 @@ pub struct RtpStartRequest { #[serde(skip_serializing_if = "Option::is_none")] invoice: Option
, #[serde(skip_serializing_if = "Option::is_none")] + delivery: Option
, + #[serde(skip_serializing_if = "Option::is_none")] items: Option>, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "rust_decimal::serde::float_option::serialize" + )] + shipping_cost: Option, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "rust_decimal::serde::float_option::serialize" + )] + discount: Option, #[serde(skip_serializing_if = "Option::is_none")] additional_info: Option, #[serde(skip_serializing_if = "Option::is_none")] urls: Option, + #[serde(skip_serializing_if = "Option::is_none")] + may_select_email: Option, + #[serde(skip_serializing_if = "Option::is_none")] + may_select_invoice: Option, + #[serde(skip_serializing_if = "Option::is_none")] + may_select_delivery: Option>, } impl RtpStartRequest { @@ -72,9 +92,15 @@ impl RtpStartRequest { deadline: None, timeout: None, invoice: None, + delivery: None, items: None, + shipping_cost: None, + discount: None, additional_info: None, urls: None, + may_select_email: None, + may_select_invoice: None, + may_select_delivery: None, } } @@ -85,6 +111,17 @@ impl RtpStartRequest { self } + /// Lets the customer give a delivery address on the payment page, when you don't know it. + /// List the two-letter codes of every country you deliver to; the customer chooses from them. + #[must_use] + pub fn may_select_delivery( + mut self, + countries: impl IntoIterator>, + ) -> Self { + self.may_select_delivery = Some(countries.into_iter().map(Into::into).collect()); + self + } + default_setters! { /// The two-letter code of the customer's language. language: String, @@ -97,11 +134,22 @@ impl RtpStartRequest { timeout: Duration, /// The billing address. invoice: Address, + /// The delivery address. + delivery: Address, + /// The shipping cost, which SimplePay adds to the amount to pay. + shipping_cost: Decimal, + /// The discount, which SimplePay takes off the amount to pay. + discount: Decimal, /// The announcement shown with the bank transfer. additional_info: String, /// A URL for each outcome, including `pending`. SimplePay ignores the single `url` when /// they are set. urls: RedirectUrls, + /// Lets the customer give their email address on the payment page, when you don't know + /// it. Start the request with an empty email address then. + may_select_email: bool, + /// Lets the customer give their billing data on the payment page, when you don't know it. + may_select_invoice: bool, } } @@ -128,6 +176,22 @@ pub struct RtpPayment { additional_info: Option, #[serde(skip_serializing_if = "Option::is_none")] customer_bank_account: Option, + #[serde(skip_serializing_if = "Option::is_none")] + items: Option>, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "rust_decimal::serde::float_option::serialize" + )] + shipping_cost: Option, + #[serde( + skip_serializing_if = "Option::is_none", + serialize_with = "rust_decimal::serde::float_option::serialize" + )] + discount: Option, + #[serde(skip_serializing_if = "Option::is_none")] + invoice: Option
, + #[serde(skip_serializing_if = "Option::is_none")] + delivery: Option
, } impl RtpPayment { @@ -148,9 +212,21 @@ impl RtpPayment { deadline: None, additional_info: None, customer_bank_account: None, + items: None, + shipping_cost: None, + discount: None, + invoice: None, + delivery: None, } } + /// The lines of the order. + #[must_use] + pub fn items(mut self, items: impl IntoIterator) -> Self { + self.items = Some(items.into_iter().collect()); + self + } + default_setters! { /// The two-letter code of the customer's language. language: String, @@ -164,6 +240,14 @@ impl RtpPayment { additional_info: String, /// The customer's bank account number, when you know it. customer_bank_account: String, + /// The shipping cost, which SimplePay adds to the amount to pay. + shipping_cost: Decimal, + /// The discount, which SimplePay takes off the amount to pay. + discount: Decimal, + /// The billing address. + invoice: Address, + /// The delivery address. + delivery: Address, } } @@ -224,7 +308,10 @@ impl RtpDoRequest { #[serde(rename_all = "camelCase")] pub struct RtpRefundRequest { pub(crate) currency: Currency, - transaction_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + transaction_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + order_ref: Option, #[serde( rename = "refundTotal", serialize_with = "rust_decimal::serde::float::serialize" @@ -238,7 +325,7 @@ pub struct RtpRefundRequest { } impl RtpRefundRequest { - /// Refunds `amount` of the transaction. + /// Refunds `amount` of the transaction with the given SimplePay identifier. #[must_use] pub fn new( currency: Currency, @@ -247,7 +334,25 @@ impl RtpRefundRequest { ) -> Self { Self { currency, - transaction_id: transaction_id.into(), + transaction_id: Some(transaction_id.into()), + order_ref: None, + amount: amount.into(), + original_total: None, + } + } + + /// Refunds `amount` of the transaction with the given order reference of yours, as the + /// official SDK sample offers instead of the identifier. + #[must_use] + pub fn for_order( + currency: Currency, + order_ref: impl Into, + amount: impl Into, + ) -> Self { + Self { + currency, + transaction_id: None, + order_ref: Some(order_ref.into()), amount: amount.into(), original_total: None, } @@ -259,9 +364,10 @@ impl RtpRefundRequest { } } -/// What a Request to Pay query looks for. +/// Names a payment request, or a batch of them, for +/// [`RtpService::reverse`](crate::RtpService::reverse). #[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub enum RtpQuery { +pub enum RtpRef { /// The transaction with this SimplePay identifier. Transaction(String), /// The transaction with this order reference of yours. @@ -269,3 +375,111 @@ pub enum RtpQuery { /// Every transaction of the batch with this package reference. Package(String), } + +/// What a Request to Pay query looks for, with [`RtpService::query`](crate::RtpService::query). +/// +/// ``` +/// use netipar_simplepay::RtpQuery; +/// +/// // One transaction, with its details and its refunds. +/// let query = RtpQuery::transaction("168867693").detailed(true).refunds(true); +/// +/// // Every payment request sent to a customer in a period. +/// let query = RtpQuery::customer_email("customer@example.com") +/// .from("2026-12-01T00:00:00+01:00") +/// .until("2026-12-31T23:59:59+01:00"); +/// ``` +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RtpQuery { + #[serde(skip_serializing_if = "Vec::is_empty")] + transaction_ids: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + order_refs: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + package_ref: Option, + #[serde(skip_serializing_if = "Option::is_none")] + customer_email: Option, + #[serde(skip_serializing_if = "Option::is_none")] + customer_bank_account: Option, + #[serde(skip_serializing_if = "Option::is_none")] + from: Option, + #[serde(skip_serializing_if = "Option::is_none")] + until: Option, + #[serde(skip_serializing_if = "Option::is_none")] + detailed: Option, + #[serde(skip_serializing_if = "Option::is_none")] + refunds: Option, +} + +impl RtpQuery { + fn empty() -> Self { + Self { + transaction_ids: Vec::new(), + order_refs: Vec::new(), + package_ref: None, + customer_email: None, + customer_bank_account: None, + from: None, + until: None, + detailed: None, + refunds: None, + } + } + + /// The transaction with this SimplePay identifier. + #[must_use] + pub fn transaction(transaction_id: impl Into) -> Self { + Self { + transaction_ids: vec![transaction_id.into()], + ..Self::empty() + } + } + + /// The transaction with this order reference of yours. + #[must_use] + pub fn order_ref(order_ref: impl Into) -> Self { + Self { + order_refs: vec![order_ref.into()], + ..Self::empty() + } + } + + /// Every transaction of the batch with this package reference. + #[must_use] + pub fn package(package_ref: impl Into) -> Self { + Self { + package_ref: Some(package_ref.into()), + ..Self::empty() + } + } + + /// The transactions of the customer with this email address. + #[must_use] + pub fn customer_email(email: impl Into) -> Self { + Self { + customer_email: Some(email.into()), + ..Self::empty() + } + } + + /// The transactions of the customer with this bank account number. + #[must_use] + pub fn customer_bank_account(account: impl Into) -> Self { + Self { + customer_bank_account: Some(account.into()), + ..Self::empty() + } + } + + setters! { + /// Only transactions from this ISO 8601 moment on. + from: String, + /// Only transactions until this ISO 8601 moment. + until: String, + /// Whether the response carries the details of each transaction. + detailed: bool, + /// Whether the response carries the refunds started on each transaction. + refunds: bool, + } +} diff --git a/src/lib.rs b/src/lib.rs index 04fbe7b..2827f32 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,8 +25,8 @@ pub use dto::{ BrowserData, CardData, CardStorageDoRequest, EamStartRequest, FinishRequest, FinishResponse, GooglePayButtonConfig, GooglePayDoRequest, GooglePayResponse, IpnMessage, Item, PaymentRequest, PaymentResponse, QueryResponse, Recurring, RecurringRequest, RedirectUrls, RefundRequest, - RefundResponse, RtpDoRequest, RtpPayment, RtpQuery, RtpRefundRequest, RtpStartRequest, - StatusResponse, TransactionRef, + RefundResponse, RtpDoRequest, RtpPayment, RtpQuery, RtpRef, RtpRefundRequest, RtpStartRequest, + StatusResponse, ThreeDsExternal, TransactionRef, }; pub use enums::{BackEvent, Currency, PaymentMethod, PaymentStatus, TransactionType}; pub use error::{ApiError, Error}; diff --git a/src/rtp.rs b/src/rtp.rs index 8d88dff..c8dec7e 100644 --- a/src/rtp.rs +++ b/src/rtp.rs @@ -2,8 +2,8 @@ use serde_json::{Map, Value}; use crate::wire::{default_deadline, object, random_hex}; use crate::{ - Currency, Error, PaymentResponse, RtpDoRequest, RtpQuery, RtpRefundRequest, RtpStartRequest, - SimplePay, + Currency, Error, PaymentResponse, RtpDoRequest, RtpQuery, RtpRef, RtpRefundRequest, + RtpStartRequest, SimplePay, }; /// Request to Pay, reached through [`SimplePay::rtp`]. @@ -70,27 +70,17 @@ impl<'a> RtpService<'a> { self.simplepay.post("/rtp/do", body, request.currency).await } - /// Reads payment requests: one by its identifier or order reference, or a whole batch. - /// Returns SimplePay's response as it is. + /// Reads payment requests: one by its identifier or order reference, a whole batch, or a + /// customer's. Returns SimplePay's response as it is. /// /// # Errors /// /// Returns an [`Error`] when the currency has no merchant account, the request fails, or /// SimplePay answers with error codes. - pub async fn query(&self, currency: Currency, query: RtpQuery) -> Result { - let mut body = Map::new(); - - match query { - RtpQuery::Transaction(id) => body.insert("transactionIds".to_owned(), vec![id].into()), - RtpQuery::OrderRef(order_ref) => { - body.insert("orderRefs".to_owned(), vec![order_ref].into()) - } - RtpQuery::Package(package_ref) => { - body.insert("packageRef".to_owned(), package_ref.into()) - } - }; - - self.simplepay.post("/rtp/query", body, currency).await + pub async fn query(&self, currency: Currency, query: &RtpQuery) -> Result { + self.simplepay + .post("/rtp/query", object(query)?, currency) + .await } /// Refunds all or part of a paid request. Returns SimplePay's response as it is. @@ -105,17 +95,26 @@ impl<'a> RtpService<'a> { .await } - /// Reverses a payment request that hasn't completed yet. Returns SimplePay's response as it - /// is. + /// Reverses a payment request the customer hasn't paid yet, or every such request of a + /// batch. Returns SimplePay's response as it is. + /// + /// If the customer pays after the reversal, SimplePay transfers the amount back. /// /// # Errors /// /// Returns an [`Error`] when the currency has no merchant account, the request fails, or /// SimplePay answers with error codes. - pub async fn reverse(&self, currency: Currency, transaction_id: &str) -> Result { + pub async fn reverse(&self, currency: Currency, payment: RtpRef) -> Result { let mut body = Map::new(); body.insert("currency".to_owned(), currency.as_str().into()); - body.insert("transactionId".to_owned(), transaction_id.into()); + + match payment { + RtpRef::Transaction(id) => body.insert("transactionId".to_owned(), id.into()), + RtpRef::OrderRef(order_ref) => body.insert("orderRef".to_owned(), order_ref.into()), + RtpRef::Package(package_ref) => { + body.insert("packageRef".to_owned(), package_ref.into()) + } + }; self.simplepay.post("/rtp/reverse", body, currency).await } diff --git a/tests/auto_payment.rs b/tests/auto_payment.rs index 0fc211b..bdc3320 100644 --- a/tests/auto_payment.rs +++ b/tests/auto_payment.rs @@ -5,7 +5,7 @@ use laravel::http::client; use laravel::testing::prelude::*; use netipar_simplepay::{ Address, AutoPaymentRequest, BrowserData, CardData, Currency, Item, SimplePay, SimplePayConfig, - TransactionType, + ThreeDsExternal, TransactionType, }; mod common; @@ -121,7 +121,11 @@ async fn an_auto_payment_sends_the_addresses_and_the_items(app: Application) { "4024", "Side Street 2", )) - .items([Item::new("Product", 100)]), + .items([Item::new("Product", 100)]) + .three_ds_external(ThreeDsExternal::new("01234567980123456789", "01", "ABCDEF")) + .shipping_cost(20) + .discount(10) + .pocket("09"), ) .await .unwrap(); @@ -129,6 +133,13 @@ async fn an_auto_payment_sends_the_addresses_and_the_items(app: Application) { let (_, body) = sent(&http); assert_eq!(body["customer"], "Customer Name"); + assert_eq!( + body["3DSecExternal"], + json!({"xid": "01234567980123456789", "eci": "01", "cavv": "ABCDEF"}) + ); + assert_eq!(body["shippingCost"], 20.0); + assert_eq!(body["discount"], 10.0); + assert_eq!(body["pocket"], "09"); assert_eq!(body["invoice"]["city"], "Budapest"); assert_eq!(body["delivery"]["city"], "Debrecen"); assert_eq!( diff --git a/tests/card_storage.rs b/tests/card_storage.rs index 631a995..8e39cd0 100644 --- a/tests/card_storage.rs +++ b/tests/card_storage.rs @@ -115,7 +115,8 @@ async fn a_one_click_payment_sends_its_other_optional_fields(app: Application) { "1111", "Main Street 1", )) - .items([Item::new("Product", 1500)]), + .items([Item::new("Product", 1500)]) + .legacy_recurring(true), ) .await .unwrap(); @@ -143,6 +144,7 @@ async fn a_one_click_payment_sends_its_other_optional_fields(app: Application) { }, "url": "https://example.com/back", "items": [{"title": "Product", "amount": 1, "price": 1500.0}], + "legacyRecurring": true, "sdkVersion": SDK_VERSION, }) ); diff --git a/tests/payment.rs b/tests/payment.rs index 1df32d2..27fd584 100644 --- a/tests/payment.rs +++ b/tests/payment.rs @@ -143,6 +143,13 @@ fn request_with_every_option() -> PaymentRequest { ) .pending("https://example.com/payment/pending"), ) + .may_select_email(true) + .may_select_invoice(true) + .may_select_delivery(["HU", "AT"]) + .mobile_app_back_url("myAppS01234://payment/123456789") + .only_card_reg(true) + .legacy_card_register(true) + .legacy_recurring(true) } #[laravel::test(app = create_with_route)] @@ -232,10 +239,48 @@ async fn start_sends_every_optional_field_under_its_official_name(app: Applicati "timeout": "https://example.com/payment/timeout", "pending": "https://example.com/payment/pending", }, + "maySelectEmail": true, + "maySelectInvoice": true, + "maySelectDelivery": ["HU", "AT"], + "mobilApp": {"simpleAppBackUrl": "myAppS01234://payment/123456789"}, + "onlyCardReg": true, + "legacyCardRegister": true, + "legacyRecurring": true, }) ); } +#[laravel::test(app = create)] +async fn start_leaves_out_an_email_address_the_customer_gives_on_the_payment_page( + app: Application, +) { + let http = client::fake().with( + "*/v2/start", + signed( + &json!({"transactionId": 12345, "paymentUrl": "https://example.com/pay"}), + HUF_KEY, + ), + ); + let simplepay = app.resolve::().await; + + let request = PaymentRequest::new( + Currency::Huf, + 1500, + "ORD-001", + "", + "HU", + "https://example.com/payment/back", + ) + .may_select_email(true); + + simplepay.payment().start(&request).await.unwrap(); + + let (_, body) = sent(&http); + + assert_eq!(body["maySelectEmail"], true); + assert!(body.get("customerEmail").is_none(), "{body}"); +} + #[laravel::test(app = create)] async fn start_reads_a_text_identifier_and_the_recurring_tokens(app: Application) { let _http = client::fake().with( diff --git a/tests/rtp.rs b/tests/rtp.rs index 9321d0f..690c041 100644 --- a/tests/rtp.rs +++ b/tests/rtp.rs @@ -6,8 +6,8 @@ use std::time::Duration; use laravel::http::client; use laravel::testing::prelude::*; use netipar_simplepay::{ - Address, Currency, Item, RedirectUrls, RtpDoRequest, RtpPayment, RtpQuery, RtpRefundRequest, - RtpStartRequest, SimplePay, + Address, Currency, Item, RedirectUrls, RtpDoRequest, RtpPayment, RtpQuery, RtpRef, + RtpRefundRequest, RtpStartRequest, SimplePay, }; mod common; @@ -280,15 +280,19 @@ async fn a_query_names_what_it_looks_for_without_the_currency(app: Application) let simplepay = app.resolve::().await; let rtp = simplepay.rtp(); - rtp.query(Currency::Huf, RtpQuery::Transaction("168867693".to_owned())) - .await - .unwrap(); - rtp.query(Currency::Huf, RtpQuery::OrderRef("RTP-1".to_owned())) - .await - .unwrap(); - rtp.query(Currency::Huf, RtpQuery::Package("PKG-1".to_owned())) - .await - .unwrap(); + for query in [ + RtpQuery::transaction("168867693"), + RtpQuery::order_ref("RTP-1"), + RtpQuery::package("PKG-1"), + RtpQuery::customer_email("test@example.com") + .from("2026-12-01T00:00:00+01:00") + .until("2026-12-31T23:59:59+01:00"), + RtpQuery::customer_bank_account("002000041111111111111111") + .detailed(true) + .refunds(true), + ] { + rtp.query(Currency::Huf, &query).await.unwrap(); + } let bodies: Vec<_> = sent_all(&http).into_iter().map(|(_, body)| body).collect(); @@ -298,6 +302,20 @@ async fn a_query_names_what_it_looks_for_without_the_currency(app: Application) json!({"merchant": "TEST_HUF_MERCHANT", "transactionIds": ["168867693"], "sdkVersion": SDK_VERSION}), json!({"merchant": "TEST_HUF_MERCHANT", "orderRefs": ["RTP-1"], "sdkVersion": SDK_VERSION}), json!({"merchant": "TEST_HUF_MERCHANT", "packageRef": "PKG-1", "sdkVersion": SDK_VERSION}), + json!({ + "merchant": "TEST_HUF_MERCHANT", + "customerEmail": "test@example.com", + "from": "2026-12-01T00:00:00+01:00", + "until": "2026-12-31T23:59:59+01:00", + "sdkVersion": SDK_VERSION, + }), + json!({ + "merchant": "TEST_HUF_MERCHANT", + "customerBankAccount": "002000041111111111111111", + "detailed": true, + "refunds": true, + "sdkVersion": SDK_VERSION, + }), ] ); } @@ -329,16 +347,44 @@ async fn a_refund_sends_the_official_refund_fields(app: Application) { } #[laravel::test(app = create)] -async fn a_reverse_names_the_transaction_and_the_currency(app: Application) { +async fn a_reverse_names_the_payment_and_the_currency(app: Application) { let http = client::fake().with( "sandbox.simplepay.hu/payment/rtp/reverse", accepted(EUR_KEY), ); + let simplepay = app.resolve::().await; + let rtp = simplepay.rtp(); + + for payment in [ + RtpRef::Transaction("102264204".to_owned()), + RtpRef::OrderRef("RTP-1".to_owned()), + RtpRef::Package("PKG-1".to_owned()), + ] { + rtp.reverse(Currency::Eur, payment).await.unwrap(); + } + + let bodies: Vec<_> = sent_all(&http).into_iter().map(|(_, body)| body).collect(); + let eur = |key: &str, value: &str| json!({"merchant": "TEST_EUR_MERCHANT", "currency": "EUR", key: value, "sdkVersion": SDK_VERSION}); + + assert_eq!( + bodies, + [ + eur("transactionId", "102264204"), + eur("orderRef", "RTP-1"), + eur("packageRef", "PKG-1"), + ] + ); +} + +#[laravel::test(app = create)] +async fn a_refund_can_name_the_order_instead_of_the_transaction(app: Application) { + let http = client::fake().with("*/rtp/refund", accepted(HUF_KEY)); + let simplepay = app.resolve::().await; simplepay .rtp() - .reverse(Currency::Eur, "102264204") + .refund(&RtpRefundRequest::for_order(Currency::Huf, "RTP-1", 15)) .await .unwrap(); @@ -347,10 +393,117 @@ async fn a_reverse_names_the_transaction_and_the_currency(app: Application) { assert_eq!( body, json!({ - "merchant": "TEST_EUR_MERCHANT", - "currency": "EUR", - "transactionId": "102264204", + "merchant": "TEST_HUF_MERCHANT", + "currency": "HUF", + "orderRef": "RTP-1", + "refundTotal": 15.0, + "sdkVersion": SDK_VERSION, + }) + ); +} + +#[laravel::test(app = create)] +async fn a_start_and_a_batch_send_the_optional_fields_of_the_official_samples(app: Application) { + let http = client::fake() + .with("*/rtp/start", accepted(HUF_KEY)) + .with("*/rtp/do", accepted(HUF_KEY)); + + let simplepay = app.resolve::().await; + let rtp = simplepay.rtp(); + let delivery = || Address::new("Customer Name", "hu", "Debrecen", "4024", "Side Street 2"); + + rtp.start( + &RtpStartRequest::new( + Currency::Huf, + 5000, + "RTP-1", + "", + "https://example.com/back", + "Customer Name", + ) + .deadline("2026-12-31T12:00:00+01:00") + .shipping_cost(20) + .discount(10) + .delivery(delivery()) + .may_select_email(true) + .may_select_invoice(true) + .may_select_delivery(["HU", "DE"]), + ) + .await + .unwrap(); + + rtp.do_payments( + &RtpDoRequest::new( + Currency::Huf, + [RtpPayment::new("RTP-2", 510, "b@example.com", "Customer B") + .deadline("2026-12-31T12:00:00+01:00") + .items([Item::new("Product", 100).quantity(5).tax(27)]) + .shipping_cost(50) + .discount(40) + .invoice(Address::new( + "Customer B", + "hu", + "Budapest", + "1111", + "Main Street 1", + )) + .delivery(delivery())], + ) + .package_ref("PKG-2"), + ) + .await + .unwrap(); + + let bodies: Vec<_> = sent_all(&http).into_iter().map(|(_, body)| body).collect(); + let delivery = json!({ + "name": "Customer Name", + "country": "hu", + "city": "Debrecen", + "zip": "4024", + "address": "Side Street 2", + }); + + assert_eq!( + bodies[0], + json!({ + "merchant": "TEST_HUF_MERCHANT", + "orderRef": "RTP-1", + "currency": "HUF", + "total": 5000.0, + "customer": "Customer Name", + "url": "https://example.com/back", + "language": "HU", + "deadline": "2026-12-31T12:00:00+01:00", + "shippingCost": 20.0, + "discount": 10.0, + "delivery": delivery, + "maySelectEmail": true, + "maySelectInvoice": true, + "maySelectDelivery": ["HU", "DE"], "sdkVersion": SDK_VERSION, }) ); + assert_eq!( + bodies[1]["transactions"], + json!([{ + "orderRef": "RTP-2", + "total": 510.0, + "currency": "HUF", + "customerEmail": "b@example.com", + "customer": "Customer B", + "deadline": "2026-12-31T12:00:00+01:00", + "language": "HU", + "items": [{"title": "Product", "amount": 5, "price": 100.0, "tax": 27.0}], + "shippingCost": 50.0, + "discount": 40.0, + "invoice": { + "name": "Customer B", + "country": "hu", + "city": "Budapest", + "zip": "1111", + "address": "Main Street 1", + }, + "delivery": delivery, + }]) + ); } From f8da098d522c85a66fa2db1452231a5fd3ab3d57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tibor=20Heged=C5=B1s?= Date: Thu, 3 Dec 2026 16:49:59 +0100 Subject: [PATCH 2/3] Hide the identifier and cryptogram of an external 3DS check --- AGENTS.md | 2 +- src/client.rs | 6 +++++- src/dto/auto_payment.rs | 12 +++++++----- tests/auto_payment.rs | 11 ++++++++++- 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 14e3a57..2fa05cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ This repository is a Laravel Rust package: a library crate that integrates with - `payment().handle_ipn` and `handle_back` do the verification for a route of the application's own. - `do_google_pay` turns error code 3004 with a `redirectUrl` into a normal `GooglePayResponse`; the other calls return it as `Error::Api`, as the PHP package does. - `src/client.rs`: the internal client. It adds `merchant`, `salt` and `sdkVersion` (`SDK_VERSION`) to a body, serializes it once, signs those bytes and sends them through a dedicated `laravel::http::client::Client`, so `client::fake()` intercepts the calls in tests. It turns an HTTP error status into `Error::Http`, requires a `Signature` on the response and verifies it (stricter than the PHP package, which accepts an unsigned response), and turns a non-empty `errorCodes` list into `Error::Api`. It logs requests and responses on the `netipar_simplepay` tracing target with card data and tokens masked. -- `src/dto/`: request and response bodies. A request has private fields, a `new` with the required values in the PHP constructor's order, and chainable setters (`setters!`) for the optional ones; it serializes to the official field names. A value a request computes at send time (`timeout`, `deadline`, a generated `packageRef`) is added by the service, not by the DTO. `BrowserData` is the exception to the builder shape: its eight required values make a struct literal clearer. Secrets (`cardSecret`, tokens, card data) are held in `dto::secret::Secret`, so a request's `Debug` output never shows them. A response is a `#[non_exhaustive]` struct with public fields. Amounts are `rust_decimal::Decimal`, sent as JSON numbers with the opt-in `rust_decimal::serde::float` serializers (never enable `serde-float` or other crate-wide serde features: Cargo would apply them to the application too). Identifiers that SimplePay sends as a number or as text are read with `dto::lenient`. +- `src/dto/`: request and response bodies. A request has private fields, a `new` with the required values in the PHP constructor's order, and chainable setters (`setters!`) for the optional ones; it serializes to the official field names. A value a request computes at send time (`timeout`, `deadline`, a generated `packageRef`) is added by the service, not by the DTO. `BrowserData` is the exception to the builder shape: its eight required values make a struct literal clearer. Secrets (`cardSecret`, tokens, card data, the identifier and cryptogram of an external 3DS check) are held in `dto::secret::Secret`, so a request's `Debug` output never shows them; the same fields are in the client's `MASKED_KEYS`, so the log never shows them either. A new secret field needs both. A response is a `#[non_exhaustive]` struct with public fields. Amounts are `rust_decimal::Decimal`, sent as JSON numbers with the opt-in `rust_decimal::serde::float` serializers (never enable `serde-float` or other crate-wide serde features: Cargo would apply them to the application too). Identifiers that SimplePay sends as a number or as text are read with `dto::lenient`. - `tests/`: one file per area, through the public API. `tests/provider.rs` builds a host application with `for_testing`; The tests of the API calls (`payment`, `card_storage`, `auto_payment`, `wallets`, `rtp`) fake the SimplePay API with signed responses and compare each sent body, as a whole, with the PHP package's; their shared helpers are in `tests/common/mod.rs`. The expected signatures and messages come from the PHP package and from SimplePay's developer documentation. ## Release diff --git a/src/client.rs b/src/client.rs index 799c253..1e76157 100644 --- a/src/client.rs +++ b/src/client.rs @@ -12,7 +12,7 @@ pub(crate) const SDK_VERSION: &str = "SimplePay_Rust_SDK_2.1_Laravel"; const LOG_TARGET: &str = "netipar_simplepay"; /// Body fields whose values never reach the log. -const MASKED_KEYS: [&str; 8] = [ +const MASKED_KEYS: [&str; 10] = [ "number", "expiry", "cvc", @@ -21,6 +21,8 @@ const MASKED_KEYS: [&str; 8] = [ "tokens", "googlePayToken", "applePayToken", + "xid", + "cavv", ]; #[derive(Debug, Clone)] @@ -159,6 +161,7 @@ mod tests { "token": "SPT-1", "tokens": ["SPT-1", "SPT-2"], "cardData": {"number": "4908366099900425", "expiry": "0130", "cvc": "123", "holder": "Test Holder"}, + "3DSecExternal": {"xid": "01234567980123456789", "eci": "01", "cavv": "ABCDEF"}, "items": [{"title": "Product", "applePayToken": "apple", "googlePayToken": "google"}], }); @@ -170,6 +173,7 @@ mod tests { "token": "[masked]", "tokens": "[masked]", "cardData": {"number": "[masked]", "expiry": "[masked]", "cvc": "[masked]", "holder": "Test Holder"}, + "3DSecExternal": {"xid": "[masked]", "eci": "01", "cavv": "[masked]"}, "items": [{"title": "Product", "applePayToken": "[masked]", "googlePayToken": "[masked]"}], }) ); diff --git a/src/dto/auto_payment.rs b/src/dto/auto_payment.rs index e6dd824..b9ff815 100644 --- a/src/dto/auto_payment.rs +++ b/src/dto/auto_payment.rs @@ -45,18 +45,20 @@ impl CardData { } /// The result of a 3D Secure check your own system ran before the payment (with its own MPI), -/// sent as `3DSecExternal`. +/// sent as `3DSecExternal`. Its `Debug` output hides the identifier and the cryptogram. /// /// ``` /// use netipar_simplepay::ThreeDsExternal; /// /// let result = ThreeDsExternal::new("01234567980123456789", "01", "ABCDEF"); +/// +/// assert!(!format!("{result:?}").contains("ABCDEF")); /// ``` #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct ThreeDsExternal { - xid: String, + xid: Secret, eci: String, - cavv: String, + cavv: Secret, } impl ThreeDsExternal { @@ -66,9 +68,9 @@ impl ThreeDsExternal { #[must_use] pub fn new(xid: impl Into, eci: impl Into, cavv: impl Into) -> Self { Self { - xid: xid.into(), + xid: Secret::new(xid), eci: eci.into(), - cavv: cavv.into(), + cavv: Secret::new(cavv), } } } diff --git a/tests/auto_payment.rs b/tests/auto_payment.rs index bdc3320..55ca0a5 100644 --- a/tests/auto_payment.rs +++ b/tests/auto_payment.rs @@ -170,9 +170,18 @@ async fn the_live_system_has_its_own_card_data_host() { #[test] fn debug_output_hides_the_card_data() { - let debug = format!("{:?}", request()); + let debug = format!( + "{:?}", + request().three_ds_external(ThreeDsExternal::new( + "the-3ds-identifier", + "01", + "the-3ds-cryptogram" + )) + ); assert!(debug.contains("Test Holder"), "{debug}"); + assert!(!debug.contains("the-3ds-identifier"), "{debug}"); + assert!(!debug.contains("the-3ds-cryptogram"), "{debug}"); assert!(!debug.contains("4908366099900425"), "{debug}"); assert!(!debug.contains("0130"), "{debug}"); assert!(!debug.contains("123"), "{debug}"); From 82a4b1dbe9c83a2092ff8c084a689b81dc8ab4a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tibor=20Heged=C5=B1s?= Date: Thu, 3 Dec 2026 16:52:11 +0100 Subject: [PATCH 3/3] Hide the customer's bank account number in logs and debug output --- AGENTS.md | 2 +- src/client.rs | 5 ++++- src/dto/rtp.rs | 16 +++++++++++----- tests/rtp.rs | 17 +++++++++++++++++ 4 files changed, 33 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2fa05cf..863478d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ This repository is a Laravel Rust package: a library crate that integrates with - `payment().handle_ipn` and `handle_back` do the verification for a route of the application's own. - `do_google_pay` turns error code 3004 with a `redirectUrl` into a normal `GooglePayResponse`; the other calls return it as `Error::Api`, as the PHP package does. - `src/client.rs`: the internal client. It adds `merchant`, `salt` and `sdkVersion` (`SDK_VERSION`) to a body, serializes it once, signs those bytes and sends them through a dedicated `laravel::http::client::Client`, so `client::fake()` intercepts the calls in tests. It turns an HTTP error status into `Error::Http`, requires a `Signature` on the response and verifies it (stricter than the PHP package, which accepts an unsigned response), and turns a non-empty `errorCodes` list into `Error::Api`. It logs requests and responses on the `netipar_simplepay` tracing target with card data and tokens masked. -- `src/dto/`: request and response bodies. A request has private fields, a `new` with the required values in the PHP constructor's order, and chainable setters (`setters!`) for the optional ones; it serializes to the official field names. A value a request computes at send time (`timeout`, `deadline`, a generated `packageRef`) is added by the service, not by the DTO. `BrowserData` is the exception to the builder shape: its eight required values make a struct literal clearer. Secrets (`cardSecret`, tokens, card data, the identifier and cryptogram of an external 3DS check) are held in `dto::secret::Secret`, so a request's `Debug` output never shows them; the same fields are in the client's `MASKED_KEYS`, so the log never shows them either. A new secret field needs both. A response is a `#[non_exhaustive]` struct with public fields. Amounts are `rust_decimal::Decimal`, sent as JSON numbers with the opt-in `rust_decimal::serde::float` serializers (never enable `serde-float` or other crate-wide serde features: Cargo would apply them to the application too). Identifiers that SimplePay sends as a number or as text are read with `dto::lenient`. +- `src/dto/`: request and response bodies. A request has private fields, a `new` with the required values in the PHP constructor's order, and chainable setters (`setters!`) for the optional ones; it serializes to the official field names. A value a request computes at send time (`timeout`, `deadline`, a generated `packageRef`) is added by the service, not by the DTO. `BrowserData` is the exception to the builder shape: its eight required values make a struct literal clearer. Secrets and personal financial data (`cardSecret`, tokens, card data, the identifier and cryptogram of an external 3DS check, the customer's bank account number) are held in `dto::secret::Secret`, so a request's `Debug` output never shows them; the same fields are in the client's `MASKED_KEYS`, so the log never shows them either. A new secret field needs both. A response is a `#[non_exhaustive]` struct with public fields. Amounts are `rust_decimal::Decimal`, sent as JSON numbers with the opt-in `rust_decimal::serde::float` serializers (never enable `serde-float` or other crate-wide serde features: Cargo would apply them to the application too). Identifiers that SimplePay sends as a number or as text are read with `dto::lenient`. - `tests/`: one file per area, through the public API. `tests/provider.rs` builds a host application with `for_testing`; The tests of the API calls (`payment`, `card_storage`, `auto_payment`, `wallets`, `rtp`) fake the SimplePay API with signed responses and compare each sent body, as a whole, with the PHP package's; their shared helpers are in `tests/common/mod.rs`. The expected signatures and messages come from the PHP package and from SimplePay's developer documentation. ## Release diff --git a/src/client.rs b/src/client.rs index 1e76157..0cd3bc0 100644 --- a/src/client.rs +++ b/src/client.rs @@ -12,7 +12,7 @@ pub(crate) const SDK_VERSION: &str = "SimplePay_Rust_SDK_2.1_Laravel"; const LOG_TARGET: &str = "netipar_simplepay"; /// Body fields whose values never reach the log. -const MASKED_KEYS: [&str; 10] = [ +const MASKED_KEYS: [&str; 11] = [ "number", "expiry", "cvc", @@ -23,6 +23,7 @@ const MASKED_KEYS: [&str; 10] = [ "applePayToken", "xid", "cavv", + "customerBankAccount", ]; #[derive(Debug, Clone)] @@ -162,6 +163,7 @@ mod tests { "tokens": ["SPT-1", "SPT-2"], "cardData": {"number": "4908366099900425", "expiry": "0130", "cvc": "123", "holder": "Test Holder"}, "3DSecExternal": {"xid": "01234567980123456789", "eci": "01", "cavv": "ABCDEF"}, + "transactions": [{"orderRef": "RTP-1", "customerBankAccount": "002000041111111111111111"}], "items": [{"title": "Product", "applePayToken": "apple", "googlePayToken": "google"}], }); @@ -174,6 +176,7 @@ mod tests { "tokens": "[masked]", "cardData": {"number": "[masked]", "expiry": "[masked]", "cvc": "[masked]", "holder": "Test Holder"}, "3DSecExternal": {"xid": "[masked]", "eci": "01", "cavv": "[masked]"}, + "transactions": [{"orderRef": "RTP-1", "customerBankAccount": "[masked]"}], "items": [{"title": "Product", "applePayToken": "[masked]", "googlePayToken": "[masked]"}], }) ); diff --git a/src/dto/rtp.rs b/src/dto/rtp.rs index dd448ce..60d09fd 100644 --- a/src/dto/rtp.rs +++ b/src/dto/rtp.rs @@ -3,6 +3,7 @@ use std::time::Duration; use rust_decimal::Decimal; use serde::Serialize; +use super::secret::Secret; use crate::{Address, Currency, Item, RedirectUrls}; /// A Request to Pay to start with [`RtpService::start`](crate::RtpService::start). @@ -175,7 +176,7 @@ pub struct RtpPayment { #[serde(skip_serializing_if = "Option::is_none")] additional_info: Option, #[serde(skip_serializing_if = "Option::is_none")] - customer_bank_account: Option, + customer_bank_account: Option, #[serde(skip_serializing_if = "Option::is_none")] items: Option>, #[serde( @@ -227,6 +228,13 @@ impl RtpPayment { self } + /// The customer's bank account number, when you know it. + #[must_use] + pub fn customer_bank_account(mut self, account: impl Into) -> Self { + self.customer_bank_account = Some(Secret::new(account)); + self + } + default_setters! { /// The two-letter code of the customer's language. language: String, @@ -238,8 +246,6 @@ impl RtpPayment { deadline: String, /// The announcement shown with the bank transfer. additional_info: String, - /// The customer's bank account number, when you know it. - customer_bank_account: String, /// The shipping cost, which SimplePay adds to the amount to pay. shipping_cost: Decimal, /// The discount, which SimplePay takes off the amount to pay. @@ -401,7 +407,7 @@ pub struct RtpQuery { #[serde(skip_serializing_if = "Option::is_none")] customer_email: Option, #[serde(skip_serializing_if = "Option::is_none")] - customer_bank_account: Option, + customer_bank_account: Option, #[serde(skip_serializing_if = "Option::is_none")] from: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -467,7 +473,7 @@ impl RtpQuery { #[must_use] pub fn customer_bank_account(account: impl Into) -> Self { Self { - customer_bank_account: Some(account.into()), + customer_bank_account: Some(Secret::new(account)), ..Self::empty() } } diff --git a/tests/rtp.rs b/tests/rtp.rs index 690c041..81f24fe 100644 --- a/tests/rtp.rs +++ b/tests/rtp.rs @@ -507,3 +507,20 @@ async fn a_start_and_a_batch_send_the_optional_fields_of_the_official_samples(ap }]) ); } + +#[test] +fn debug_output_hides_the_bank_account_number() { + let payment = format!( + "{:?}", + RtpPayment::new("RTP-1", 1000, "a@example.com", "Customer A") + .customer_bank_account("002000041111111111111111") + ); + let query = format!( + "{:?}", + RtpQuery::customer_bank_account("002000041111111111111111") + ); + + assert!(payment.contains("RTP-1"), "{payment}"); + assert!(!payment.contains("002000041111111111111111"), "{payment}"); + assert!(!query.contains("002000041111111111111111"), "{query}"); +}