Skip to content
Draft
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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "truelayer-rust"
version = "0.2.0"
version = "0.3.0-pre0"
edition = "2021"

[dependencies]
Expand Down
1 change: 1 addition & 0 deletions examples/create_payment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ async fn run() -> anyhow::Result<()> {
phone: None,
},
metadata: None,
sub_merchants: None,
})
.await?;

Expand Down
87 changes: 84 additions & 3 deletions src/apis/payments/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,13 +406,13 @@ mod tests {
apis::{
auth::Credentials,
payments::{
refunds::RefundStatus, AdditionalInputType, AuthorizationFlowNextAction,
refunds::RefundStatus, AdditionalInputType, Address, AuthorizationFlowNextAction,
AuthorizationFlowResponseStatus, Beneficiary, ConsentSupported, CountryCode,
CreatePaymentStatus, CreatePaymentUserRequest, Currency, FailureStage,
FormSupported, PaymentMethod, PaymentMethodRequest, PaymentStatus, Provider,
ProviderSelection, ProviderSelectionRequest, ProviderSelectionSupported,
RedirectSupported, SchemeSelection, SubmitProviderReturnParametersResponseResource,
User,
RedirectSupported, SchemeSelection, SubMerchants,
SubmitProviderReturnParametersResponseResource, UltimateCounterparty, User,
},
},
authenticator::Authenticator,
Expand Down Expand Up @@ -517,6 +517,7 @@ mod tests {
id: "user-id".to_string(),
},
metadata: None,
sub_merchants: None,
})
.await
.unwrap();
Expand All @@ -527,6 +528,86 @@ mod tests {
assert_eq!(res.status, CreatePaymentStatus::AuthorizationRequired)
}

#[tokio::test]
async fn create_with_sub_merchants() {
let (inner, mock_server) = mock_client_and_server().await;
let api = PaymentsApi::new(Arc::new(inner));

Mock::given(method("POST"))
.and(path("/payments"))
.and(header_exists(IDEMPOTENCY_KEY_HEADER))
.and(body_partial_json(json!({
"sub_merchants": {
"ultimate_counterparty": {
"type": "business_client",
"id": "client-id",
"trading_name": "Test Trading",
"commercial_name": "Test Commercial",
"mcc": "5411",
"address": {
"address_line1": "1 Test Street",
"city": "London",
"zip": "EC1A 1BB",
"country_code": "GB"
}
}
}
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": "payment-id",
"resource_token": "resource-token",
"user": { "id": "user-id" },
"status": "authorization_required"
})))
.expect(1)
.mount(&mock_server)
.await;

let res = api
.create(&CreatePaymentRequest {
amount_in_minor: 100,
currency: Currency::Gbp,
payment_method: PaymentMethodRequest::BankTransfer {
provider_selection: ProviderSelectionRequest::UserSelected {
filter: None,
scheme_selection: None,
},
beneficiary: Beneficiary::MerchantAccount {
merchant_account_id: "merchant-account-id".to_string(),
account_holder_name: None,
reference: None,
statement_reference: None,
},
},
user: CreatePaymentUserRequest::ExistingUser {
id: "user-id".to_string(),
},
metadata: None,
sub_merchants: Some(SubMerchants {
ultimate_counterparty: UltimateCounterparty::BusinessClient {
id: "client-id".to_string(),
trading_name: "Test Trading".to_string(),
commercial_name: Some("Test Commercial".to_string()),
url: None,
mcc: Some("5411".to_string()),
registration_number: None,
address: Some(Box::new(Address {
address_line1: "1 Test Street".to_string(),
address_line2: None,
city: "London".to_string(),
state: None,
zip: "EC1A 1BB".to_string(),
country_code: "GB".to_string(),
})),
},
}),
})
.await
.unwrap();

assert_eq!(res.id, "payment-id");
}

#[tokio::test]
async fn start_authorization_flow() {
let (inner, mock_server) = mock_client_and_server().await;
Expand Down
42 changes: 42 additions & 0 deletions src/apis/payments/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,48 @@ pub struct CreatePaymentRequest {
pub payment_method: PaymentMethodRequest,
pub user: CreatePaymentUserRequest,
pub metadata: Option<HashMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_merchants: Option<SubMerchants>,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct SubMerchants {
pub ultimate_counterparty: UltimateCounterparty,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum UltimateCounterparty {
BusinessDivision {
id: String,
name: String,
},
BusinessClient {
id: String,
trading_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
commercial_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
mcc: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
registration_number: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
address: Option<Box<Address>>,
},
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct Address {
pub address_line1: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub address_line2: Option<String>,
pub city: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
pub zip: String,
pub country_code: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
Expand Down
64 changes: 63 additions & 1 deletion src/apis/payouts/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ mod tests {
use crate::{
apis::{
auth::Credentials,
payments::{AccountIdentifier, Currency},
payments::{AccountIdentifier, Currency, SubMerchants, UltimateCounterparty},
payouts::{PayoutBeneficiary, PayoutStatus},
},
authenticator::Authenticator,
Expand Down Expand Up @@ -175,6 +175,68 @@ mod tests {
},
reference: "some-reference".to_string(),
},
sub_merchants: None,
})
.await
.unwrap();

assert_eq!(res.id, "payout-id");
}

#[tokio::test]
async fn create_with_sub_merchants() {
let (inner, mock_server) = mock_client_and_server().await;
let api = PayoutsApi::new(Arc::new(inner));

Mock::given(method("POST"))
.and(path("/payouts"))
.and(header_exists(IDEMPOTENCY_KEY_HEADER))
.and(body_partial_json(json!({
"merchant_account_id": "merchant-account-id",
"amount_in_minor": 100,
"currency": "GBP",
"beneficiary": {
"type": "external_account",
"account_holder_name": "Mr. Holder",
"account_identifier": {
"type": "iban",
"iban": "some-iban"
},
"reference": "some-reference"
},
"sub_merchants": {
"ultimate_counterparty": {
"type": "business_division",
"id": "division-id",
"name": "Division Name"
}
}
})))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": "payout-id"
})))
.expect(1)
.mount(&mock_server)
.await;

let res = api
.create(&CreatePayoutRequest {
merchant_account_id: "merchant-account-id".to_string(),
amount_in_minor: 100,
currency: Currency::Gbp,
beneficiary: PayoutBeneficiary::ExternalAccount {
account_holder_name: "Mr. Holder".to_string(),
account_identifier: AccountIdentifier::Iban {
iban: "some-iban".to_string(),
},
reference: "some-reference".to_string(),
},
sub_merchants: Some(SubMerchants {
ultimate_counterparty: UltimateCounterparty::BusinessDivision {
id: "division-id".to_string(),
name: "Division Name".to_string(),
},
}),
})
.await
.unwrap();
Expand Down
4 changes: 3 additions & 1 deletion src/apis/payouts/model.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
apis::payments::{AccountIdentifier, Currency},
apis::payments::{AccountIdentifier, Currency, SubMerchants},
pollable::IsInTerminalState,
Error, Pollable, TrueLayerClient,
};
Expand All @@ -14,6 +14,8 @@ pub struct CreatePayoutRequest {
pub amount_in_minor: u64,
pub currency: Currency,
pub beneficiary: PayoutBeneficiary,
#[serde(skip_serializing_if = "Option::is_none")]
pub sub_merchants: Option<SubMerchants>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
Expand Down
6 changes: 3 additions & 3 deletions src/authenticator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,9 @@ async fn process_get_access_token(
/// Returns `true` if the token is close to expiration (10 minutes before actual expiration)
/// and should be refreshed. If this token does not expire, this function always returns `false`.
fn should_refresh_token(token: &AccessToken) -> bool {
token.expires_at.map_or(false, |expires_at| {
now() >= expires_at - Duration::minutes(10)
})
token
.expires_at
.is_some_and(|expires_at| now() >= expires_at - Duration::minutes(10))
}

// Select an implementation of `now()` depending on whether we are testing or not
Expand Down
8 changes: 7 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub enum Error {
HttpError(#[from] reqwest::Error),
/// Error returned by a TrueLayer API endpoint.
#[error("{0}")]
ApiError(#[from] ApiError),
ApiError(Box<ApiError>),
/// Error building request signature.
///
/// Read more about signing here: <https://docs.truelayer.com/docs/signing-your-requests>
Expand All @@ -21,6 +21,12 @@ pub enum Error {
Other(anyhow::Error),
}

impl From<ApiError> for Error {
fn from(e: ApiError) -> Self {
Error::ApiError(Box::new(e))
}
}

impl From<reqwest_middleware::Error> for Error {
fn from(e: reqwest_middleware::Error) -> Self {
match e {
Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@
//! email: Some("some.one@email.com".to_string()),
//! phone: None,
//! },
//! metadata: None
//! metadata: None,
//! sub_merchants: None,
//! })
//! .await?;
//!
Expand Down
2 changes: 1 addition & 1 deletion src/middlewares/error_handling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ impl Middleware for ErrorHandlingMiddleware {
tracing::debug!("Failed HTTP request. Status code: {}", response.status());

let api_error = api_error_from_response(response).await?;
return Err(Error::ApiError(api_error).into());
return Err(Error::from(api_error).into());
}

Ok(response)
Expand Down
2 changes: 1 addition & 1 deletion src/middlewares/retry_idempotent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ impl Middleware for RetryIdempotentMiddleware {
Method::POST | Method::PATCH => req
.headers()
.get(IDEMPOTENCY_KEY_HEADER)
.map_or(false, |v| !v.is_empty()),
.is_some_and(|v| !v.is_empty()),
_ => false,
};

Expand Down
2 changes: 1 addition & 1 deletion tests/common/mock_server/middlewares.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub(super) async fn ensure_idempotency_key(req: &mut ServiceRequest) -> Result<(
.get("Idempotency-Key")
.map(|v| v.to_str())
.transpose()?
.map_or(false, |v| !v.is_empty()),
.is_some_and(|v| !v.is_empty()),
"Invalid or missing Idempotency Key"
);

Expand Down
10 changes: 0 additions & 10 deletions tests/common/test_context/local_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,4 @@ impl TestContext {
.complete_mock_bank_redirect_authorization(redirect_uri, action)
.await
}

pub async fn submit_provider_return_parameters(
&self,
_query: &str,
_fragment: &str,
) -> Result<(), anyhow::Error> {
// This is only necessary for acceptance tests to work correctly.
// This work is usually done by TrueLayer's SPA upon redirect from the provider.
Ok(())
}
}
26 changes: 0 additions & 26 deletions tests/common/test_context/sandbox.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
use crate::common::MockBankAction;
use anyhow::Context;
use serde_json::json;
use std::str::FromStr;
use truelayer_rust::{apis::auth::Credentials, client::Environment, TrueLayerClient};
use url::Url;

static SANDBOX_RETURN_PARAMETERS_URI: &str = "https://pay-api.truelayer-sandbox.com";

pub struct TestContext {
pub client: TrueLayerClient,
pub merchant_account_gbp_id: String,
Expand Down Expand Up @@ -83,27 +80,4 @@ impl TestContext {

Ok(Url::from_str(&provider_return_uri)?)
}

pub async fn submit_provider_return_parameters(
&self,
query: &str,
fragment: &str,
) -> Result<(), anyhow::Error> {
reqwest::Client::new()
.post(
Url::parse(SANDBOX_RETURN_PARAMETERS_URI)
.unwrap()
.join("/spa/submit-provider-return-parameters")
.unwrap(),
)
.json(&json!({
"fragment": fragment,
"query": query
}))
.send()
.await?
.error_for_status()?;

Ok(())
}
}
Loading
Loading