# Drivers

Every outside service is a driver behind a contract (PLAN › Architecture). A module defines the contract and
registers its drivers; Platform keeps the shop's switches for them and the plumbing they share.

## Registering a driver

```php
$this->app->make(Drivers::class)->register(new DriverDefinition(
    DriverFamily::Payment, 'netopia', 'Netopia', NetopiaDriver::class,
    fields: [CredentialField::text('signature', 'checkout.netopia.signature'), CredentialField::secret('api_key', '…')],
    sandbox: true,
));
```

A registered driver is *implemented*; the shop makes it *available* in Settings → Integrations
(`integrations`: `is_enabled`, `is_default`, `sandbox`, `credentials` encrypted). `Platform\Contracts\Drivers`
gives `enabled()`, `default()` and `make($family, $key, Contract::class)`, which builds the class through the
container with a `DriverConfig` (`config` argument: credentials and sandbox). `make()` works for a switched-off
driver too, so old orders can still be followed up. `CredentialField` types: `text`, `secret` (kept on blank, never
echoed), `number`, `switch`. A driver that implements `Platform\Contracts\ChecksConnection` gets a connection test
(a `CheckReport`).

## Shared plumbing

- `Platform\Contracts\IntegrationLog::record()` writes `integration_logs` with `Drivers\Redactor` taking out keys that
  look like passwords, secrets, tokens, keys, signatures, card data, IBANs and CNPs. A failed write never breaks the
  call.
- Webhooks: `POST /webhooks/{family}/{driver}` (outside the web group: no session, no CSRF; throttled) stores the
  call in `webhook_calls` as it arrived (headers without cookies or authorization, query, raw body), answers with
  the family handler's `acknowledgement()`, and queues `ProcessWebhook`, which runs the handler once
  (`processed_at`, under a row lock) and records `accepted`, `reference`, `message`. Handlers implement
  `Platform\Contracts\WebhookHandler` and register per family in `WebhookHandlers`; they verify through the driver
  and must be idempotent.

## Payments (Checkout module)

`Checkout\Contracts\PaymentDriver`: `start(PaymentRequest): PaymentStart` (a redirect URL or a self-submitting
form), `notification(IncomingWebhook): PaymentResult`, `returned(reference, query): ?PaymentResult` (null when the
return is not signed), `status(reference, providerReference)`, `refund(reference, providerReference, Money)`
(`RefundResult`: executed, unsupported or failed) and `acknowledgement()`. `PaymentOutcome` is the one vocabulary:
paid, awaiting, declined, cancelled, not_found, unverifiable. Amounts are `Money` in minor units.

`Checkout\Contracts\Payments` runs it for orders: a `payments` row per attempt (our `reference` UUID, amount,
outcome, provider reference, reason), `start()` with the default driver, `returned()` (a signed return, else a
status query), `latest()`. `Payments\RecordPaymentResult` records a verified answer once (a settled payment is not
changed again; a paid amount other than the one asked is left unverifiable) and moves the order to paid through
`OrderBook::changeStatus()`. `Payments\PaymentWebhooks` handles the family's notifications.

`PaymentMethod::Card` is offered when a payment driver is on. Storefront: placing a card order redirects to the
processor; `/plata/{reference}` (`payment.return`) reads the return; `POST /comanda/{token}/plateste` starts a new
attempt after a declined one.

Answers from a demo driver count only while it is switched on (a real processor switched off is still heard, since
money moved), so a demo link can never pay a real shop's order.

Drivers in code: `DemoPaymentDriver` (registered; its page at `/payments/demo/{reference}`, signed links, signs its
answers with the app key) and `FakePaymentDriver` (tests only: register it, script `$outcome`/`$paid`, read
`$started`).

## Couriers (Fulfilment module)

`Fulfilment\Contracts\CourierDriver`: `createShipment(ShipmentRequest): ShipmentResult` (AWB, tracking URL, label
PDF when returned at once, cost), `label(awb, format)`, `track(awb): TrackingResult` (a `ShipmentStatus` with the
courier's events), `cancel(awb)`. Optional: `QuotesShipping::quote()` and `SupportsLockers::lockers()`, for the
drivers that can. Checkout reaches them only through `Fulfilment\Contracts\CourierNetwork`: `lockerNetworks()` (the
enabled couriers implementing `SupportsLockers`), `lockers(driver, search)`, `locker(driver, id, search)`,
`quotes()` and `quote(ShipmentRequest)` from the default courier, cached an hour per destination, weight, parcels
and cash on delivery; every failure there is reported and reads as "no lockers" or "no price". The demo courier
prices parcels and has three made-up lockers in any locality. `Shipments::create()` sends a locker order to its
locker (`lockerId`, the locker's address) and refuses another courier.

`Fulfilment\Contracts\Shipments`: `create(orderId, driver, weightGrams, parcels)` builds the request from the order
(shipping or billing address, cash on delivery = the total for `cod`, declared value, contents), stores the
shipment (`shipments`, label on the private disk), and `label()`, `cancel()` (only while `registered`), `track()`,
`trackOpen()` (the `fulfilment:track` task, every 30 minutes, 60 days back). Tracking moves the order through
`OrderBook::changeStatus()`: in transit → picking/shipped, delivered → delivered, returned → returned.

Drivers in code: `DemoCourierDriver` (registered; AWBs move by time, kept in the cache; labels from
`Platform\Data\DemoPdf`) and `FakeCourierDriver` (tests: `$status`, `$refuse`, `$booked`, `$cancelled`).

## Invoicing (Invoicing module)

`Invoicing\Contracts\InvoiceDriver`: `issue(InvoiceDraft): IssuedInvoice` (series, number, date, the service's id,
the PDF when returned at once, the e-Factura status), `reverse(InvoiceReference, date)` (a full credit note) and
`pdf(InvoiceReference)`. The service numbers invoices and sends them to e-Factura; the seller is the shop's account
there. A foreign-currency draft carries its currency; the driver shows VAT in RON at the BNR rate of the issue date.

`Invoices\DraftBuilder` turns an order's frozen totals into `InvoiceLine`s (products at the price paid, each followed by
the discounts that came off it at its VAT rate, gifts at 0, delivery, the SGR deposit at 0 % VAT) and refuses
when they do not add up to the order total. `Invoicing\Contracts\Invoices`: `issue(orderId)` (one standing invoice
per order, under a lock; not for cancelled orders), `reverse(invoiceId)`, `pdf()`, `forOrder()`; `invoices` table,
PDFs on the private disk. Permission `invoices.manage`.

Drivers in code: `DemoInvoiceDriver` (registered; DEMO series numbered in the cache, PDF from `DemoPdf`) and
`FakeInvoiceDriver` (tests: `$issued`, `$reversed`, `$refuse`).

## Marketplaces (Marketplaces module)

`Marketplaces\Contracts\MarketplaceDriver`: `newOrders()`, `changedSince(moment)` (both `list<MarketplaceOrder>`:
lines by SKU with gross unit price and VAT rate, shipping and a negative discount with VAT, buyer, billing and delivery
`MarketplaceAddress` by names, pickup point, `PaymentMethod`), `acknowledge(orderId)` and
`setStatus(orderId, MarketplaceStatus)` (new, in_progress, prepared, finalized, cancelled, returned).

`Actions\ImportOrder` finds the variants with `VariantDirectory::variantsBySku()`, builds `TotalsLine`s, the voucher as
an `Adjustment` without lines, delivery at the standard rate, then `Totals::withVatSummary()` (the VAT stage's logic,
now on `Totals` for orders made elsewhere), matches county and locality in the address register, and places the order
through `OrderBook::place()` with `source` `marketplace:{driver}:{id}` (no deposit, courier delivery). Paid on the
marketplace (`PaymentMethod::Marketplace`, prepaid) moves it to paid. Only then is the order acknowledged. Problems
(unknown SKU, `OrderRefused`) keep a `marketplace_orders` row in state `failed` with the reason; it stays new on the
marketplace and is tried again. `Actions\SyncMarketplace` runs import, then `changedSince(last run − 10 min)` and
cancels shop orders cancelled there; `marketplaces:sync` (every 5 minutes, one at a time under a cache lock) runs it for
each enabled driver. `Listeners\PushOrderStatus` maps picking → prepared, shipped/ready/delivered → finalized,
cancelled → cancelled and queues `Jobs\PushStatus` (5 tries), skipping what the marketplace already says.
`PlacedOrder::marketplace()` and `channel()` (`marketplace` in the ledger); `SendOrderMail` sends marketplace buyers
nothing. Admin: `admin.marketplaces.*` (`orders.manage`).

`Drivers\Emag\EmagDriver`: eMAG Marketplace API v4 at `marketplace-api.emag.{ro,bg,hu}/api-3`, Basic auth, JSON
`{isError, messages, results}`; `order/read` by status 1 or `modifiedAfter` (Bucharest time), 100 a page;
`order/acknowledge/{id}`; status saved by reading the order and posting it back to `order/save` with the new status
(0 cancelled with `cancellation_reason`, 1 new, 2 in progress, 3 prepared, 4 finalized, 5 returned). Product prices
come without VAT and are grossed up per line; removed lines (status 0) are left out; vouchers are
`sale_price + sale_price_vat`. The log keeps only `isError` and `messages`, never the buyer. Tested against
`Http::fake()`: confirm the shapes on a seller account. `DemoMarketplaceDriver` (registered) places one order a day
from the first public product; `FakeMarketplaceDriver` for tests (`$new`, `$changed`, `$acknowledged`, `$statuses`,
`$refuse`).

Not built yet: offers (price and stock pushed to eMAG), AWBs through eMAG's own courier contracts, and returns (RMA).

## Messaging (Chat module)

- `Chat\Contracts\MessagingDriver`: `channel()`, `receive(IncomingWebhook)` → `list<InboundMessage>` (the signature
  checked first; receipts and echoes skipped), `send($to, $text, $hoursSinceCustomer)` (throws `MessagingRefused`
  outside the reply window), `verify($query)` for the GET handshake, `replyWindowHours()`.
- Drivers (`DriverFamily::Messaging`): `Drivers\Meta\WhatsAppDriver` (Cloud API v26.0, `/{phone_number_id}/messages`,
  24 h, Meta error 131047 = window) and `Drivers\Meta\MessengerDriver` (`/me/messages`, `RESPONSE` within 24 h,
  `MESSAGE_TAG` + `HUMAN_AGENT` up to 7 days when switched on, parts of 2,000 characters; subcode 2018278 = window),
  sharing `TalksToMeta` (X-Hub-Signature-256 HMAC of the raw body with the app secret, hub.challenge, Bearer token);
  `DemoMessagingDriver` (unsigned JSON in, replies kept in the cache).
- Webhooks: `POST /webhooks/messaging/{driver}` through the usual store-then-queue path to
  `Chat\Channels\MessagingWebhooks`; `GET /webhooks/messaging/{driver}` answers the handshake through the new
  `Platform\Contracts\VerifiesWebhooks` (switched-on channels only).

## Drivers lifted from ELVPro

| Driver | Class | Notes |
|---|---|---|
| NETOPIA Payments | `Checkout\Payments\Drivers\Netopia\NetopiaDriver` | v2 hosted page (`payment/card/start`, no card data); IPN JWT RS512 verified natively (signature, `iss`, `aud` = POS signature, `exp`, `sub` = SHA-512 of the raw body); bundled public key; charges RON (converted); unsigned return and no public status or refund API, so the IPN settles and refunds are `unsupported`. |
| Stripe | `Checkout\Payments\Drivers\Stripe\StripeDriver` | Plain HTTP (no SDK): Checkout Session with `client_reference_id`; webhooks verified by `Stripe-Signature` (HMAC-SHA256 of `t.body`, 300 s tolerance); the return reads the session back (`cs_…`); refunds through the payment intent; the connection test calls `/balance`. Order currency. |
| PayU | `Checkout\Payments\Drivers\PayU\PayUDriver` | OAuth client credentials (token cached per POS and environment); `/api/v2_1/orders` without following its 302; a notification only names an order, which is read back (`extOrderId` from PayU, not from the notification) and captured when `WAITING_FOR_CONFIRMATION`; refunds via `/refunds`. |
| EuPlătesc | `Checkout\Payments\Drivers\EuPlatesc\EuPlatescDriver` | Hosted form (`PaymentStart::$html`); `GatewaySignature` HMAC-MD5 over length-prefixed fields with the hex key; the same signed answer by IPN and at the fixed return address `payment.back`; invoice id = `PaymentRequest::$merchantReference`; RON; refunds `unsupported`. |
| LibraPay | `Checkout\Payments\Drivers\LibraPay\LibraPayDriver` | Hosted form, HMAC-SHA1 (`STRING` and `P_SIGN`, `-` for empty optional fields); `DATA_CUSTOM` is LibraPay's base64 PHP-serialised order and buyer data; `BACKREF` = `payment.back` in the buyer's language; IPN acknowledged with `1`; RON; refunds `unsupported`. |
| ING WebPay, BT iPay | `Checkout\Payments\Drivers\Bpc\BpcDriver` | One class for both BPC `payment/rest` banks (keys `ing`, `bt`; `DriverConfig::$key` says which): `register.do` (BT gets the merchant reference as `orderNumber`, ING `FORCE_3DS2` and a `reconciliationId`), every answer read back with `getOrderStatusExtended.do`, refunds `reverse.do` then `refund.do`; errorCode 6 on a dummy order is the connection test's pass. |
| Sameday | `Fulfilment\Shipments\Drivers\Sameday\SamedayDriver` | 12-hour token cached per account and environment; city id found by name within the order's county; COD and insured value in RON; label `A4`/`A6`; `SupportsLockers` over the cached easybox list; connection test lists pickup points. Shapes follow Sameday's SDK: confirm on the sandbox before going live. |
| FAN Courier | `Fulfilment\Shipments\Drivers\FanCourier\FanCourierDriver` | v2: 24-hour Bearer from `/login`, `/intern-awb` (county and locality by name), `/awb/label`, `/reports/awb/tracking` (S-codes), `QuotesShipping` via `/reports/awb/internal-tariff`, FANbox lockers (service FANbox, option V, `pickupLocationId`). Domestic only. |
| Cargus | `Fulfilment\Shipments\Drivers\Cargus\CargusDriver` | V3: APIM subscription key plus a 24-hour Bearer from `/LoginUser`; `/Awbs` answers a bare barcode; base64 label; service 34/35/36 by weight, 39/40 for several parcels; V3 limits refused with the reason; statuses read from Cargus's wording. |
| DPD | `Fulfilment\Shipments\Drivers\Dpd\DpdDriver` | Speedy API: credentials in every body (logged without them); the shipment id is the AWB; cancel via `/shipment/cancel`; statuses from DPD's wording. Confirm the service id, the cancel call and the wording on DPD test credentials. |
| GLS | `Fulfilment\Shipments\Drivers\Gls\GlsDriver` | MyGLS: username, SHA-512 password as a byte list and client number in every body; `PrintLabels` books and returns the label at once; numeric statuses; ParcelShops from GLS's public feed (PSD service); no cancel call (the portal). |
| SmartBill | `Invoicing\Invoices\Drivers\SmartBill\SmartBillDriver` | Basic auth; in-band `errorText`; discounts as `isDiscount` lines with `numberOfItems: 1` right after their product; tax names from settings; payment recorded when paid; `exchangeRate` from `ExchangeRates::on()` for foreign currency; `seriesname` lower case on the PDF endpoint. |

| Oblio | `Invoicing\Invoices\Drivers\Oblio\OblioDriver` | OAuth2 client credentials (token cached); in-band `status`; value discount lines (`discountType: valoric`, `discountAllAbove: 0`) after their product; credit note = a new invoice with the original draft's lines negated; `collect` when paid; the PDF from the document `link` kept as the external id. |
| FGO | `Invoicing\Invoices\Drivers\Fgo\FgoDriver` | Body signature: uppercase SHA-1 of CIF + private key + client name (issue) or number (operations), as FGO's protocol requires; net `PretUnitar` with `CotaTVA`; credit note via `/factura/stornare`; the PDF from the `Link` kept as the external id; UAT host in test mode; the connection test reads HTTP 409 as a refused signature. |

Hosted-form gateways sign fields with `Checkout\Payments\Drivers\Support\GatewaySignature` and hand the buyer over
with `HostedForm::html()`. Banks that return to a fixed address post to `payment.back` (`/plata/{driver}`, GET or
POST): it runs without the session and CSRF (a cross-site post carries no cookie and must not replace it), asks
`Payments::returnedFrom()` to verify the fields through `PaymentDriver::returned('', $fields)`, then redirects to the
payment's own `payment.return`, which has the buyer's session. `Payment::locate()` finds a payment by our UUID, the
15-digit merchant reference or (after the driver asked the provider) the provider's reference.

`InvoiceDriver::reverse()` receives the original draft too (rebuilt from the order's frozen totals at the original
issue date), for the services that re-send the lines.

Each logs through `IntegrationLog` (no credentials or tokens) and is tested against `Http::fake()`
(`tests/Feature/Checkout/NetopiaTest.php`, `tests/Feature/Checkout/ProcessorsTest.php`, `tests/Feature/Fulfilment/SamedayTest.php`, `tests/Feature/Fulfilment/CouriersTest.php`,
`tests/Feature/Invoicing/SmartBillTest.php`, `tests/Feature/Invoicing/OblioFgoTest.php`). `CredentialField::textarea()` holds multi-line values such as a PEM key.

Tests: `tests/Feature/Checkout/PaymentsTest.php`, `tests/Feature/Fulfilment/ShipmentsTest.php`,
`tests/Feature/Invoicing/InvoicesTest.php`,
`tests/Feature/Platform/IntegrationsTest.php`, `tests/Feature/Marketplaces/MarketplacesTest.php`.

## Saved cards and recurring charges

A payment driver that can keep a card and charge it again implements `Checkout\Contracts\SupportsRecurring`
(`charge(PaymentRequest, CardToken): PaymentResult`). Stripe, the demo and the fake driver do; NETOPIA's token
flow is still to be verified against its sandbox.

- `PaymentRequest::$saveCard` is set when the order carries the buyer's consent to recurring charges
  (`PlacedOrder::$recurringConsentAt`) and the driver supports it. Stripe then opens the session with
  `customer_creation: always` and `setup_future_usage: off_session`; its paid result reads the card back from the
  PaymentIntent (`expand[]=payment_method`) into `PaymentResult::$card`.
- `RecordPaymentResult` saves that card in `payment_cards` (token and processor customer encrypted; brand, last four
  and expiry in clear) for the order's customer, only with the consent.
- `Payments::chargeCard($order, $cardId)` is the merchant-initiated payment: Stripe confirms an off-session
  PaymentIntent with the attempt's reference as idempotency key. A card that needs 3-D Secure comes back declined
  with `authentication_required`; the caller then sends the buyer a payment link. A card that is not the order's
  customer's, or a driver that is off, is never charged (`no_recurring`).
- Saved cards are personal data: exported as "Visa ···· 4242" with the expiry, deleted with the account.
