Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -41,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 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
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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> {
Expand All @@ -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(())
}
Expand Down
9 changes: 8 additions & 1 deletion src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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; 11] = [
"number",
"expiry",
"cvc",
Expand All @@ -21,6 +21,9 @@ const MASKED_KEYS: [&str; 8] = [
"tokens",
"googlePayToken",
"applePayToken",
"xid",
"cavv",
"customerBankAccount",
];

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -159,6 +162,8 @@ 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"},
"transactions": [{"orderRef": "RTP-1", "customerBankAccount": "002000041111111111111111"}],
"items": [{"title": "Product", "applePayToken": "apple", "googlePayToken": "google"}],
});

Expand All @@ -170,6 +175,8 @@ mod tests {
"token": "[masked]",
"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]"}],
})
);
Expand Down
4 changes: 2 additions & 2 deletions src/dto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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;
57 changes: 57 additions & 0 deletions src/dto/auto_payment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,37 @@ impl CardData {
}
}

/// The result of a 3D Secure check your own system ran before the payment (with its own MPI),
/// 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: Secret,
eci: String,
cavv: Secret,
}

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<String>, eci: impl Into<String>, cavv: impl Into<String>) -> Self {
Self {
xid: Secret::new(xid),
eci: eci.into(),
cavv: Secret::new(cavv),
}
}
}

/// A payment with card data your own page collected, for
/// [`AutoPaymentService::auto`](crate::AutoPaymentService::auto).
///
Expand Down Expand Up @@ -91,6 +122,20 @@ pub struct AutoPaymentRequest {
delivery: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
items: Option<Vec<Item>>,
#[serde(rename = "3DSecExternal", skip_serializing_if = "Option::is_none")]
three_ds_external: Option<ThreeDsExternal>,
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "rust_decimal::serde::float_option::serialize"
)]
shipping_cost: Option<Decimal>,
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "rust_decimal::serde::float_option::serialize"
)]
discount: Option<Decimal>,
#[serde(skip_serializing_if = "Option::is_none")]
pocket: Option<String>,
}

impl AutoPaymentRequest {
Expand Down Expand Up @@ -119,6 +164,10 @@ impl AutoPaymentRequest {
invoice: None,
delivery: None,
items: None,
three_ds_external: None,
shipping_cost: None,
discount: None,
pocket: None,
}
}

Expand All @@ -145,5 +194,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,
}
}
6 changes: 6 additions & 0 deletions src/dto/card_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ pub struct CardStorageDoRequest {
customer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
invoice: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
legacy_recurring: Option<bool>,
}

impl CardStorageDoRequest {
Expand Down Expand Up @@ -79,6 +81,7 @@ impl CardStorageDoRequest {
browser: None,
customer: None,
invoice: None,
legacy_recurring: None,
}
}

Expand Down Expand Up @@ -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,
}
}

Expand Down
65 changes: 65 additions & 0 deletions src/dto/payment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -68,6 +70,27 @@ pub struct PaymentRequest {
customer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
urls: Option<RedirectUrls>,
#[serde(skip_serializing_if = "Option::is_none")]
may_select_email: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
may_select_invoice: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
may_select_delivery: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
mobil_app: Option<MobileApp>,
#[serde(skip_serializing_if = "Option::is_none")]
only_card_reg: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
legacy_card_register: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
legacy_recurring: Option<bool>,
}

/// The `mobilApp` object of a start request.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct MobileApp {
simple_app_back_url: String,
}

impl PaymentRequest {
Expand Down Expand Up @@ -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,
}
}

Expand All @@ -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<Item = impl Into<String>>,
) -> 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<String>) -> 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.
Expand Down
Loading