Skip to main content

adk_payments/wallet/
ap2.rs

1//! The AP2 rail: purchases under AP2 mandates (spec 3.5 §7.14, §13 Q5).
2//!
3//! The site buys as an AP2 shopper. The merchant's signed cart mandate is the payment's
4//! rail data; the rail builds the payment mandate for exactly that cart, has the owner's
5//! credentials provider authorise it — never the agent — and submits it to the merchant
6//! agent through an [`Ap2MerchantEndpoint`], which on the merchant's side is an
7//! [`Ap2Adapter`](crate::protocol::ap2::Ap2Adapter).
8
9use std::sync::Arc;
10
11use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
12use async_trait::async_trait;
13use chrono::Utc;
14use serde::{Deserialize, Serialize};
15use serde_json::{Map, Value, json};
16
17use super::error::{WALLET_RAIL_DATA_MISMATCH_CODE, refused};
18use super::policy::RailRef;
19use super::rail::{PaymentRail, RailPayment, RailSettlement};
20use crate::domain::Money;
21use crate::kernel::PaymentExecutionOutcome;
22use crate::protocol::ap2::{
23    CartMandate, PaymentMandate, PaymentMandateContents, PaymentReceipt, PaymentResponse,
24};
25
26/// What a merchant agent answered to a payment mandate.
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28#[serde(rename_all = "camelCase")]
29pub struct Ap2Settlement {
30    /// The merchant's outcome.
31    pub outcome: PaymentExecutionOutcome,
32    /// The merchant's reference for the payment.
33    pub reference: String,
34    /// The merchant's receipt, when it returned one.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub receipt: Option<PaymentReceipt>,
37}
38
39/// Where the wallet sends AP2 payment mandates: the merchant agent's AP2 endpoint, over A2A
40/// in production.
41#[async_trait]
42pub trait Ap2MerchantEndpoint: Send + Sync {
43    /// Submits `mandate` for the cart `cart` describes.
44    ///
45    /// # Errors
46    ///
47    /// Returns the merchant's refusal or a transport error.
48    async fn submit_payment_mandate(
49        &self,
50        cart: &CartMandate,
51        mandate: PaymentMandate,
52    ) -> Result<Ap2Settlement>;
53}
54
55/// The owner's credentials provider: authorises a payment mandate on the owner's behalf
56/// within the wallet's mandate (spec 3.5 §7.14). The agent never holds this authority.
57#[async_trait]
58pub trait Ap2UserAuthorizer: Send + Sync {
59    /// The user authorization over `contents`, such as an SD-JWT the merchant verifies.
60    ///
61    /// # Errors
62    ///
63    /// Returns the provider's refusal.
64    async fn authorize(&self, contents: &PaymentMandateContents) -> Result<String>;
65}
66
67/// The rail data of an AP2 purchase: the merchant's signed cart mandate.
68///
69/// # Example
70///
71/// ```rust,ignore
72/// let request = PaymentRequest::new(key, SpendCategory::Domains, payee, 1_500, "USD")
73///     .with_rail_data(Ap2RailData { cart_mandate }.into_value());
74/// ```
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77pub struct Ap2RailData {
78    /// The merchant's signed cart.
79    pub cart_mandate: CartMandate,
80}
81
82impl Ap2RailData {
83    /// The data as a payment request's `rail_data`.
84    pub fn into_value(self) -> Value {
85        serde_json::to_value(self).unwrap_or(Value::Null)
86    }
87}
88
89/// AP2 mandates for purchases (spec 3.5 §7.14).
90///
91/// A cart from another merchant than the payee, or at another total than the payment the
92/// wallet allowed, is refused before any money moves. A merchant answer other than
93/// authorised or completed fails the payment, and the wallet voids its debit.
94pub struct Ap2Rail {
95    endpoint: Arc<dyn Ap2MerchantEndpoint>,
96    authorizer: Arc<dyn Ap2UserAuthorizer>,
97}
98
99impl Ap2Rail {
100    /// A rail submitting to `endpoint`, authorised by `authorizer`.
101    pub fn new(
102        endpoint: Arc<dyn Ap2MerchantEndpoint>,
103        authorizer: Arc<dyn Ap2UserAuthorizer>,
104    ) -> Self {
105        Self { endpoint, authorizer }
106    }
107}
108
109fn cart_of(payment: &RailPayment) -> Result<CartMandate> {
110    let data = payment.rail_data.clone().ok_or_else(|| {
111        refused(
112            WALLET_RAIL_DATA_MISMATCH_CODE,
113            "an AP2 purchase carries the merchant's cart mandate as its rail data",
114        )
115    })?;
116    let data: Ap2RailData = serde_json::from_value(data).map_err(|error| {
117        refused(
118            WALLET_RAIL_DATA_MISMATCH_CODE,
119            format!("the AP2 rail data is not a cart mandate: {error}"),
120        )
121    })?;
122    Ok(data.cart_mandate)
123}
124
125/// The cart's total in minor units of `currency`, or why it cannot be paid as `currency`.
126fn cart_total(cart: &CartMandate, currency: &str) -> std::result::Result<u64, String> {
127    let total = &cart.contents.payment_request.details.total.amount;
128    if !total.currency.eq_ignore_ascii_case(currency) {
129        return Err(format!("the cart is in {}, not {currency}", total.currency));
130    }
131    let scale = Money::iso_minor_unit_scale(currency).unwrap_or(2);
132    let money = total.to_money().map_err(|error| error.to_string())?;
133    let money = money.rescaled(scale).map_err(|error| error.to_string())?;
134    u64::try_from(money.amount_minor).map_err(|_| "the cart total is negative".to_string())
135}
136
137#[async_trait]
138impl PaymentRail for Ap2Rail {
139    fn rail(&self) -> RailRef {
140        RailRef::ap2()
141    }
142
143    fn check(&self, payment: &RailPayment) -> Result<()> {
144        let cart = cart_of(payment)?;
145        let merchant = &cart.contents.merchant_name;
146        let names_payee = merchant.eq_ignore_ascii_case(&payment.payee.id)
147            || payment
148                .payee
149                .name
150                .as_deref()
151                .is_some_and(|name| merchant.eq_ignore_ascii_case(name));
152        if !names_payee {
153            return Err(refused(
154                WALLET_RAIL_DATA_MISMATCH_CODE,
155                format!("the cart is from {merchant}, not payee {}", payment.payee.id),
156            ));
157        }
158        let total = cart_total(&cart, &payment.currency)
159            .map_err(|reason| refused(WALLET_RAIL_DATA_MISMATCH_CODE, reason))?;
160        if total != payment.amount {
161            return Err(refused(
162                WALLET_RAIL_DATA_MISMATCH_CODE,
163                format!("the cart totals {total}, not the {} the wallet allowed", payment.amount),
164            ));
165        }
166        Ok(())
167    }
168
169    async fn execute(&self, payment: &RailPayment) -> Result<RailSettlement> {
170        let cart = cart_of(payment)?;
171        let details = &cart.contents.payment_request.details;
172        let method = cart
173            .contents
174            .payment_request
175            .method_data
176            .first()
177            .map_or_else(|| "CARD".to_string(), |method| method.supported_methods.clone());
178        let mut funding = Map::new();
179        if let Some(debit) = &payment.debit {
180            funding.insert("debitId".to_string(), Value::String(debit.id.clone()));
181            if let Some(token) = &debit.funding_token {
182                funding.insert("fundingToken".to_string(), Value::String(token.clone()));
183            }
184        }
185        let contents = PaymentMandateContents {
186            payment_mandate_id: payment.payment_id.clone(),
187            payment_details_id: details.id.clone(),
188            payment_details_total: details.total.clone(),
189            payment_response: PaymentResponse {
190                request_id: details.id.clone(),
191                method_name: method,
192                details: Some(funding),
193                shipping_address: None,
194                shipping_option: None,
195                payer_name: None,
196                payer_email: None,
197                payer_phone: None,
198            },
199            merchant_agent: cart.contents.merchant_name.clone(),
200            timestamp: Utc::now().to_rfc3339(),
201        };
202        let user_authorization = self.authorizer.authorize(&contents).await?;
203        let mandate = PaymentMandate {
204            payment_mandate_contents: contents,
205            user_authorization: Some(user_authorization),
206        };
207        let settled = self.endpoint.submit_payment_mandate(&cart, mandate).await?;
208        match settled.outcome {
209            PaymentExecutionOutcome::Authorized | PaymentExecutionOutcome::Completed => {
210                Ok(RailSettlement {
211                    reference: settled.reference.clone(),
212                    amount: payment.amount,
213                    settled_at: Utc::now(),
214                    proof: Some(json!({
215                        "merchant": cart.contents.merchant_name,
216                        "outcome": settled.outcome,
217                        "receipt": settled.receipt,
218                    })),
219                })
220            }
221            PaymentExecutionOutcome::InterventionRequired | PaymentExecutionOutcome::Failed => {
222                Err(AdkError::new(
223                    ErrorComponent::Tool,
224                    ErrorCategory::Unavailable,
225                    "wallet.ap2.not_settled",
226                    format!(
227                        "{} answered the payment mandate with {:?}; nothing was paid",
228                        cart.contents.merchant_name, settled.outcome
229                    ),
230                ))
231            }
232        }
233    }
234}