Skip to content

M. Freight payment: collect carrier invoices by card

How do you use FRAGMENT for freight payment?

Build a freight payment flow that collects approved carrier invoices by card. Record the invoice after delivery and charge approval, then create a FRAGMENT Payment. Embedded checkout collects the shipper's payment, while FRAGMENT posts settlement and fee accounting against the invoice receivable.

OperationWho handles it?
Authorize the freight invoice and collectible amountYour application
Collect a card payment from the shipperFRAGMENT checkout and payments API
Post settlement and processing-fee accountingFRAGMENT, using your Payment Type
Record approved freight invoiceYour application posts freight_invoice_approve

Set up the Ledger and Payment Account

Use the Quickstart to configure your SDK and create a Ledger with the example schema. Use carrier as its ik. Configure a Payment Account before collecting payments. The schema marks assets/payments with payment: { "enabled": true }.

  • assets
    • payments
    • receivables:<id>
      • outstanding
  • income
    • freight-services:<id>
  • expenses
    • payment-fees
Chart of Accounts

The receivable records an approved, earned invoice. Settlement reduces the outstanding amount without recognizing that income twice. Processing fees are a separate expense.

AccountWhat it tracks
assets/paymentsCard receipts less processing fees
assets/receivables:<invoice_id>/outstandingUncollected invoice amount
income/freight-services:<invoice_id>Recognized income
expenses/payment-feesFRAGMENT processing fees

Record the approved invoice before collecting

Confirm delivery evidence, agreed rates, and approved accessorial charges before creating the invoice and Payment. Post the approved invoice once before creating its Payment. The entry records the receivable and earned income. Your accounting policy determines the recognition date. Use the AddLedgerEntry mutation with these variables.

AddLedgerEntry variables
↓
{
  "ik": "freight_invoice_approve-1-v1",
  "entry": {
    "ledger": {
      "ik": "carrier"
    },
    "type": "freight_invoice_approve",
    "typeVersion": 1,
    "parameters": {
      "invoice_id": "1",
      "amount": "10000"
    }
  }
}
 

Define the Payment Type

Add freight_invoice to payments.types in your Schema. Its payment.amount reads the server-approved amount. Add the settlement accounting below to these fields; the complete schema contains both.

Payment Type fields
↓
{
  "type": "freight_invoice",
  "typeVersion": 1,
  "status": "active",
  "payment": {
    "amount": "{{amount}}",
    "direction": "payin"
  }
}
 

Set accounting.settled.lines to these four lines. FRAGMENT supplies settled_amount and fragment_fee_amount; your application supplies invoice_id. The shipper receives credit for the gross amount. The Payment Account receives that amount less the processing fee.

Settlement lines
↓
[
  {"key": "settlement", "account": {"path": "assets/payments"}, "amount": "{{settled_amount}}", "system": "payment_settlement_line"},
  {"key": "fee", "account": {"path": "assets/payments"}, "amount": "-{{fragment_fee_amount}}", "system": "payment_fee_line"},
  {"key": "receipt", "account": {"path": "assets/receivables:{{invoice_id}}/outstanding"}, "amount": "-{{settled_amount}}"},
  {"key": "fee-expense", "account": {"path": "expenses/payment-fees"}, "amount": "{{fragment_fee_amount}}"}
]
 

Create a Payment from your backend

Resolve the approved freight invoice, payer, and amount from authenticated application records. Call createPayment with a stable idempotency key. Amounts are integer strings in USD cents. Return the Payment to your frontend; keep API credentials on your server.

Create a $100 card payment
↓
const { createPayment } = await fragment.createPayment({
  ik: 'freight_invoice-1-v1',
  ledgerIk: 'carrier',
  type: 'freight_invoice',
  typeVersion: 1,
  parameters: { invoice_id: '1', amount: '10000' },
});
if (createPayment.__typename !== 'CreatePaymentResult') {
  throw new Error(createPayment.message);
}
return { payment: createPayment.payment };
 

Embed FRAGMENT checkout in your product

Mount Checkout inside PaymentElements from @fragment-dev/payment-elements. Pass the Payment returned by your backend and the payer's email. The Payment starts in needs_payment_method. Your Pay button calls confirm() to charge the card.

Checkout
  1. Browser
  2. Your server
  3. FRAGMENT
  4. Card rail
    1. createPayment
    2. Payment
    1. Payment
    2. confirm
    1. capture
    2. captured

Place checkout in the freight invoice screen. Use onConfirmed to update that screen. Verify the Payment's settled status on your backend before marking the receipt available.

PaymentCheckout.tsx
↓
import { Checkout, PaymentElements, type Payment } from '@fragment-dev/payment-elements';
import { PayButton } from './PayButton';

type Props = { payment: Payment; email: string; onConfirmed: () => void };

export const PaymentCheckout = ({ payment, email, onConfirmed }: Props) => (
  <PaymentElements>
    <Checkout
      payment={payment}
      billingDetails={{ email }}
      onConfirmed={onConfirmed}
      onError={(message) => console.error(message)}
    >
      <PayButton />
    </Checkout>
  </PaymentElements>
);
 

Disable the Pay button until checkout can confirm the Payment. Show errors beside the form so the customer can correct their card details.

PayButton.tsx
↓
import { usePayment } from '@fragment-dev/payment-elements';

export const PayButton = () => {
  const { confirm, canConfirm, isConfirming, isLoading, error } = usePayment();
  return <>
    <button type="button" disabled={isLoading || !canConfirm || isConfirming}
      onClick={() => canConfirm && confirm()}>Pay by card</button>
    {error && <p role="alert">{error}</p>}
  </>;
};
 

Inspect the allowed entry types

FRAGMENT posts settlement accounting automatically. Your application posts the separate business entry after authorization. Do not submit native settlement entries through addLedgerEntry.

Payment Settled

Records the gross card receipt and processing fee. Reduces the outstanding receivable.

payment_freight_invoice_settled

Invoice Approved

Record approved freight invoice. Post this entry once before collecting the invoice.

freight_invoice_approve

Walk through the expected balances

These diagrams show a $100 approved invoice followed by its $100 card payment. The assumed $3 fee illustrates accounting; it is not a pricing quote. FRAGMENT supplies the actual fee. Only freight_invoice_approve is posted by your application.

Step 1: invoice-approved

Amount parameters, in cents: amount=10000. Expected outcome: posted.

Expected result: The assets/receivables:1/outstanding balance increases from 0 to 10,000 USD cents. The income balance increases from 0 to 10,000 USD cents.

Posted changes
freight_invoice_approve
assets/receivables:1/outstanding10000
income/freight-services:110000
Accounting Equation
Assets10000
Liabilities0
10000
Income10000
Expense0
10000
Total10000−10000=0
Balances after this step
assets/payments
0
assets/receivables:1/outstanding
10000
income/freight-services:1
10000
expenses/payment-fees
0
Invoice Approved

Step 2: payment-settled

Amount parameters, in cents: settled_amount=10000, fragment_fee_amount=300. Expected outcome: posted.

Expected result: The assets/payments balance increases from 0 to 9,700 USD cents. The assets/receivables:1/outstanding balance decreases from 10,000 to 0 USD cents. The expenses/payment-fees balance increases from 0 to 300 USD cents.

Posted changes
payment_freight_invoice_settled
assets/payments9700
assets/receivables:1/outstanding-10000
expenses/payment-fees300
Accounting Equation
Assets-300
Liabilities0
-300
Income0
Expense300
-300
Total-300−-300=0
Balances after this step
assets/payments
9700
assets/receivables:1/outstanding
0
income/freight-services:1
10000
expenses/payment-fees
300
Payment Settled

What happens if the card payment fails?

Store the Payment identifier with the freight invoice and operation key. A client callback alone does not establish settlement. Recover server-side status when the response is lost.

SituationApplication behavior
Card is declinedKeep the receipt unavailable. Let the payer correct checkout or use the documented retryPayment flow.
Request times outRecover the operation with its existing key and exact payload.
Payment remains processingDisplay its pending state and avoid creating a second collection.
Payment settlesUse the automatically posted entries; do not post a second receipt.

Enforce the application-side input contract

Serialize collection attempts and cap each payment at the approved invoice balance. Payment settlement accounting does not enforce that collection limit. Bind the payer, Ledger, record, and amount on your server. The application contract records these checks.

CheckRequired behavior
OwnershipResolve the record from the authenticated payer's permissions.
AmountValidate positive integer cents against the approved amount.
RetryReuse each operation's key and exact payload.
Concurrent requestsSerialize decisions for the same record and recover in-flight operations.

Check the logistics business rules

Confirm delivery evidence, agreed rates, and approved accessorial charges before creating the invoice and Payment. Keep those decisions in the carrier's application and pass only approved identifiers and amounts to FRAGMENT.

SituationHandling
Accessorial chargesRequire approval for detention, handling, or other additions before including them in the invoice.
Short paymentResolve deductions before creating the collectible amount; retain the disputed balance separately.
Shipment identifiersBind the invoice to the authorized shipment record instead of trusting a customer-entered reference.

Test the checkout and accounting flow

Use a sandbox Ledger and the documented test cards. Compare actual entries with the illustrative snapshots. The snapshots do not execute checkout or prove settlement.

  1. Post the approved invoice once, then collect it through checkout.
  2. Verify the Payment status, gross receipt, fee expense, and remaining balance.
  3. Retry with the same key and verify that the operation does not duplicate its financial effect.
  4. Test a decline, a lost response, and concurrent collection requests.

Sources and companion files