FRAGMENT enables you to make payments that automatically reconcile to your Ledger.
For webhook setup and request handling, see Webhooks (draft).
a. Payment Type
#A Payment Type is a reusable definition of one type of money movement in your Ledger. Define them in your Schema.
{
"type": "card_payin",
"typeVersion": 1,
"status": "active",
"payment": {
"amount": "{{order_amount}}",
"direction": "payin"
},
"accounting": {
"settled": {
"description": "Order {{order_id}} settled",
"lines": [
{
"key": "settlement",
"system": "payment_settlement_line",
"account": {
"path": "assets-root/payments"
},
"amount": "{{settled_amount}}"
},
{
"key": "fee",
"system": "payment_fee_line",
"account": {
"path": "assets-root/payments"
},
"amount": "-{{fragment_fee_amount}}"
},
{
"key": "receivable",
"account": {
"path": "assets-root/receivable:{{order_id}}"
},
"amount": "-{{settled_amount}}"
},
{
"key": "fee-expense",
"account": {
"path": "expense-root/payment-fees"
},
"amount": "{{fragment_fee_amount}}"
}
]
},
"refund_initiated": {
"description": "Order {{order_id}} refund initiated",
"lines": [
{
"key": "refund",
"system": "payment_refund_line",
"account": {
"path": "assets-root/payments"
},
"amount": "-{{refund_amount}}"
},
{
"key": "receivable",
"account": {
"path": "assets-root/receivable:{{order_id}}"
},
"amount": "{{refund_amount}}"
}
]
},
"refund_failed": {
"description": "Order {{order_id}} refund failed",
"lines": [
{
"key": "refund-reversal",
"system": "payment_refund_reversal_line",
"account": {
"path": "assets-root/payments"
},
"amount": "{{refund_amount}}"
},
{
"key": "receivable",
"account": {
"path": "assets-root/receivable:{{order_id}}"
},
"amount": "-{{refund_amount}}"
}
]
},
"chargeback_settled": {
"description": "Order {{order_id}} chargeback",
"lines": [
{
"key": "chargeback",
"system": "payment_chargeback_line",
"account": {
"path": "assets-root/payments"
},
"amount": "-{{chargeback_amount}}"
},
{
"key": "chargeback-fee",
"system": "payment_chargeback_fee_line",
"account": {
"path": "assets-root/payments"
},
"amount": "-{{chargeback_fee_amount}}"
},
{
"key": "dispute-clearing",
"account": {
"path": "assets-root/dispute-clearing"
},
"amount": "{{chargeback_amount}}"
},
{
"key": "dispute-fee-expense",
"account": {
"path": "expense-root/dispute-fees"
},
"amount": "{{chargeback_fee_amount}}"
}
]
},
"chargeback_countered": {
"description": "Order {{order_id}} countered fee",
"lines": [
{
"key": "chargeback-countered-fee",
"system": "payment_chargeback_countered_fee_line",
"account": {
"path": "assets-root/payments"
},
"amount": "-{{chargeback_countered_fee_amount}}"
},
{
"key": "dispute-fee-expense",
"account": {
"path": "expense-root/dispute-fees"
},
"amount": "{{chargeback_countered_fee_amount}}"
}
]
},
"chargeback_reversed": {
"description": "Order {{order_id}} chargeback reversed",
"lines": [
{
"key": "chargeback-reversal",
"system": "payment_chargeback_reversal_line",
"account": {
"path": "assets-root/payments"
},
"amount": "{{chargeback_amount}}"
},
{
"key": "chargeback-countered-fee-reversal",
"system": "payment_chargeback_countered_fee_reversal_line",
"account": {
"path": "assets-root/payments"
},
"amount": "{{chargeback_countered_fee_amount}}"
},
{
"key": "dispute-clearing",
"account": {
"path": "assets-root/dispute-clearing"
},
"amount": "-{{chargeback_amount}}"
},
{
"key": "dispute-fee-expense",
"account": {
"path": "expense-root/dispute-fees"
},
"amount": "-{{chargeback_countered_fee_amount}}"
}
]
}
}
}b. Embed Checkout
#Embed FRAGMENT's checkout in your product to begin processing payments.
- Browser
- Your server
- FRAGMENT
- Card rail
- createPayment
- Payment
- createPayment
- Payment
- confirm
- Payment
- capture
- captured
- capture
Call createPayment from your backend with a Payment Type. Pass the returned Payment to your frontend:
const { createPayment } = await fragment.createPayment({
ik: orderId,
ledgerIk: 'main',
type: 'card_payin',
typeVersion: 1,
parameters: {
amount: '4999',
},
});
if (createPayment.__typename !== 'CreatePaymentResult') {
throw new Error(createPayment.message);
}
return { payment: createPayment.payment };The Payment starts in needs_payment_method. No money moves until the customer confirms the card.
Use FRAGMENT's frontend SDK to render a checkout form.
Pass the Payment and the customer's email in billingDetails.email as props to the component. Mount Checkout within PaymentElements:
import {
Checkout,
PaymentElements,
type Payment,
} from '@fragment-dev/payment-elements';
import { PayButton } from './PayButton';
const CheckoutPage = ({
payment,
email,
onSuccess,
}: {
payment: Payment;
email: string;
onSuccess: () => void;
}) => (
<PaymentElements>
<Checkout
payment={payment}
billingDetails={{ email }}
onPaymentAccepted={onSuccess}
onPaymentDeclined={({ message }) => console.warn('Card declined:', message)}
onError={({ message }) => console.error('Payment failed:', message)}
>
<PayButton />
</Checkout>
</PaymentElements>
);You control the Pay button. Call submit() from usePayment() when canSubmit is true:
import { usePayment } from '@fragment-dev/payment-elements';
export const PayButton = () => {
const { submit, canSubmit, state, error } = usePayment();
return (
<>
<button type="button" disabled={!canSubmit} onClick={() => void submit()}>
{state.status === 'processing' ? 'Paying…' : 'Pay'}
</button>
{state.status === 'declined' && <p role="alert">{state.message}</p>}
{error && <p role="alert">{error.message}</p>}
</>
);
};The SDK calls onPaymentAccepted when the charge is accepted, and onPaymentDeclined when the card is declined. The payer can enter another card and pay again. Any other failure calls onError. Read the Payment's status on your backend before you fulfill the order.
c. Manage saved cards
#Save a user's cards during checkout or onboarding to initiate payments from your backend.
Enable savePaymentMethod on the Checkout component to save a user's card when the payment confirms:
const CheckoutPage = ({ payment, email }: { payment: Payment; email: string }) => {
const [saveCard, setSaveCard] = useState(false);
return (
<Checkout
payment={payment}
billingDetails={{ email }}
savePaymentMethod={saveCard}
onPaymentAccepted={showReceipt}
onError={logError}
>
<SaveCardCheckbox checked={saveCard} onChange={setSaveCard} />
<PayButton />
</Checkout>
);
};Render a checkbox for the payer to choose during checkout:
Saved cards are tied to the user's email provided in billingDetails.email.
Save a user's card during onboarding to charge them later.
- Browser
- Your server
- FRAGMENT
- createPaymentMethodSetup
- PaymentMethodSetup
- createPaymentMethodSetup
- PaymentMethodSetup
- PaymentMethodSetup
- submit
- submitted
- submit
Call createPaymentMethodSetup from your backend. Pass the returned PaymentMethodSetup to your frontend:
const { createPaymentMethodSetup } = await fragment.createPaymentMethodSetup({
ik: requestId,
ledgerIk: 'main',
email,
});
if (createPaymentMethodSetup.__typename !== 'CreatePaymentMethodSetupResult') {
throw new Error(createPaymentMethodSetup.message);
}
return { paymentMethodSetup: createPaymentMethodSetup.paymentMethodSetup };Render SavePaymentMethod from FRAGMENT's frontend SDK inside PaymentElements to show the card form:
Pass the PaymentMethodSetup to SavePaymentMethod. You control the Save button. Call submit() from usePaymentMethodSetup() when canSubmit is true:
import {
PaymentElements,
SavePaymentMethod,
usePaymentMethodSetup,
type PaymentMethodSetup,
} from '@fragment-dev/payment-elements';
const SaveButton = () => {
const { submit, canSubmit, state, error } = usePaymentMethodSetup();
return (
<>
<button type="button" disabled={!canSubmit} onClick={() => void submit()}>
{state.status === 'processing' ? 'Saving…' : 'Save card'}
</button>
{state.status === 'declined' && <p role="alert">{state.message}</p>}
{error && <p role="alert">{error.message}</p>}
</>
);
};
export const SaveCardPage = ({ setup }: { setup: PaymentMethodSetup }) => (
<PaymentElements>
<SavePaymentMethod
paymentMethodSetup={setup}
onPaymentMethodSaved={showConfirmation}
onPaymentMethodDeclined={showDecline}
onError={logError}
>
<SaveButton />
</SavePaymentMethod>
</PaymentElements>
);The SDK calls onPaymentMethodSaved after it saves the card, and onPaymentMethodDeclined when the card is declined. Any other failure calls onError.
Call createPayment with the saved card's id in paymentMethod to make a payment from your backend:
const { createPayment } = await fragment.createPayment({
ik: renewalId,
ledgerIk: 'main',
type: 'card_payin',
typeVersion: 1,
parameters: {
amount: '4999',
},
paymentMethod: { id: savedCardId },
});The Payment comes back accepted when the card is charged at once, or processing while the charge waits on the card network. It then follows the same lifecycle as a checkout Payment. If the card is declined, the Payment moves to needs_payment_method instead.
Call retryPayment on a Payment in needs_payment_method to charge the same saved card again, or pass a paymentMethod to charge another:
const { retryPayment } = await fragment.retryPayment({
payment: { ik: renewalId, ledger: { ik: 'main' } },
paymentMethod: { id: savedCardId }, // optional
attemptIk: retryRequestId, // a new key for each try
});retryPayment is idempotent on attemptIk. Resending a request with attemptIk with the same body as the original request does not retry the payment a second time. It will return the latest version of the attempt the attemptIk started.
Call deletePaymentMethod with the saved card's id. After the call, the card can no longer be charged:
await fragment.deletePaymentMethod({
id: savedCardId,
});d. Refund a Payment
#Refunds are configured per Payment Type. A Payment Type must define the refund_initiated and refund_failed Ledger Entries, as card_payin does above. To refund a settled Payment, call refundPayment with the Payment's ik, its Ledger's ik and the amount to refund:
const { refundPayment } = await fragment.refundPayment({
ik: refundRequestIk,
payment: { ik: orderId, ledger: { ik: 'main' } },
refund: { amount: '4999' },
});
if (refundPayment.__typename !== 'RefundPaymentResult') {
throw new Error(refundPayment.message);
}
console.log(refundPayment.refund.status); // processing
console.log(refundPayment.refund.amount); // 4999Pass a smaller refund.amount to refund part of the Payment, up to its captured amount:
const { refundPayment } = await fragment.refundPayment({
ik: refundRequestIk,
payment: { ik: orderId, ledger: { ik: 'main' } },
refund: { amount: '2500' },
});The funds will immediately move out of your Payment Account and the refund will move to a processing status. Refunds will move to the settled status after a few days. In the event of a failure, the refund will be marked as failed.
FRAGMENT keeps its processing fee from the original Payment when you refund it. Your Payment Account must hold at least the refund amount to issue a refund. While a chargeback is open, in needs_chargeback_response or chargeback_under_review, refundPayment returns a BadRequestError. A refund during an inquiry is allowed, and a refund still processing when a dispute opens can fail.
e. Handle disputes
#A cardholder's bank can dispute a settled card Payment. FRAGMENT tracks each case as a dispute on the Payment, sends a webhook for each change, and posts each withdrawal and credit to your Ledger.
A dispute starts as an inquiry, where the bank asks for information, or as a chargeback, where the disputed amount is withdrawn.
An inquiry can escalate to a chargeback and keeps its dispute id. The Payment stays settled throughout, and one Payment can have several disputes.
Each arrow is a change to the dispute's status:
An inquiry has these statuses:
needs_inquiry_response: the bank asks for information. You can respond.inquiry_under_review: your inquiry response is submitted.inquiry_closed: the inquiry closed without a chargeback.
A chargeback has these statuses. A dispute resolved before a chargeback opened is prevented:
needs_chargeback_response: the chargeback is open. You can accept it or submit evidence.chargeback_under_review: your evidence is submitted. The bank is deciding.chargeback_closed: the bank decided the chargeback. Readoutcome.
A closed dispute has one of these outcomes:
inquiry_closed_without_chargeback, with statusinquiry_closed.chargeback_wonorchargeback_lost, with statuschargeback_closed.prevented, with statusprevented.
Admins respond on the Payment's page in the FRAGMENT Dashboard:
- Answer an inquiry while its status is
needs_inquiry_response. - Accept a chargeback while its status is
needs_chargeback_response. The chargeback closes as lost. - Submit evidence to contest a chargeback. This incurs the countered fee.
The webhook for a response is sent once its submission is confirmed.
A chargeback can incur two fees, each posted by its own system line:
- The dispute fee is charged when a chargeback opens, and posts on
chargeback_settledbypayment_chargeback_fee_line. It is never returned. - The countered fee is charged when you submit evidence to contest a chargeback, and posts on
chargeback_counteredbypayment_chargeback_countered_fee_linesome hours later. A win returns it as its ownchargeback_reversed, onpayment_chargeback_countered_fee_reversal_linewith no principal.
A Payment Type must define three dispute Ledger Entries, as card_payin does above. Each contains fixed system lines on the Payment Account, and you add the lines that balance them on your own accounts. In this example, a $100 Payment settles with a $3 fee, leaving $97, and a $100 chargeback is contested and won:
- A chargeback opens, directly or by escalating an inquiry.
chargeback_settledposts the principal onpayment_chargeback_lineand the $15 dispute fee onpayment_chargeback_fee_line. The balance is −$18. - You submit evidence.
chargeback_counteredposts the $15 countered fee onpayment_chargeback_countered_fee_line. The balance is −$33. - You win.
chargeback_reversedposts the $100 principal onpayment_chargeback_reversal_line, and a secondchargeback_reversedreturns the $15 countered fee onpayment_chargeback_countered_fee_reversal_line. The balance is $82.
A credit outside a win, such as a partial credit, posts its own chargeback_reversed once the dispute has an outcome.
Dispute entries can use their own parameters, such as one in a template account path. A dispute posts without an API call, so createPayment requires every parameter they use.
f. Testing
#Use the following cards in sandbox mode for your testing:
| Card number | Outcome |
|---|---|
4242 4242 4242 4242 | The payment succeeds and settles asynchronously. |
4000 0000 0000 0077 | The payment succeeds and settles instantly. |
4000 0000 0000 0002 | The payment is declined. |
4000 0000 0000 0341 | The card saves, but a later charge against it is declined. |
5385 3083 6013 5181 | 3D Secure is required. Enter Checkout1! on the 3DS screen. |
The expiry date must be in the future, and use any three-digit CVC.