SimplePay online payment integration for Laravel Rust applications. It is the Rust port of netipar/simplepay, the Laravel PHP package.
Note
The crate covers the API calls, the IPN and back routes, the events and the logo assets of the PHP package. The calls that need no paying customer are checked against SimplePay's sandbox. The flows that need a completed payment, such as refunding or capturing a card payment, paying with a stored card, and receiving the IPN, follow SimplePay's documentation and its official SDK, and have not run against the sandbox yet.
The guides are in English and in Hungarian: see Documentation. Magyar útmutatók: docs/hu.
Requires Rust 1.99+ and laravel-rust 0.2. Add the crate to your application's Cargo.toml:
[dependencies]
netipar-simplepay = "0.2"An application on laravel-rust 0.1 requires netipar-simplepay = "0.1" instead: the two minor versions of the framework don't mix in one application.
Then register the service provider in your application's src/app.rs:
use laravel::Application;
use netipar_simplepay::SimplePayServiceProvider;
let app = Application::configure()
# .replace_env(laravel::config::Env::default())
.with_providers(|providers| {
providers.add(SimplePayServiceProvider);
})
.create();
# assert!(app.config().section::<netipar_simplepay::SimplePayConfig>().sandbox);The provider reads its settings from the environment. The variable names are the ones the PHP package uses, so an existing .env keeps working:
SIMPLEPAY_HUF_MERCHANT,SIMPLEPAY_HUF_SECRET_KEY: the forint merchant account.EURandUSDhave the same pair of variables. A currency gets a merchant account only when both are set.SIMPLEPAY_SANDBOX: whether API calls go to the SimplePay sandbox. Defaults totrue.SIMPLEPAY_TIMEOUT: how many seconds a started payment stays open. Defaults to600.SIMPLEPAY_GOOGLE_PAY_MERCHANT_ID,SIMPLEPAY_GOOGLE_PAY_MERCHANT_NAME: the settings of merchant-side Google Pay.
An invalid value, such as SIMPLEPAY_TIMEOUT=soon, stops the application at startup.
Your application may override a setting in with_config, which runs after the provider has read the environment:
use laravel::Application;
use netipar_simplepay::{Currency, Merchant, SimplePayConfig, SimplePayServiceProvider};
let app = Application::configure()
# .replace_env(laravel::config::Env::default())
.with_providers(|providers| {
providers.add(SimplePayServiceProvider);
})
.with_config(|config, _| {
let simplepay = config.section_mut::<SimplePayConfig>();
simplepay.sandbox = false;
simplepay
.merchants
.insert(Currency::Huf, Merchant::new("MERCHANT_ID", "secret-key"));
})
.create();
# let config = app.config().section::<SimplePayConfig>();
# assert!(!config.sandbox);
# assert_eq!(config.merchant(Currency::Huf).unwrap().id, "MERCHANT_ID");Inject the client into a handler, and reach the payment calls through payment().
use laravel::container::Inject;
use laravel::prelude::*;
use netipar_simplepay::{Address, Currency, PaymentMethod, PaymentRequest, SimplePay};
pub async fn pay(simplepay: Inject<SimplePay>) -> laravel::Result<Redirect> {
let request = PaymentRequest::new(
Currency::Huf,
2500,
"ORDER-123",
"customer@example.com",
"HU",
"https://example.com/simplepay/back",
)
.methods([PaymentMethod::Card])
.invoice(Address::new("John Doe", "hu", "Budapest", "1111", "Main Street 1"));
let response = simplepay.payment().start(&request).await?;
// Store response.transaction_id with your order, then send the customer to the payment page.
Ok(Redirect::to(response.payment_url))
}Amounts are decimals (netipar_simplepay::Decimal, re-exported from rust_decimal); a whole number such as 2500 converts on its own. The payment times out after SIMPLEPAY_TIMEOUT seconds unless the request sets its own timeout.
Start the payment with .two_step(true) to only reserve the amount, then charge all or part of it:
use netipar_simplepay::{Currency, Error, FinishRequest, FinishResponse, SimplePay};
pub async fn capture(simplepay: &SimplePay, transaction_id: u64) -> Result<FinishResponse, Error> {
// Charges 20 000 of the 25 400 forints the payment reserved.
let request = FinishRequest::new(Currency::Huf, transaction_id, "ORDER-123", 20_000, 25_400);
simplepay.payment().finish(&request).await
}query, status and cancel take the transaction's SimplePay identifier or your order reference:
use netipar_simplepay::{Currency, Error, PaymentStatus, RefundRequest, SimplePay};
pub async fn examples(simplepay: &SimplePay) -> Result<(), Error> {
let payment = simplepay.payment();
let refund = payment
.refund(&RefundRequest::new(Currency::Huf, 502_272_810, "ORDER-123", 1000))
.await?;
println!("{} is left of the payment", refund.remaining_total);
// The transaction with its details...
let transaction = payment.query(Currency::Huf, 502_272_810).await?;
println!("{} paid {}", transaction.order_ref, transaction.total);
// ...or only its status, which is lighter and suits polling.
let status = payment.status(Currency::Huf, "ORDER-123").await?;
if status.end_state && status.status == PaymentStatus::Finished {
// Fulfil the order.
}
payment.cancel(Currency::Huf, "ORDER-124").await?;
Ok(())
}A payment started with .card_secret(..) stores the card for OneClick payments; one started with .recurring(..) returns recurring tokens. card_storage() charges them later:
use netipar_simplepay::{
CardStorageDoRequest, Currency, Error, PaymentRequest, Recurring, RecurringRequest, SimplePay,
TransactionType,
};
pub async fn examples(simplepay: &SimplePay) -> Result<(), Error> {
let back = "https://example.com/simplepay/back";
let cards = simplepay.card_storage();
// Store the card with a payment. The customer's secret protects it.
let registration = simplepay
.payment()
.start(
&PaymentRequest::new(Currency::Huf, 2500, "ORDER-123", "customer@example.com", "HU", back)
.card_secret("the-customers-secret"),
)
.await?;
// Charge the stored card. Its identifier is the transaction identifier of the registration.
let card_id = registration.transaction_id.to_string();
cards
.do_payment(
&CardStorageDoRequest::new(Currency::Huf, &card_id, "ORDER-124", 1500, "customer@example.com", back)
.card_secret("the-customers-secret"),
)
.await?;
// A recurring registration returns tokens to charge later.
let subscription = simplepay
.payment()
.start(
&PaymentRequest::new(Currency::Huf, 9900, "SUB-2027-01", "customer@example.com", "HU", back)
.recurring(Recurring::new(12, "2027-12-31T00:00:00+02:00", 10_000)),
)
.await?;
cards
.do_recurring(&RecurringRequest::new(
Currency::Huf,
&subscription.tokens[0],
"SUB-2027-02",
9900,
"customer@example.com",
back,
TransactionType::Mit,
))
.await?;
// Remove the stored card.
cards.card_cancel(Currency::Huf, &card_id).await?;
Ok(())
}card_query, token_query and token_cancel read a stored card, and read or invalidate a token. When the card issuer asks for a 3DS challenge, do_payment fails with error code 3004; see Errors.
auto_payment() charges card data your own page collected. The Debug output of CardData hides the number, the expiry and the verification code:
use netipar_simplepay::{AutoPaymentRequest, CardData, Currency, Error, SimplePay, TransactionType};
pub async fn charge(simplepay: &SimplePay, card: CardData) -> Result<serde_json::Value, Error> {
let request = AutoPaymentRequest::new(
Currency::Huf,
1500,
"ORDER-125",
"customer@example.com",
card,
TransactionType::Cit,
)
.url("https://example.com/simplepay/back");
simplepay.auto_payment().auto(&request).await
}use netipar_simplepay::{
ApplePayDoRequest, ApplePayStartRequest, Currency, EamStartRequest, Error, GooglePayDoRequest,
SimplePay,
};
pub async fn examples(simplepay: &SimplePay, apple_token: &str, google_token: &str) -> Result<(), Error> {
let back = "https://example.com/simplepay/back";
let payment = simplepay.payment();
// An instant payment (EAM, known as qvik) with a QR code and a deeplink.
payment
.start_eam(&EamStartRequest::new(Currency::Huf, 3000, "ORDER-EAM-1", "customer@example.com", back).eam_type(4))
.await?;
// Apple Pay: start a session for the registered domain, then complete it with the page's token.
payment
.start_apple_pay(&ApplePayStartRequest::new(
Currency::Huf,
1500,
"ORDER-AP-1",
"customer@example.com",
back,
"shop.example.com",
))
.await?;
payment
.do_apple_pay(&ApplePayDoRequest::new(Currency::Huf, 581_841_992, "ORDER-AP-1", apple_token))
.await?;
// Google Pay on your own checkout page. A 3DS challenge is a normal outcome here.
let charge = payment
.do_google_pay(&GooglePayDoRequest::new(
Currency::Huf,
1500,
"ORDER-GPAY-1",
"customer@example.com",
google_token,
back,
))
.await?;
if let Some(url) = &charge.redirect_url {
println!("send the customer to {url}");
}
// The values the Google Pay button needs; the struct serializes to JSON for the page.
let button = payment.google_pay_config(Currency::Huf, 1500)?;
println!("{}", button.gpay_environment);
Ok(())
}use netipar_simplepay::{
Currency, Error, RtpDoRequest, RtpPayment, RtpQuery, RtpRef, RtpRefundRequest, RtpStartRequest,
SimplePay,
};
pub async fn examples(simplepay: &SimplePay) -> Result<(), Error> {
let rtp = simplepay.rtp();
// One payment request: send the customer to response.payment_url.
let response = rtp
.start(&RtpStartRequest::new(
Currency::Huf,
5000,
"RTP-001",
"customer@example.com",
"https://example.com/simplepay/back",
"John Doe",
))
.await?;
println!("{}", response.payment_url);
// A batch of payment requests.
rtp.do_payments(&RtpDoRequest::new(
Currency::Huf,
[RtpPayment::new("RTP-002", 1000, "a@example.com", "Customer A")],
))
.await?;
rtp.query(Currency::Huf, &RtpQuery::order_ref("RTP-001").detailed(true)).await?;
rtp.refund(&RtpRefundRequest::new(Currency::Huf, "102264132", 15, 25)).await?;
rtp.reverse(Currency::Huf, RtpRef::Transaction("102264204".to_owned())).await?;
Ok(())
}Every call returns netipar_simplepay::Error. When SimplePay answers with error codes, the error is Error::Api, which keeps the codes and the whole response body:
use netipar_simplepay::{Error, ErrorCode};
fn describe(error: &Error) -> String {
match error {
Error::Api(api) if api.has(ErrorCode::THREE_DS_CHALLENGE_REDIRECT) => {
// The customer has to complete a 3DS challenge at this URL.
format!("redirect to {}", api.body()["redirectUrl"])
}
other => other.to_string(),
}
}The client writes a debug event for every request and response on the netipar_simplepay target, with card data and tokens masked. Enable it with a log level such as LOG_LEVEL=info,netipar_simplepay=debug.
SimplePay signs the exact bytes of a body with the merchant's secret key (HMAC-SHA384, in base64) and sends the result in the Signature header. The signature module signs and verifies the same way:
use netipar_simplepay::signature;
let body = r#"{"orderRef":"ORD-001"}"#;
let signature = signature::sign("secret-key", body);
assert!(signature::verify("secret-key", body, &signature));ErrorCode knows SimplePay's error codes and their Hungarian descriptions. A code the package does not know yet is still a valid ErrorCode:
use netipar_simplepay::ErrorCode;
assert_eq!(ErrorCode::THREE_DS_CHALLENGE_REDIRECT.code(), 3004);
assert_eq!(ErrorCode::new(5083).to_string(), "[5083] Token times szükséges");
assert_eq!(ErrorCode::new(99999).description(), None);The provider registers two routes.
POST /simplepay/ipn receives the notification SimplePay sends when a transaction's status changes. Set its public URL in SimplePay's merchant control panel, for every merchant account. The route has no session and no CSRF protection; it verifies SimplePay's signature instead, and answers an IPN that doesn't verify with 401.
A verified IPN dispatches IpnReceived, then the event of its status:
PaymentSucceeded:FINISHEDPaymentAuthorized:AUTHORIZEDPaymentFailed:NOTAUTHORIZEDPaymentCancelled:CANCELLEDPaymentTimedOut:TIMEOUTPaymentRefunded:REFUND
Listen to them in with_events. Every event carries the notification in ipn:
use laravel::Application;
use laravel::event::Event;
use netipar_simplepay::{PaymentSucceeded, SimplePayServiceProvider};
let app = Application::configure()
# .replace_env(laravel::config::Env::default())
.with_providers(|providers| {
providers.add(SimplePayServiceProvider);
})
.with_events(|events, _| {
events.listen(async |event: Event<PaymentSucceeded>| {
println!("order {} is paid", event.ipn.order_ref);
});
})
.create();
# let _ = app;The route acknowledges the IPN only after the listeners ran. When a listener fails, the route fails too, so SimplePay sends the IPN again later. SimplePay waits 20 seconds for the acknowledgement, so do long work in a queued job.
GET /simplepay/back is where SimplePay sends the customer after the payment page, when a request names the route as its url. Link to it by its handler:
use laravel::prelude::*;
use netipar_simplepay::{Currency, PaymentRequest};
pub fn request() -> laravel::Result<PaymentRequest> {
Ok(PaymentRequest::new(
Currency::Huf,
2500,
"ORDER-123",
"customer@example.com",
"HU",
route!(netipar_simplepay::back)?,
))
}The route verifies the r and s parameters SimplePay appends, then asks the application's BackResponder what the customer sees. The default one redirects to /; register your own in with_services:
use laravel::prelude::*;
use netipar_simplepay::{BackEvent, BackResponder, BackResponse, SimplePayServiceProvider};
let app = Application::configure()
# .replace_env(laravel::config::Env::default())
.with_providers(|providers| {
providers.add(SimplePayServiceProvider);
})
.with_services(|services| {
services.instance(BackResponder::new(
async |_request: Request, back: BackResponse| match back.event {
BackEvent::Success => Redirect::to(format!("/orders/{}/thanks", back.order_ref)),
_ => Redirect::to(format!("/orders/{}/retry", back.order_ref)),
},
));
})
.create();
# let _ = app;The back URL says what happened on the payment page, not whether the money arrived: fulfil the order when the IPN arrives, or after a status or query call.
In a route of your own, simplepay.payment().handle_ipn(body, signature) and handle_back(r, s) do the same verification.
With the assets Cargo feature the provider serves SimplePay's logo pack under /vendor/simplepay. The images are embedded in the binary, which they make about 5.5 MB larger, so the feature is off by default:
[dependencies]
netipar-simplepay = { version = "0.2", features = ["assets"] }<img src="{{ vendor_asset("simplepay", "logos/simplepay_200x50.png") }}" alt="SimplePay" width="200" height="50">See Logos and assets for the list of images.
| Topic | English | Magyar |
|---|---|---|
| Configuration | Configuration | Konfiguráció |
| Starting a payment | Starting a payment | Fizetés indítása |
| Query, refund, cancel | Query, refund and cancel | Lekérdezés, visszatérítés és megszakítás |
| Card storage | Card storage | Kártyatárolás |
| Card data on your page | Card data on your own page | Kártyaadat a saját oldalon |
| Instant payment, Apple Pay | Instant payment and Apple Pay | Azonnali fizetés és Apple Pay |
| Google Pay | Google Pay on your own checkout page | Google Pay a saját fizetési oldalon |
| Request to Pay | Request to Pay | Request to Pay |
| IPN webhook | IPN webhook | IPN webhook |
| Back URL | Back URL | Visszairányítás |
| Error codes | Error codes | Hibakódok |
| Logos and assets | Logos and assets | Logók és assetek |
cargo test --locked --all-targets --all-features
cargo test --locked --doc --all-featuresThe examples in this README and in the guides under docs/ run as doctests.
The tests fake the SimplePay API. tests/sandbox.rs holds the ones that call SimplePay's real sandbox; they are ignored unless you name them and give a sandbox merchant account, such as the demo accounts SimplePay publishes:
SIMPLEPAY_HUF_MERCHANT=... SIMPLEPAY_HUF_SECRET_KEY=... cargo test --test sandbox -- --ignored --test-threads=1See CHANGELOG.md.
Please review the contributing guide before opening a pull request.
Please review the security policy on how to report security vulnerabilities.
The MIT License (MIT). See LICENSE.md.