Skip to main content

Payment accounts

An install normally runs one provider, configured once: billing.default, billing.mollie.api_key or cashier.secret. An application that takes payments for many shops, each with its own account at Mollie or Stripe, needs a second way: the credential belongs to the shop of the request, not to the install, and it comes from wherever the application keeps it.

That way is a PaymentAccount, handed to BillingManager::forAccount():

use Pushery\Billing\Support\BillingManager;
use Pushery\Billing\ValueObjects\Money;
use Pushery\Billing\ValueObjects\PaymentAccount;

$account = new PaymentAccount(
provider: 'mollie',
key: $shop->uuid,
credential: $shop->mollieAccessToken(),
testmode: $shop->isInTestMode(),
profileId: $shop->mollieProfileId(),
webhookSecret: $shop->mollieWebhookSecret(),
);

$result = app(BillingManager::class)
->forAccount($account)
->rails()
->charge(Money::of(1900, 'EUR'), 'ideal', idempotencyKey: $order->uuid);

The driver that comes back charges with that account and no other: its client carries the account's credential and test mode, every payment it creates at Mollie carries the account's profile, and Mollie posts the status pings to an address that names the account. A second account gets a client of its own.

What an account holds​

FieldWhat it is
providerthe driver the account belongs to, mollie or stripe
keyyour stable name for the account. It becomes part of the account's webhook address, so lowercase letters, digits and inner hyphens, at most 64 characters
credentialthe API key, or for Mollie an OAuth access token
testmodewhether calls go to the provider's test mode
profileIdthe Mollie profile payments are created on. Mollie requires it with an OAuth access token and ignores it with an API key
webhookSecretthe secret the provider signs this account's webhooks with
redirectHoststhe hosts the provider serves this account's payment pages from beside its own, such as the custom domain of a Stripe account's Checkout. Host names only, such as payments.example.com

A Mollie or Stripe API key picks its mode by its prefix (test_ or live_, sk_test_ or sk_live_). An account whose testmode disagrees with its key is refused when its driver is built, before anything reaches the provider, because the key would win and the account would charge in the mode nobody asked for. An OAuth access token carries no mode, so the client is told the account's.

Paying for an order​

charge() takes ChargeOptions as its last argument, for what the shop's checkout decided about one payment:

use Pushery\Billing\ValueObjects\ChargeOptions;
use Pushery\Billing\ValueObjects\PaymentAddress;

$result = app(BillingManager::class)->forAccount($account)->rails()->charge(
Money::of(5990, 'EUR'),
'',
idempotencyKey: $order->uuid,
options: new ChargeOptions(
returnUrl: route('shop.orders.show', $order),
cancelUrl: route('shop.cart'),
locale: 'de_DE',
methods: ['klarna', 'in3'],
metadata: ['shop' => $shop->uuid, 'order' => $order->number],
lines: $order->paymentLines(),
billingAddress: new PaymentAddress(givenName: 'Ada', familyName: 'Lovelace', streetAndNumber: 'Keizersgracht 1', postalCode: '1015 CJ', city: 'Amsterdam', country: 'NL'),
),
);
OptionMollieStripe, with a payment method
returnUrlthe redirectUrl, in place of the install'sthe return_url, in place of billing.stripe.return_url
cancelUrlwhere a customer who cancels goesnot used
webhookUrlin place of the account's addressnot used, Stripe posts to the endpoints of the account
localethe language of the checkoutnot used, Stripe.js picks it in the browser
methodsthe methods offered, empty for all of the account'snot used, the payment method decides
metadatakept with the paymentkept with the payment intent
lines, billingAddress, shippingAddresssent with the paymentnot used
cardTokenthe token from Mollie Components, with the creditcard methodnot used
applePayTokenthe token Apple Pay handed the page, with the creditcard methodnot used, Stripe's wallets create a payment method in the browser
captureModemanual authorizes a card payment and leaves the capture to younot used

Some Mollie methods refuse a payment without lines or a billing address, Klarna, in3, Billie and Riverty among them. Each PaymentLine states its amounts VAT included, and the lines add up to the amount charged; a charge whose lines disagree with it is refused before anything reaches Mollie. At Mollie the token names one method or stays empty, and a charge that names a method as its token and in its options is refused as well. The metadata holds text and whole numbers, and billing_reference is the key the rails write themselves, so no option can carry it.

On Stripe's checkout page​

A charge into a Stripe account that names no payment method, an empty token as above, opens a Checkout Session on the account. The customer picks the method on Stripe's page, as on Mollie's checkout, and the result hands the page out the same way: requiresAction is true, clientSecret is the page's address and reference the session's id. A charge with a payment method created in the browser stays a payment intent that Stripe.js confirms.

OptionOn Stripe's checkout page
returnUrlthe success_url, in place of billing.stripe.return_url. Without either the charge is refused
cancelUrlwhere a customer who cancels goes
localethe language of the page where Stripe has it, such as de for de_DE, otherwise Stripe's choice
methodsthe Stripe ids offered, such as card and klarna, empty for all the account has turned on
metadatakept with the session and with the payment intent Stripe creates when the customer pays
linesthe session's line items, where each line's total is its unit price times its quantity. A line with a discount or below zero cannot be one, and then the session has one line for the amount that names the lines
expiresAtwhen the session stops taking the payment, its expires_at. Stripe takes 30 minutes to 24 hours after the session is created, and a charge outside that is refused before Stripe hears of it. Without one the session lasts Stripe's day
webhookUrl, billingAddress, shippingAddress, cardToken, applePayToken, captureModenot used

Stripe creates the payment intent only when the customer pays, so its events report the payment under the intent's id, with the charge's idempotency key as billingReference and its metadata. A session the customer never pays expires after a day, or at its expiresAt, and that is reported under the session's id with the status Expired.

A Stripe account with a custom domain serves its Checkout there. Name the domain in the account's redirectHosts, and that account's charge sends the customer to it. Another account's charge and the install's own pages do not: billing.redirect_hosts covers the install's account, and a page on a host nobody listed counts as none, so the charge comes back pending with no page and the refusal is logged with the host.

The result names that host in refusedPageHost, in lower case and without the rest of the address. Stripe names an account's custom domain nowhere else, so this is where an application learns it. Whether the host goes into the account's redirectHosts is the application's decision; the package never sends anybody to a refused page.

Klarna, in3, Billie and Riverty​

These methods refuse a payment without its lines, and most of them without a billing address, so the charge carries both in its options. Their payments end in authorized, which AccountPaymentChanged reports, and the money moves once the payment is captured, usually when the order ships. A card payment created with the capture mode manual waits the same way. Capture it in full, or in parts as the parcels go out:

use Pushery\Billing\Drivers\Mollie\MollieCaptures;

$capture = app(MollieCaptures::class)->capture($account, $paymentReference, Money::of(2000, 'EUR'), 'First parcel');

A capture Mollie refuses comes back as a failed CaptureResult with Mollie's status and words, and an error that says nothing about the capture is thrown. Once the capture succeeds, Mollie pings the payment again and it is reported as paid.

Refunding a payment​

The rails of an account refund one of its payments, in full or in part, under your idempotency key:

$result = app(BillingManager::class)->forAccount($account)->rails()
->refund($paymentReference, Money::of(1000, 'EUR'), idempotencyKey: $return->uuid);

if ($result->failed()) {
$result->failureCode; // why the provider refused, in its own terms
$result->failureMessage; // the provider's words, where it gave any
}

A refusal of the refund itself comes back as such a result: at Stripe with its error code or the refund's failure_reason, at Mollie with the HTTP status or the refund's status, because Mollie names no error codes. An error that says nothing about the refund, such as a rejected credential, a rate limit or an outage, is thrown, so the refund can be tried again under the same key. A refund that fails after the provider accepted it is reported later, as an AccountPaymentChanged with the status RefundFailed.

Finding a refund again​

The idempotency key protects a retry only while the provider remembers it: an hour at Mollie, a day at Stripe. When the answer to a refund is lost, after the request went out and before the response came back, read the payment's refunds before you try again. The rails store your key with every refund they make, and the Mollie and Stripe rails implement ReadsRefunds:

use Pushery\Billing\Contracts\ReadsRefunds;
use Pushery\Billing\ValueObjects\RefundState;

$rails = app(BillingManager::class)->forAccount($account)->rails();

if ($rails instanceof ReadsRefunds) {
$made = collect($rails->refundsOf($paymentReference))
->first(fn (RefundState $refund): bool => $refund->key === $return->uuid);

$made?->standing(); // true: it went out, and is on its way or with the customer
$rails->refundableOf($paymentReference); // what can still be refunded, or null
}

Each RefundState carries the provider's reference, the key the refund was made under, its status as pending, refunded, failed or canceled, and its amount. A pending refund can still fail, so only refunded means the money reached the customer. refundableOf() is Mollie's own amountRemaining, and at Stripe what was captured less what was refunded. On a connected Mollie account, listing refunds needs the refunds.read permission and the remaining amount needs payments.read.

Canceling a payment​

A provider reports a payment on the webhook when its status changes, not when it is created, so a payment nobody completes is reported only when it expires. The rails of Mollie and of Stripe cancel such a payment, and the provider reports it right away: Mollie as Canceled, Stripe a payment on its checkout page as Expired and a payment intent as Canceled. They implement CancelsPayments:

use Pushery\Billing\Contracts\CancelsPayments;

$rails = app(BillingManager::class)->forAccount($account)->rails();

if ($rails instanceof CancelsPayments) {
$cancellation = $rails->cancel($paymentReference);

$cancellation->canceled; // true once the provider canceled it
$cancellation->failureCode; // otherwise why it kept it: Stripe's error code, the HTTP status where
// there is none, or the status the payment still has
$cancellation->failureMessage; // the provider's words, where it gave any
}

Mollie cancels a payment while its method allows it, an open one in most cases. A payment it keeps comes back as a cancellation that did not happen, and so does an id Mollie does not know. An error that says nothing about the payment, such as a rejected credential, a rate limit or an outage, is thrown, so the call can be made again. The rails cancel in the account's mode, so the rails of a test-mode copy of an account cancel the test payment they made. On a connected Mollie account, canceling needs the payments.write permission.

On Stripe, a charge made on its checkout page is a Checkout Session, and canceling it expires the session, which Stripe does only while the session is open: the customer can no longer pay on its page, and the account's webhook reports the payment as Expired. A shop that cancels when the customer comes back through the cancel address frees the order at once instead of at the end of the session's lifetime. Every other reference is a payment intent, which Stripe cancels until it succeeds. A session that is complete or expired comes back as a cancellation that did not happen, as does an intent that succeeded and an id Stripe does not know, with Stripe's code and words. The key decides the mode, so the rails of a test-mode account cancel the test payment they made, and a restricted key needs checkout_sessions_write and payment_intents_write.

Apple Pay, Google Pay and PayPal on the shop's domain​

At Mollie, Apple Pay runs on the shop's own page. When Apple Pay JS asks the page to validate the merchant, an endpoint of your application asks Mollie for the merchant session and answers Apple Pay with it, unchanged:

use Pushery\Billing\Drivers\Mollie\MollieApplePay;

return response()->json(
app(MollieApplePay::class)->session($account, $request->input('validationUrl'), $request->getHost()),
);

The domain serves Mollie's validation file at /.well-known/apple-developer-merchantid-domain-association. Once the customer has authorized the payment, the page sends Apple Pay's token to your application, and the charge carries it as applePayToken, JSON encoded. Mollie creates such a payment with the creditcard method, which the charge picks when it names no other. Google Pay and PayPal run on Mollie's checkout: offer googlepay or paypal as a method and the customer completes the payment there. Mollie's API and SDK name no Google Pay token for a page of your own.

At Stripe, register each shop domain with the merchant's account, with the merchant's own key:

use Pushery\Billing\Drivers\Stripe\StripePaymentMethodDomains;

$domain = app(StripePaymentMethodDomains::class)->register($account, 'shop.example');

$domain->wallets; // ['apple_pay' => true, 'google_pay' => true, 'link' => true, 'paypal' => false]

A domain the account has already is found rather than registered twice, and wallets says per wallet whether Stripe reports it active there. The Express Checkout Element then creates the payment method in the browser, and charge() confirms it with the payment method's id and the order's returnUrl, which a wallet or PayPal needs for its redirect.

Connecting a merchant's Mollie account​

A merchant who already has a Mollie account connects it to your platform's OAuth app, and stays the merchant at Mollie: no money is routed through the platform. Pushery\Billing\Drivers\Mollie\Connect\MollieConnect has the steps, and MollieOAuthApp holds the app's client id, client secret and the address Mollie sends the merchant back to.

use Pushery\Billing\Drivers\Mollie\Connect\MollieConnect;
use Pushery\Billing\Drivers\Mollie\Connect\MollieOAuthApp;

$app = new MollieOAuthApp($clientId, $clientSecret, 'https://lane.example/mollie/callback');
$connect = app(MollieConnect::class);

// 1. Send the merchant to Mollie, with a state you remember for this attempt.
return redirect($connect->authorizeUrl($app, ['payments.read', 'payments.write', 'refunds.read', 'refunds.write', 'profiles.read', 'methods.read', 'onboarding.read'], $state));

// 2. On the way back, after checking the state, exchange the code for tokens and store both, encrypted.
$tokens = $connect->exchangeCode($app, $request->query('code'));

// 3. Let the merchant pick the profile payments are created on.
$profiles = $connect->profiles(new PaymentAccount('mollie', $shop->uuid, $tokens->accessToken, testmode: false));

An access token expires after an hour, and a refresh token does not expire on its own. Refresh before $tokens->expiresWithin(300) says the access token runs out; Mollie may issue a new refresh token, and refresh() hands back the one it was given where it does not. revoke() ends the connection from your side.

onboarding() says where a connected account stands in Mollie's onboarding, for a check before a shop goes live:

$onboarding = $connect->onboarding($account);

$onboarding->permitted; // false without the onboarding.read permission, and then nothing else is known
$onboarding->status; // needs-data, in-review or completed
$onboarding->canReceivePayments; // whether Mollie lets the merchant take real payments
$onboarding->canReceiveSettlements; // whether Mollie pays the money out
$onboarding->dashboard; // the page in Mollie's dashboard where the merchant gives what is missing, or null

Mollie lets a merchant take payments while it still checks the details, and pays out only once the onboarding is complete. Without the onboarding.read permission the answer says so rather than throwing; every other refusal is thrown.

A merchant without a Mollie account goes through clientLink() instead, with the organization access token of your partner account. Mollie creates the account, links it to your partner account, and connects it to the app once it exists.

MollieTokens and MollieOAuthApp keep their secrets out of debuggers and refuse to be serialized, like an account. A refused code or refresh throws MollieConnectFailed with Mollie's error, and its refused() and unavailable() tell a connection that is lost from an answer Mollie could not give just now.

An account's client gives up quickly inside a web request: one attempt, ten seconds for the request and three for the connection. A queue worker, the scheduler and Artisan keep the SDK's five retries on the application's own timeouts. Both sets are billing.mollie.account_http. Where you hold a lock across calls to an account, size it with app(MollieClientFactory::class)->longestAccountCall(): the seconds one call can take at most, every attempt at its full timeout and every pause before a retry, in the set the current context uses.

Setting up a merchant's Stripe account​

A merchant connects a Stripe account with a key of their own, usually a restricted one (rk_live_…, rk_test_…). Pushery\Billing\Drivers\Stripe\StripeAccountSetup checks the key and sets up the account's webhook endpoint, each with the account's own key.

use Pushery\Billing\Drivers\Stripe\StripeAccountSetup;

$setup = app(StripeAccountSetup::class);

$missing = $setup->missingRights($account); // list<StripeAccountRight>, empty when the key holds them all

$endpoint = $setup->createWebhookEndpoint($account, 'https://shop.example/billing/webhook/stripe/'.$account->key);
// Keep $endpoint->id, and $endpoint->secret encrypted as the account's webhookSecret.

$setup->removeWebhookEndpoint($account, $endpointId); // when the merchant disconnects

$setup->seesWebhookEndpoint($account, $endpointId); // false where the key belongs to another Stripe account

A restricted key holds the rights the merchant gave it, and Stripe names them nowhere, so missingRights() asks for each with a request that carries a parameter Stripe does not know. Stripe answers it with a permission error where the key lacks the right and refuses the parameter where the key holds it, so nothing is read or created either way. Pass a list of StripeAccountRight cases to ask for some of them only. A key Stripe does not accept, a rate limit or an outage throws, because it says nothing about rights.

RightWhat it is for
checkout_sessions_writeCheckout Sessions on the account
payment_intents_writecharges
payment_intents_readthe account's webhooks, which read every payment they report back
disputes_readthe disputes a change about a refund or a dispute lists
payment_methods_reada payment method a charge or a mandate names
refunds_writerefunds
webhook_endpoints_writethe account's webhook endpoint
payment_method_configurations_readBillingManager::accountPaymentMethods()
payment_method_domains_writeStripePaymentMethodDomains, for the wallets on the shop's domain

The endpoint subscribes to the events the account's webhooks read, in the API version the package reads them in, as they stand when it is created. An endpoint created before charge.dispute.closed, charge.dispute.funds_withdrawn and charge.dispute.funds_reinstated joined them does not receive those: add them to the endpoint in Stripe's dashboard. Stripe hands out its signing secret only when it creates the endpoint, so keep it then. removeWebhookEndpoint() counts an endpoint Stripe no longer has as removed.

seesWebhookEndpoint() says whether the account's key sees an endpoint. An endpoint lives on one Stripe account and in one mode, so a new key that does not see the account's endpoint belongs to another account or to the other mode. Ask it before you take a new key over, and refuse a key that does not see it: the refunds and the open payments of the old account would be lost with it. Only Stripe's answer that it has no such endpoint is false; a key Stripe does not accept, a rate limit or an outage throws.

An account's client gives up quickly inside a web request as well: one attempt, ten seconds for the request and three for the connection, where the SDK would wait 80 and 30. A queue worker, the scheduler and Artisan keep the SDK's own numbers. Both sets are billing.stripe.account_http. An application that gave the Stripe SDK an HTTP client of another kind keeps it, with its own timeouts. Where you hold a lock across calls to an account, size it with StripeAccountClient::longestCall(): the seconds one call can take at most, every attempt at its full timeout and every pause before a retry, in the set the current context uses or the one servingRequest: names.

The credential stays out of logs and queues​

An account never shows its two secrets: var_dump, print_r and a debugger see them masked, and the refusals above name the account by its key, never by its credential. An account also refuses to be serialized, so it cannot reach a queue payload, a cache or a session by accident.

A job therefore carries the provider and the key, and finds the account again. Bind your own Pushery\Billing\Contracts\PaymentAccounts for that:

use Pushery\Billing\Contracts\PaymentAccounts;
use Pushery\Billing\ValueObjects\PaymentAccount;

final class ShopPaymentAccounts implements PaymentAccounts
{
public function find(string $provider, string $key): ?PaymentAccount
{
return Shop::query()->where('uuid', $key)->first()?->paymentAccount($provider);
}
}
$this->app->bind(PaymentAccounts::class, ShopPaymentAccounts::class);

The default knows no account and answers null for every pair.

Webhooks​

Each account has its own webhook address: the install's billing.webhook_path, followed by the provider and the key.

https://shop.example/billing/webhook/mollie/0b7c1e4a-2f63-4b8e-9a51-6d2f0c9e7a11

At Mollie, the account's driver sets this address on every payment it creates, so the classic status pings arrive there without any setup. At Stripe, StripeAccountSetup::createWebhookEndpoint() adds an endpoint with this address to the account, as above, and the signing secret it hands back is the account's webhookSecret.

A delivery to the address goes through these steps:

  1. The account is looked up through your PaymentAccounts, before anything in the request is trusted. An address that names no account you know answers 404, so the endpoint tells a caller nothing about which shops exist.
  2. The delivery is verified with the account's webhookSecret. Stripe signs every event, so a Stripe account without a secret has none of its webhooks accepted. Mollie's classic ping is not signed: it is read back from Mollie with the account's own credential, which a payment of another account does not answer to.
  3. It is recorded under the account's provider, with the account's key as its reference and the id of the payment it names, reported as an AccountPaymentChanged and queued to the effects registered for it. A redelivery to the same account is recognized as one; the same event id at another account is a different delivery. Mollie's ping names only the payment, so there a delivery is told apart by where the payment stands, its refunds that failed or were canceled included: a payment that is paid again after a refund was canceled is a delivery of its own, not a redelivery of the ping that first reported it paid.

billing:webhooks:replay reads a stored delivery of an account again with that account's mapper.

What happened to a payment​

Every webhook about a payment of an account is reported as Pushery\Billing\Events\AccountPaymentChanged, and only as that: an account's payment raises no add-on, subscription or marketplace event, so nothing of the install reads it as its own. The event says where the payment stood when the package read it, never what changed, and observedAt names that moment. A queue can still run a report after a newer one about the same payment: a listener that failed runs again later, or a delivery is replayed. A listener that stores the latest state keeps observedAt with it and drops a report that is not later:

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Pushery\Billing\Events\AccountPaymentChanged;

Event::listen(function (AccountPaymentChanged $change): void {
$key = "payment:{$change->paymentReference}:observed";
$held = Cache::get($key);

// A Redis store hands the number back as text, so it is read as a number, not tested for an int.
if (is_numeric($held) && (int) $held >= $change->observedAt->getTimestampMs()) {
return; // an older report, run after a newer one
}

Cache::forever($key, $change->observedAt->getTimestampMs());
// store $change->status and the amounts here
});
FieldWhat it is
provider, accountthe account the payment went into
paymentReferencethe provider's id of the payment, as the charge's result reported it
statusan AccountPaymentStatus
amountwhat the payment was for
amountRefundedwhat went back to the customer so far, failed refunds not counted
amountChargedBackwhat the customer's bank took back and still holds
billingReferencethe idempotency key the charge carried, such as the order's id
metadatathe metadata of the charge's options
refundReferencewith RefundFailed, the refund that failed
testmodewhether the payment ran in the provider's test mode: every payment of a test account, and on a live account one made in test mode
chargebacksevery chargeback of the payment, each a PaymentChargeback: reference, amount, outcome (a ChargebackOutcome: Open, Reversed or Lost), bookedAt, and reasonCode, reason and fee where the provider names them. fee is what Stripe charged for handling a dispute, 0.00 where it gave the fee back with a won one; Mollie's chargeback names none. A reversed one stays in the list
observedAtwhen the package worked out where the payment stands, a CarbonImmutable: of two reports about the same payment, the later one is the newer state

The statuses are Pending, Authorized, Paid, PartiallyRefunded, Refunded, RefundFailed, ChargedBack, Failed, Canceled and Expired. A chargeback outranks the refunds, because the bank holds the money whatever happened to them.

At Mollie the ping only names the payment, so it is read back with the account's client, together with its refunds and chargebacks where it has any. A chargeback Mollie reversed stays in chargebacks as Reversed; Mollie reports no lost one. Mollie pings when a payment is paid, authorized, expired, failed or canceled, when a refund reaches processing, refunded or failed, and when a chargeback arrives.

A live account connected through Mollie Connect can also make payments in test mode, through the same access token: hand forAccount() the account with testmode: true, for a probe payment before a shop goes live. Mollie does not show a test payment to a request in live mode, so for a live account with an access token a payment that is unknown in live mode is asked for once more in test mode, and its change carries testmode: true. A payment in the account's own mode is read once, as before, and an account with an API key reads only the mode its key carries. The flag says which mode a payment ran in, not why it was made: to tell your own probe from a test order, mark it in the charge's metadata as well. At Stripe, testmode is what Stripe marks on the payment intent or the session.

At Stripe the signed event says what happened. Add a webhook endpoint for the events payment_intent.processing, payment_intent.amount_capturable_updated, payment_intent.succeeded, payment_intent.payment_failed, payment_intent.canceled, charge.refunded, charge.dispute.created, charge.dispute.funds_withdrawn, charge.dispute.funds_reinstated, charge.dispute.closed, refund.failed and checkout.session.expired (charge.refund.updated and refund.updated work as well). For every event about a payment, the payment intent is read back with the account's key, together with its disputes. Stripe delivers events out of the order they happened in, so the intent a payment_intent.succeeded carries can be older than a refund already reported, and read back it reports the refund. A replay reads it back as well. A restricted key needs read access to payment intents and to disputes.

What the bank holds follows from the disputes. amountChargedBack counts the open and the lost ones, and a chargeback outranks the refunds, as at Mollie. An inquiry takes no money, so it is no chargeback. When an inquiry becomes one, Stripe sends charge.dispute.funds_withdrawn, and when a dispute is won, a late win included, charge.dispute.funds_reinstated. The dispute an event carries counts the way the event states it, even before Stripe's list of disputes shows the change. A key that may not read disputes gets its change with the dispute its event carries at most, and a warning names the account. Stripe names a dispute's reason by its code alone, so reason stays empty there.

A refused delivery dispatches WebhookDeliveryRefused with the surface account.

Before the webhook arrives​

A page the customer returns to can ask where a payment stands before its webhook arrives. The account's webhooks read it back from the provider by the reference the charge returned:

use Pushery\Billing\Support\BillingManager;

foreach (app(BillingManager::class)->accountWebhooks($account)->read($paymentReference) as $change) {
$change->status; // where the payment stands, as its webhook would report it
}

read() returns the AccountPaymentChanged the webhook would report for the payment as it stands now, with its billingReference and metadata. At Mollie it takes the payment's tr_… id and reads the payment back as for a ping. At Stripe it takes the Checkout Session of a charge on Stripe's checkout page, cs_…, or a payment intent, pi_…. A paid session is reported under its payment intent, as payment_intent.succeeded reports it, and an expired one under the session, as checkout.session.expired does. A session the customer has not paid yet, and an intent that still waits for a method, a confirmation or an action, report nothing: a declined card ends nothing at Stripe, since the customer can pay with another one in the same session. A reference the provider does not know reports nothing, and an error that says nothing about the payment is thrown. Each call reads from the provider, so a page that asks again waits a few seconds between calls.

What changed without a webhook​

Mollie calls no webhook for a refund that is canceled before it is paid out, and documents none for a chargeback the bank reverses. The payment then stands somewhere your listeners never heard of: paid again, with the refund's amount back in the account. The package reads such changes back on a schedule, and for that it has to know your accounts. Implement Pushery\Billing\Contracts\ListsPaymentAccounts on the class that implements PaymentAccounts:

use App\Models\Shop;
use Pushery\Billing\Contracts\ListsPaymentAccounts;
use Pushery\Billing\Contracts\PaymentAccounts;
use Pushery\Billing\ValueObjects\PaymentAccount;

final class ShopPaymentAccounts implements ListsPaymentAccounts, PaymentAccounts
{
public function find(string $provider, string $key): ?PaymentAccount
{
return Shop::query()->where('uuid', $key)->first()?->paymentAccount($provider);
}

/** @return iterable<PaymentAccount> */
public function all(string $provider): iterable
{
foreach (Shop::query()->cursor() as $shop) {
$account = $shop->paymentAccount($provider);

if ($account !== null) {
yield $account;
}
}
}
}

billing:accounts:reconcile then runs daily at 04:40. It reads the refunds of the last 30 days and the chargebacks of the last 180 of each Mollie account, with the account's own credential, and records every payment with a refund that failed or was canceled, or a chargeback that was reversed, where it stands now, as its ping would have been: an AccountPaymentChanged to your effects. A standing that a ping or an earlier run already recorded is not announced again. Without the interface the command reads nothing and is not scheduled.

The payment methods an account has turned on​

accountPaymentMethods() lists the methods an account accepts, read from its provider with the account's own credential, for a settings screen that shows them and a checkout that offers them:

$methods = app(BillingManager::class)
->accountPaymentMethods($account)
->all(amount: Money::of(1900, 'EUR'), country: 'NL', locale: 'nl_NL');

Each EnabledPaymentMethod carries the provider's id, a name to show, the address of its logo as image, its minimumAmount and maximumAmount where the provider states them, and the issuers a customer picks from, such as the banks of KBC/CBC. The ids are the provider's own, creditcard at Mollie and card at Stripe, because a shop that runs both activates and orders the methods of each.

At Mollie the list comes from the Methods API, on the account's profile and in its test mode, and all three filters apply: the amount returns the methods that take it in its currency (without one, Mollie answers for the euro), the country the methods offered there, and the locale translates the names. In test mode Mollie also lists the methods whose activation is still pending.

A wallet needs code on the checkout that asks the shopper's device whether it can pay with it, so Mollie lists Apple Pay or Google Pay only where the checkout says it supports them. Name those in wallets:

$methods = app(BillingManager::class)
->accountPaymentMethods($account)
->all(amount: Money::of(1900, 'EUR'), wallets: ['applepay', 'googlepay']);

Without wallets the request asks for none.

At Stripe the list is what the account's default payment method configuration shows and Stripe makes available to the account. That configuration states no amounts or countries and carries no names or logos, so the filters do not narrow it, the names are Stripe's product names in English, and Stripe applies the limits of a method when it creates the payment. A restricted key needs read access to payment method configurations.

Content Security Policy​

A page that mounts a provider's element for an account, or sends the customer to its checkout, needs that provider's sources in its Content-Security-Policy. accountCsp() hands them over by directive:

$directives = app(BillingManager::class)->accountCsp($account)->directives();

// ['script-src' => ['https://js.mollie.com'], 'frame-src' => [...], 'connect-src' => [...]]

Add them to the policy of the pages that take payments, and nowhere else. The account hub keeps scoping the sources of the install's own driver to its routes, as before.

A shop with a Mollie and a Stripe account needs the sources of both, and accountsCsp() hands them over together, each source once:

$directives = app(BillingManager::class)->accountsCsp($mollieAccount, $stripeAccount)->directives();

A checkout that only sends the customer to the provider's hosted page, by submitting a form and following the checkout link it gets back, mounts nothing of the provider's and needs none of those sources. The browser checks the redirect against the page's form-action, though, and accountsRedirectCsp() hands over exactly that: the origins of the hosted pages, and a Stripe account's own redirectHosts, each once.

$directives = app(BillingManager::class)->accountsRedirectCsp($mollieAccount, $stripeAccount)->directives();

// ['form-action' => ['https://www.mollie.com', 'https://checkout.stripe.com', ...]]

A page that offers Link through Stripe adds its sources with new MergedPaymentCsp($csp, new StripePaymentCsp(link: true)). Apple Pay, Google Pay, PayPal and Klarna inside Stripe's elements need no source beyond those of Stripe.js, according to Stripe's security guide: they run in its frames or redirect through hooks.stripe.com, which is among them.

Personal data in the webhooks of an account​

The webhooks about an account's payments can name the person who paid. A Stripe event carries the payment's billing_details, receipt_email and shipping and the last four digits of the card, and an expired Checkout Session its customer_details. The package keeps each delivery with its payload, so that a failed effect can run again, until billing:prune removes the payload.

The package records no owner for these deliveries, because the person who paid is your customer, not one of the package. BillingEraser::erase() and BillingDataExport::for() find a person by the model they are handed, so they do not reach them. You know which payments were the person's, from the AccountPaymentChanged events your listener stored, and you ask by those:

use Pushery\Billing\Support\BillingDataExport;
use Pushery\Billing\Support\BillingEraser;

// The references your listener stored from AccountPaymentChanged::$paymentReference.
$references = ['pi_3QdXyZ2eZvKYlo2C', 'cs_test_a1B2c3D4'];

// A request for access: the deliveries about those payments, as plain data.
$deliveries = app(BillingDataExport::class)->forPayments('stripe', 'shop-3', $references);

// An erasure: their payloads go, and the rows stay, stamped, so a redelivery does not bring a payload back.
$report = app(BillingEraser::class)->erasePayments('stripe', 'shop-3', $references);

A payment is named the way AccountPaymentChanged::$paymentReference names it: on Stripe by its payment intent, or by the Checkout Session for one that expired unpaid, and on Mollie by its tr_ id. The receiver records that id beside each delivery as it arrives, under an index, and a delivery to a Stripe account about a refund that went through is named by its payment intent too, although it reports no change. Deliveries an earlier version recorded are named from their stored payload the first time you ask about the account's payments.

When you remove an account, such as for a shop that closes, remove it from your PaymentAccounts first, and then let the package forget it:

$report = app(BillingEraser::class)->eraseAccount('stripe', 'shop-3');

That deletes the deliveries to the account and the runs of the effects they drove. Until your PaymentAccounts stops knowing the account, a redelivery to its address would be recorded again as a new delivery and run its effects again; afterwards the address answers 404. Each of the three methods takes an account's key and refuses anything else, so the platform's own deliveries, which carry no account, and a marketplace merchant's are out of their reach.

Payments only​

An application that only takes payments into the accounts of its shops, and bills nobody for a subscription, sets BILLING_MODE=payments. Payment accounts then work as described here, and the billing of a SaaS application stays off:

  • no account hub and no admin console, so no billing screen is reachable on the domains the application serves
  • no Cashier routes
  • no default effects, so no receipt, dunning notice or credit note goes out, and no billing cycle runs
  • of the scheduled runs only billing:prune, because the webhook records of the accounts carry personal data and fall under the same retention as every other delivery, and billing:accounts:reconcile where your PaymentAccounts lists its accounts (above)

The migrations follow the mode. Payments-only mode creates two tables: billing_webhook_events, the webhook deliveries of the accounts, and billing_webhook_effect_runs, the runs of the effects an application registers on them. A payment into an account leaves no other record in the package and creates no customer at the provider. billing:prune, billing:erase, BillingEraser and BillingDataExport read those two tables and no other: what the package holds about a person there is the deliveries recorded for them, and an erasure scrubs their payloads. The deliveries about the payments a person made into an account are reached by those payments, as the section above shows. Full mode creates every table of the package, and the marketplace, which records sales and payouts of its own, needs it.

vendor:publish --tag=billing-migrations publishes the migrations of the configured mode, and BillingServiceProvider::ignoreMigrations() hands them to the application as before. An application that switches from payments-only to full mode runs php artisan migrate afterwards, and the remaining migrations create the other tables in their order. One that migrated in payments-only mode with an earlier version keeps the tables that run created; the package no longer writes them in this mode, and dropping them is the application's decision.

What stays the install's​

An account's driver charges what it is handed. Its engine is the null engine, because the subscriptions of the install keep running on the install's own driver, BillingManager::driver(). The seams the install binds at boot, such as the webhook verifier, the payment methods and the invoices, stay those of the install's driver, and an override you bound for them keeps working.

With billing switched off, forAccount() returns the null driver, as driver() does. An account of a provider that has no account driver is refused with UnsupportedDriver, which names the registration that is missing.