Orchardcore checkout

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore checkout is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for the CrestApps Orchard Core Checkout framework (CrestApps.OrchardCore.Checkout, Checkout.TestProvider, Checkout.Api). Covers starting a checkout from a custom module with ICheckoutEngine and StartCheckoutRequest, steps and BillingItem lines through ICheckoutHandler, Reject and CheckoutRejec

How to use this skill

Skill file

CrestApps Orchard Core Checkout

Checkout is the one path that takes money in the CrestApps commerce suite. Orders, subscriptions, transaction pay links, installment plans, bookings and the point of sale all start a checkout session through ICheckoutEngine; payment providers settle it; handlers decide what a completed checkout means. It is not a storefront: a consuming module contributes what is bought and reacts to the outcome.

Related skills: orchardcore-commerce (suite map and API conventions), orchardcore-payments (provider contracts, Stripe, refunds, installment plans), orchardcore-transactions (the ledger of money owed), orchardcore-pay-later (offline methods), orchardcore-carts and orchardcore-orders (the Order reference type), orchardcore-taxation, orchardcore-shipping, orchardcore-customers (Contact step, store credit, points).

Features

| Feature ID | Name | Adds | Depends on |

| --- | --- | --- | --- |

| CrestApps.OrchardCore.Checkout | Checkout | Engine, public checkout pages, payment endpoints, coupons, tenders, refund and reconciliation services, Settings > Commerce > Checkout | CrestApps.OrchardCore.Commerce |

| CrestApps.OrchardCore.Checkout.TestProvider | Test payments | Provider key test that confirms every payment without moving money | Checkout |

| CrestApps.OrchardCore.Checkout.Api | Checkout API | Checkout endpoints in the commerce JSON API (api/commerce/v1) | Checkout |

Feature IDs are constants on CheckoutConstants.Features (Area, TestProvider, Api). Install CrestApps.OrchardCore.Checkout and at least one provider module (Stripe, Pay Later) in the web/startup project. A module that only builds on checkout references CrestApps.OrchardCore.Checkout.Abstractions (contracts) and, for step drivers, CrestApps.OrchardCore.Checkout.Core.

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "CrestApps.OrchardCore.Checkout",
        "CrestApps.OrchardCore.Checkout.TestProvider"
      ],
      "disable": []
    }
  ]
}

Taxation needs no integration feature: with Taxation enabled a [RequireFeatures] startup replaces the no-op ICheckoutTaxService.

Guidelines

Starting a checkout and handling the outcome

The shortest complete flow, verified against the Transactions pay-link controller, OrderCheckoutHandler and TransactionSettlementCheckoutHandler. A full module (manifest, record, controller, handler, return page, tests) is in references/custom-checkout-example.md.

using CrestApps.OrchardCore.Checkout;
using CrestApps.OrchardCore.Checkout.Services;
using Microsoft.AspNetCore.Mvc;

// In a controller action:
var session = await _checkoutEngine.StartAsync(new StartCheckoutRequest
{
    ReferenceType = "RegistrationFee",
    ReferenceId = fee.Id,
    ReturnUrl = Url.Action(nameof(Show), new { feeId = fee.Id }),
    ReturnText = S["Back to my registration"],
    Title = S["Registration fee received"],
}, HttpContext.RequestAborted);

return RedirectToRoute(CheckoutConstants.RouteNames.Step, new
{
    sessionId = session.SessionId,
    step = session.CurrentStep,
});
using CrestApps.OrchardCore.Checkout;
using CrestApps.OrchardCore.Checkout.Handlers;
using OrchardCore.Entities;

// Constructor (IRegistrationFeeStore _fees, IClock _clock, IStringLocalizer S) omitted; see the reference.
public sealed class RegistrationFeeCheckoutHandler : CheckoutHandlerBase
{
    private const string StepKey = "RegistrationFee";

    public override async Task ActivatingAsync(CheckoutFlowActivatingContext context)
    {
        var session = context.Session;

        if (session.ReferenceType != "RegistrationFee")
        {
            return;
        }

        var fee = await _fees.FindByIdAsync(session.ReferenceId);

        if (fee is null || fee.Status == RegistrationFeeStatus.Paid)
        {
            // Nothing is billed. The full example also refuses such a checkout in CompletingAsync.
            return;
        }

        session.Currency = fee.Currency;
        session.Steps.Add(new CheckoutFlowStep
        {
            Key = StepKey,
            Title = S["Registration fee"],
            Order = 0,
            Conceal = true,
            BillingItems =
            [
                new BillingItem { ItemId = fee.Id, Description = fee.Title, Amount = fee.Amount },
            ],
        });
    }

    public override Task InitializingAsync(CheckoutFlowInitializingContext context)
    {
        foreach (var step in context.Flow.Session.Steps.Where(step => step.Key == StepKey))
        {
            step.Conceal = true;
        }

        return Task.CompletedTask;
    }

    public override async Task CompletingAsync(CheckoutFlowCompletingContext context)
    {
        if (context.Flow.Session is not CheckoutSession { ReferenceType: "RegistrationFee" } session)
        {
            return;
        }

        // Every obligation is confirmed at this point. Throwing rolls the completion back.
        var fee = await _fees.FindByIdAsync(session.ReferenceId)
            ?? throw new InvalidOperationException($"Checkout '{session.SessionId}' pays for a missing fee.");

        fee.Status = RegistrationFeeStatus.Paid;
        fee.PaidUtc = _clock.UtcNow;
        fee.CheckoutSessionId = session.SessionId;

        // Written through the request's YesSql session; the engine commits it with the completion.
        await _fees.SaveAsync(fee);
    }
}

// Startup: services.AddScoped<ICheckoutHandler, RegistrationFeeCheckoutHandler>();

The Payment step is added for you (always last). The customer pays, lands on Checkout/Confirmation/{sessionId} headed with your Title, and Continue returns them to ReturnUrl.

Handler lifecycle

| Hook | When | Use it to |

| --- | --- | --- |

| ActivatingAsync(CheckoutFlowActivatingContext) | Once, while StartAsync creates the session (context.Session is the CheckoutSession) | Add steps, billing items, session.Currency, session.Put(...) data; context.Reject(error) refuses the checkout |

| ActivatedAsync | After activation; the invoice is built | Read the first invoice |

| InitializingAsync / InitializedAsync | Every load | Re-conceal steps, per-request decisions (signed in or not) |

| LoadingAsync / LoadedAsync | Every load of the current step | Guard step transitions |

| CompletingAsync | All obligations confirmed, inside the completing transaction | Fulfil; throw to refuse and retry later |

| CompletedAsync | After the Completed status is committed | Notifications; failures are logged only |

| FailedAsync | Verification reports an obligation failed, session Failed (a decline at begin leaves the session open for another card) | Release what you held |

| CanceledAsync(context.Reason) | ICheckoutEngine.CancelAsync | Release what you held |

| ExpiredAsync | The sweep expired an abandoned session | Release what you held |

CheckoutFlowContextBase.Flow.Session is an ICheckoutFlowSession; cast it to CheckoutSession to read ReferenceType, ReferenceId, OwnerId, SettlesExistingBalance and the property bag. Read the invoice with session.TryGet<CheckoutInvoice>(out var invoice) (OrchardCore.Entities).

`ICheckoutEngine`

| Member | Returns | Notes |

| --- | --- | --- |

| StartAsync(StartCheckoutRequest) | CheckoutSession (Pending) | Runs activating handlers, builds the invoice, saves; throws CheckoutRejectedException (Errors) and saves nothing when a handler rejected it |

| BeginPaymentAsync(sessionId, BeginPaymentOptions) | PaymentBeginOutcome | One durable PaymentAttempt per obligation, written before the provider is called; Declined and ProviderErrorMessage on a decline; InvoiceChanged when a gate rebuilt the invoice |

| TryCompleteAsync(sessionId) | CheckoutCompletionResult | Never blocks; Status is Completed, AlreadyCompleted, Pending, Blocked (BlockingStepKey), Failed, Canceled or NotFound; IsCompleted covers the first two |

| CancelAsync(sessionId, reason) | CheckoutCompletionResult | Cancels pending attempts at the provider |

| ExpireAsync(sessionId) | CheckoutCompletionResult | A session that already collected money is never expired |

StartCheckoutRequest also carries References (see below), ReferenceVersionId, Contact (CheckoutContactInfo for a guest), PriceSelection (applied before the flow is built) and OwnerId (an administrator or background task paying for a customer). CheckoutSessionStatus is Pending, AwaitingProvider, PaymentPending, Completed, Failed, Canceled or Expired.

A server-driven charge (no browser) is StartAsync with OwnerId, BeginPaymentAsync with CheckoutPaymentDataKeys.ForOffSessionCharge(savedPaymentMethod), then TryCompleteAsync; cancel the session when the begin fails. The engine commits while charging, so reload any document you loaded before the call instead of saving the stale copy. See references/custom-checkout-example.md.

Paying for several things at once

One checkout can pay several things of one reference type with one payment. Set StartCheckoutRequest.References (a list of CheckoutReference with ReferenceType and ReferenceId) instead of ReferenceId. The session keeps the list in CheckoutSession.References; its ReferenceType is the shared type and its ReferenceId is empty (do not set ReferenceVersionId). A list of one starts exactly the checkout ReferenceType/ReferenceId would. StartAsync throws ArgumentException before anything is saved when the entries mix reference types, repeat an id, or ReferenceId and References are both set.

The handler of the reference type reads CheckoutSession.References in ActivatingAsync, adds one billing item per entry, and calls context.Reject(error) when they cannot be paid together; StartAsync then throws CheckoutRejectedException with every reason in Errors. Transactions uses this to settle several outstanding transactions of one customer (see orchardcore-transactions). A refund of such a payment can name the one entry it gives back for: RequestPaymentRefundContext.ReferenceType and ReferenceId are copied onto the PaymentRefund.

try
{
    var session = await _checkoutEngine.StartAsync(new StartCheckoutRequest
    {
        References = feeIds
            .Select(id => new CheckoutReference { ReferenceType = "RegistrationFee", ReferenceId = id })
            .ToList(),
        ReturnUrl = Url.Action(nameof(Index)),
        Title = S["Fees received"],
    }, HttpContext.RequestAborted);

    return RedirectToRoute(CheckoutConstants.RouteNames.Step, new { sessionId = session.SessionId, step = session.CurrentStep });
}
catch (CheckoutRejectedException ex)
{
    foreach (var error in ex.Errors)
    {
        await _notifier.ErrorAsync(H["{0}", error]);
    }

    return RedirectToAction(nameof(Index));
}

Sessions, invoice and ledger

Safety rules the engine enforces: an attempt is persisted before the provider is contacted; the provider reference is stored as soon as it returns; completion is driven from the browser poll, the provider webhook and the reconciliation sweep (CheckoutReconciliationBackgroundTask, every 5 minutes) under a session lock; a failing completing handler leaves the session PaymentPending for retry, never refunds; when one obligation fails the settled ones are refunded through ICheckoutRefundService (compensation, recorded in the refund ledger first). Money is compared with Money.AreEqual and rounded with Money.Round (CrestApps.OrchardCore.Payments); currency precision comes from CurrencyScale, now in CrestApps.OrchardCore.Abstractions (namespace CrestApps.OrchardCore.Currencies). Abandoned sessions expire after CheckoutSettings.SessionLifetimeHours (24).

Payments an AI agent brings

An AI agent pays with a one-purchase credential its platform got from the buyer (a Stripe shared payment token, a Google Pay token) and there is no browser. Server code passes it to ICheckoutEngine.BeginPaymentAsync in the provider data:

| Key | Value |

| --- | --- |

| CheckoutPaymentDataKeys.DelegatedCredential (delegatedCredential) | The credential |

| CheckoutPaymentDataKeys.DelegatedCredentialType (delegatedCredentialType) | DelegatedCredentialTypes: stripe_shared_payment_token, google_pay_token or test |

A provider that charges such a credential on the server sets PaymentProviderCapabilities.AcceptsDelegatedCredentials and charges it in BeginAsync when the key is present (Stripe does, see orchardcore-payments; the test provider charges tok_test_success, declines tok_test_decline, and asks for 3-D Secure on tok_test_3ds). A bank that asks the buyer to approve is reported as PaymentBeginOutcome.RequiresAuthentication or RequiresAction, and the caller hands the buyer to the checkout.

External 3-D Secure. When the payer was authenticated outside the provider (by an ACP agent), server code writes a ThreeDSecureResult into the provider data with CopyTo: ThreeDSecureOutcome (only authenticated, attempt_acknowledged and informational allow payment, ThreeDSecureResult.AllowsPayment), ThreeDSecureCryptogram (28 base64 characters, 20 bytes), ThreeDSecureElectronicCommerceIndicator (01, 02, 05, 06, 07), ThreeDSecureTransactionId, ThreeDSecureVersion and optional ThreeDSecureTransactionStatus. GetInvalidMember() names the first invalid member. A provider that takes it sets AcceptsExternalAuthentication, reads ThreeDSecureResult.From(context.ProviderData), and when the attempt already has a ProviderReference finishes that payment instead of starting another. Set PaymentBeginResult.CardBrand when known; the engine passes it on as PaymentBeginOutcome.CardBrand.

All these keys are server-only: PaymentEndpoints.SanitizeProviderData (using CheckoutPaymentDataKeys.IsServerOnly) drops them, with the off-session keys, from anything a browser or app sends. Agentic Commerce is the caller today (see orchardcore-agentic-commerce).

Deferred payment methods. A payment method whose capabilities say DefersPayment (the radio carries data-defers-payment) changes the payment step's label to Due later and the button to Place order (checkoutPayment.initialize({ deferredSubmitLabel })); the confirmation reads Due later for such a checkout and Paid for one a gateway charged.

Filling steps from code

The Contact and Shipping steps can be saved from code (an API, an AI agent) with the same rules as their pages. Resolve the contract as an IEnumerable and use it only when present:

| Contract (Checkout.Abstractions) | Implemented by | Members |

| --- | --- | --- |

| ICheckoutContactStep | Customers (CustomerCheckoutContactStep) | StepKey; SaveAsync(flow, CheckoutContactDetails) saves the buyer's details and billing address when required, and marks the step done |

| ICheckoutFulfillmentStep | Shipping (ShippingCheckoutFulfillmentStep) | StepKey; QuoteAsync(flow, address) ways to ship, cheapest first, without saving; GetPickupOptionsAsync(flow); SaveAsync(flow, CheckoutFulfillmentChoice) saves the choice, puts its cost on the checkout and marks the step done |

Both return a CheckoutStepSaveResult with errors per field. A step without a contract is finished by the buyer on the checkout page.

Custom steps

Derive from CheckoutFlowDisplayDriver (CrestApps.OrchardCore.Checkout.Core) and register it with services.AddDisplayDriver<CheckoutFlow, MyStepDriver>(). It renders only while StepKey is the current step. Override EditStepAsync and UpdateStepAsync; on a valid post write flow.Session.SavedSteps[StepKey] = new JsonObject { ... }. The controller does not mark a step saved: the engine refuses completion (Blocked, BlockingStepKey) while a visible CollectData = true step has no SavedSteps entry, and the one-page layout keeps the payment section hidden. Shapes go in Content (and Aside on the payment step).

Built-in step keys: CheckoutConstants.PaymentStepKey (Payment), CustomersConstants.ContactStepKey (Contact), TransactionsConstants.SettlementStepKey (TransactionSettlement), SubscriptionConstants.InstallmentPlans.CheckoutStepKey (ChooseHowToPay), business (Accounts B2B, formerly company).

Public checkout

| Route | Name (CheckoutConstants.RouteNames) |

| --- | --- |

| GET/POST Checkout/{sessionId}/{step?} | Step (CheckoutStep) |

| GET Checkout/Confirmation/{sessionId} | Confirmation |

| POST checkout/{sessionId}/payment/begin | BeginPayment |

| POST checkout/{sessionId}/payment/status | PaymentStatus |

Test payments

CrestApps.OrchardCore.Checkout.TestProvider registers TestCheckoutPaymentProvider (key test) only in the Development environment, or when CrestApps:Checkout:TestProvider:AllowOutsideDevelopment is true in the tenant configuration (read at tenant start). It implements one-time, recurring, refund and saved-card contracts, reports amounts as authoritative in GatewayMode.Testing, and can settle an existing balance.

{
  "OrchardCore": {
    "CrestApps": {
      "Checkout": {
        "TestProvider": {
          "AllowOutsideDevelopment": true
        }
      }
    }
  }
}

| Amount ends in (minor units, tax included) | Outcome |

| --- | --- |

| 02 | Declined at begin; the attempt fails |

| 05 | Pending for two minutes (PendingSettlementDelay), then the sweep completes it |

| 03 | An off-session charge of a kept card is refused as needing the cardholder's approval (PaymentBeginResult.AuthenticationRequired); a payment the payer makes themselves succeeds |

| anything else | Succeeds |

Pay a checkout in an automated test with two requests (carry the auth or checkout_owner cookie; a client that sends no Origin header passes the same-origin check):

POST /checkout/{sessionId}/payment/begin
Content-Type: application/json

{ "providerKey": "test" }
POST /checkout/{sessionId}/payment/status

The second returns { "status": "Completed", "completed": true, ... } once the handlers have run.

Kept payment methods

ISavedPaymentMethodStore (Checkout.Abstractions, registered by the Checkout feature) holds the cards each customer kept for charges made without them present, whatever provider holds them. When a checkout with CheckoutSession.SavePaymentMethod completes, SavedPaymentMethodCheckoutHandler reads back the kept card (ICheckoutSavedPaymentMethodProvider.GetSavedPaymentMethodAsync) and saves a CustomerPaymentMethod for CheckoutSession.OwnerId (installment plan down payments and booking deposits included; guests keep nothing). The card itself stays with the provider; the same card kept again updates the record. The owner's first card is the default.

| Member | Use |

| --- | --- |

| ListAsync(ownerId), FindAsync(ownerId, id), GetDefaultAsync(ownerId) | Owner-scoped lookups; an id from a browser never reaches someone else's card |

| FindByIdAsync(id) | Any owner's card; server code must check OwnerId itself |

| SaveAsync, SetDefaultAsync, MarkChargedAsync, RemoveAsync, RemoveAllAsync | Keep, change and forget cards (erasing a customer calls RemoveAllAsync) |

Charge a kept card for a new transaction with ITransactionCommandService.ChargeSavedPaymentMethodAsync (see orchardcore-transactions). A provider that supports it reports SupportsSavedPaymentMethods, implements ICheckoutSavedPaymentMethodProvider, honors CheckoutPaymentDataKeys.OffSession, and returns PaymentBeginResult.AuthenticationRequired(...) when the bank asks the cardholder to approve; the engine then sets PaymentBeginOutcome.RequiresAuthentication alongside Declined, so the caller asks the customer to pay instead of retrying the card. With Stripe, the storefront Payment methods page lists these cards under Cards for automatic payments with Make default and Remove.

Discounts and coupons

Coupons are part of the Checkout feature (not Marketing): Coupon is in Checkout.Abstractions, managed under Commerce > Coupons (ManageCoupons), and moved with the Coupons recipe and deployment steps. The full rules, a custom ICheckoutDiscountProvider, tenders and payment gates are in references/coupons-and-tenders.md.

Tenders and payment gates

Tenders (gift cards, store credit, points, business account terms) pay after tax through ICheckoutTenderProvider and ICheckoutTenderLedger; they never pay a recurring obligation or an existing balance. A tender that puts the amount on an invoice owed later derives from DeferredBalanceTenderProviderBase (Checkout.Core), which opens one outstanding transaction per checkout and obligation. ICheckoutPaymentGate runs inside the session lock before a payment begins and can Refuse it or flag InvoiceChanged so the page reloads with the new total.

Balances (gift cards GiftCard, store credit StoreCredit) keep their documents small through IBalanceLedgerArchive (BalanceLedgerArchive, Checkout.Core): the balance store's save keeps the latest BalanceLedger.RecentEntryCount (50) changes on the balance and moves older ones to BalanceLedgerEntryRecords indexed by balance kind, balance and reference (BalanceLedgerEntryIndex), so finding a change by reference is a keyed lookup.

{
  "steps": [
    {
      "name": "Coupons",
      "Coupons": [
        { "Code": "SPRING10", "Description": "Spring sale", "Kind": "Percentage", "Percentage": 10, "MaxRedemptions": 500, "MaxRedemptionsPerCustomer": 1, "EndsUtc": "2027-06-01T00:00:00Z", "IsEnabled": true },
        { "Code": "SHIPFREE", "Kind": "FreeShipping", "MinimumAmount": 75, "IsEnabled": true }
      ]
    }
  ]
}

Checkout API

CrestApps.OrchardCore.Checkout.Api maps into api/commerce/v1: GET checkout/{id}, POST checkout/{id}/codes, DELETE checkout/{id}/codes/{code}, GET checkout/{id}/payment-methods (each with the client dictionary from ICheckoutPaymentClientConfigurationProvider), POST checkout/{id}/payment, POST checkout/{id}/complete, DELETE checkout/{id}, plus staff coupons endpoints. A guest's checkout travels in X-Checkout-Token. Conventions (auth, idempotency, problem codes) are in orchardcore-commerce. ApiProblems, WithIdempotency, IdempotencyPolicy, IdempotentOperation and MapModuleApi moved from Commerce.Api.Core to CrestApps.OrchardCore.Api (in CrestApps.OrchardCore.Core) so every module's API shares them; MapCommerceApi now builds on MapModuleApi, and commerce conflict codes are in CommerceProblemCodes.

Report Builder data source

With Data Pipelines Core (OrchardCore.DataPipelines.Core) enabled, as the Report Builder does, Checkout registers the Checkout data source (Checkout). Rows are read newest first through the index; buyer contact details, card digits and provider references are never exposed. See orchardcore-report-builder.

| Data set | One row per | Permission |

| --- | --- | --- |

| CheckoutSessions | Checkout started, abandoned (Expired) ones included | ManageOrders |

| Coupons | Coupon | ManageCoupons |

| CouponRedemptions | Use of a coupon code | ManageCoupons |

| SavedPaymentMethods | Kept payment method | ManageRefunds |

Payments and refunds are in the Transactions data source.

Permissions

| Permission | Grants |

| --- | --- |

| ManageCheckoutSettings | Settings > Commerce > Checkout |

| ManageCoupons | Commerce > Coupons and the coupon API (security critical) |

Payments and refunds screens use ManageRefunds from Transactions.

Upgrading from 2.x

Troubleshooting

| Symptom | Cause |

| --- | --- |

| Checkout totals 0.00 and completes for nothing | Billing items were added to no step, or the invoice was built from an older version; add them on a step in ActivatingAsync |

| Payment step never reached | A visible CollectData step has no SavedSteps entry |

| Session stuck in PaymentPending | A completing handler throws; check the log, it is retried every sweep |

| ArgumentException from StartAsync | ReturnUrl is absolute or protocol-relative |

| Test method not offered | Not Development and AllowOutsideDevelopment is not set; a warning is logged at startup |

| Agent payment declined with delegatedCredential posted from a browser | Expected: server-only keys are dropped from browser and API provider data; only server code (Agentic Commerce) may set them |

| Begin endpoint returns 403 | Cross-site request (Origin host or Sec-Fetch-Site mismatch) |

| Charged twice concern | Begin is idempotent per obligation; a refreshed page resumes the same attempts |

| CheckoutRejectedException from StartAsync | A handler called context.Reject; show Errors to the buyer (for example transactions of different customers or currencies) |

| 500 when saving a deployment plan with the Coupons step | Fixed in 3.0 (#1228); a custom deployment step that overrides Category or Title with a LocalizationSource must mark them [JsonIgnore] |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.