Skip to content

Payment Gateways and Purchase Sources

Learnomy overviewFree + ProGet Learnomy →

How money becomes access in Learnomy, and how to plug in a gateway (Mollie, Razorpay, a local bank), a new kind of product, or an outside system that sells for you (Make, Zapier, Gumroad). Each one lives in your own plugin; none needs an edit to Learnomy’s files.

A gateway is one folder and one filter: a class that translates between your processor and Learnomy’s normalized events, registered on learnomy_register_gateways. Learnomy owns everything else: the checkout row, booking the sale, access, refunds, disputes, subscriptions, emails and earnings. A gateway never writes any of that itself (the build enforces it for Learnomy’s own gateways, Rule 59).

checkout core writes a `pending` row, then -> your create_purchase_session( $args ) -> buyer pays at the processor
webhook POST /wp-json/learnomy/v1/webhooks/{id}
-> your verify_webhook( $request ) signature over the raw body; fails closed
-> your parse_webhook( $request ) processor event -> normalized event(s)
-> Gateway_Event_Service (the applier) site marker, per-sale lock, your capture() to confirm,
then books: Purchase_Provisioner / Refund_Service / subscriptions
return the thank-you page asks your reconcile_order( $reference ), books through the same applier, then renders
hourly learnomy_reconcile_payments asks your capture() about every pending row; a final decline marks it failed,
a checkout never paid is marked abandoned after 72 hours (learnomy_abandon_pending_after)
booked -> do_action( 'learnomy_purchase_completed', $txn_id, $user_id, $type, $item_id, $ext, $gateway, $payment_ref )
do_action( 'learnomy_payment_completed', $txn_id, $user_id, $gateway, $payment_ref ) -> commissions

Rules the flow enforces for every gateway:

  • One row per checkout. Core writes the checkout row as pending before the buyer leaves, under your session_id. It moves only through Transaction::transition(): to completed on the confirmed payment, to failed on a decline (a later success on the same checkout still completes it), to abandoned when it is never paid. Pending, failed and abandoned rows are never revenue (Rule 62).
  • A webhook is a hint; capture() decides. The applier books a payment only when your capture() says paid. Until then it answers 503 so your processor sends the event again.
  • Idempotency is per sale: the applier locks the sale while it books, a delivery that finds the lock held is answered 503, and an event for a sale already booked is a no-op.
  • Only this site’s payments are booked: an event must carry this site’s marker, or name a row this site holds (see the site marker).
  • Tax in the checkout args is recorded and kept out of the commission base.
  • Currency is the site currency for new sales. A sale or subscription keeps the currency it was paid in when the site’s currency changes later.

Put the class in its own file, in a subfolder next to your main file, and load it inside the filter. Learnomy is loaded by then, so Abstract_Payment_Adapter exists. The subfolder also makes this work as a must-use plugin: WordPress loads every .php file in the root of wp-content/mu-plugins at startup, before Learnomy, so a class file left there stops the site with “Class Learnomy\Adapters\Abstract_Payment_Adapter not found”.

wp-content/plugins/acme-pay-learnomy/
├── acme-pay-learnomy.php (main file: the one filter)
└── acme-pay/
└── class-acme-pay-gateway.php
<?php
/**
* Plugin Name: Acme Pay for Learnomy
*/
add_filter( 'learnomy_register_gateways', function ( array $gateways ): array {
require_once __DIR__ . '/acme-pay/class-acme-pay-gateway.php'; // Learnomy is loaded by now.
$gateways[] = new Acme_Pay_Gateway();
return $gateways;
} );

acme-pay/class-acme-pay-gateway.php:

<?php
use Learnomy\Adapters\Abstract_Payment_Adapter;
use Learnomy\Adapters\Adapter_Registry;
use Learnomy\Adapters\Gateway_Event;
use Learnomy\Services\Site_Marker;
class Acme_Pay_Gateway extends Abstract_Payment_Adapter {
public function get_id(): string { return 'acme'; } // a-z, 0-9, _ and -, at most 20 characters
public function get_label(): string { return 'Acme Pay'; } // shown at checkout and on every admin screen
public function is_available(): bool {
return '' !== (string) $this->setting( 'acme_api_key' );
}
// What it can do: core asks supports( $flag ) before calling anything optional.
protected function features(): array {
return array( 'webhooks', 'reconcile', 'hosted_redirect', 'refunds', 'partial_refunds' );
}
// Its settings, rendered and saved by Learnomy (a `secret` field is stored encrypted).
public function settings_fields(): array {
return array(
'acme_api_key' => array( 'type' => 'secret', 'label' => 'API key', 'default' => '', 'option' => 'acme_learnomy_api_key', 'key' => '' ),
);
}
// Checkout: open a payment at Acme. Core has already written the pending row.
public function create_purchase_session( array $args ): array {
$args = Adapter_Registry::normalize_purchase_args( $args, $this ); // amount incl. tax, item, buyer
$order = acme_api_create_order( array(
'amount_minor' => \Learnomy\to_minor_unit( (float) $args['amount'], (string) $args['currency'] ),
'currency' => $args['currency'],
'metadata' => Site_Marker::metadata(), // only this site books it
'return_url' => $args['return_url'],
'notify_url' => rest_url( 'learnomy/v1/webhooks/acme' ),
) );
return $order ? array( 'redirect_url' => $order['pay_url'], 'session_id' => $order['id'] ) : array();
}
// The processor's own answer about a checkout: core trusts this, not the webhook body.
public function capture( string $transaction_id, array $args = array() ): array {
$order = acme_api_get_order( $transaction_id );
return array(
'status' => $order ? ( 'paid' === $order['status'] ? 'paid' : ( 'declined' === $order['status'] ? 'failed' : 'pending' ) ) : 'pending',
'transaction_id' => $transaction_id,
'amount_minor' => $order['amount_paid_minor'] ?? null,
'currency' => strtoupper( $order['currency'] ?? '' ),
'site_marker' => $order['metadata']['learnomy_site'] ?? '',
);
}
public function verify_payment_status( string $session_id ): string {
return $this->capture( $session_id )['status'];
}
// Webhooks: verify, then translate. Core applies the events.
public function verify_webhook( \WP_REST_Request $request ) {
return acme_api_signature_ok( $request->get_body(), $request->get_header( 'X-Acme-Signature' ) )
? true
: new \WP_Error( 'acme_bad_signature', 'Acme signature does not match.' ); // answered 400
}
public function parse_webhook( \WP_REST_Request $request ): array {
$event = json_decode( $request->get_body(), true );
$base = array(
'event_type' => $event['type'],
'site_marker' => $event['data']['metadata']['learnomy_site'] ?? '',
);
switch ( $event['type'] ) {
case 'order.paid':
return array( Gateway_Event::make( Gateway_Event::PAYMENT, $event['id'], $base + array(
'status' => 'paid',
'references' => array( $event['data']['order_id'] ),
'amount_minor' => (int) $event['data']['amount_minor'],
'currency' => strtoupper( $event['data']['currency'] ),
) ) );
case 'order.declined':
return array( Gateway_Event::make( Gateway_Event::PAYMENT, $event['id'], $base + array(
'status' => 'failed',
'references' => array( $event['data']['order_id'] ),
'data' => array( 'failure_reason' => $event['data']['reason'] ?? '' ),
) ) );
case 'refund.created': // refunded in Acme's dashboard, or by Learnomy's Refund button
return array( Gateway_Event::make( Gateway_Event::REFUND, $event['id'], $base + array(
'references' => array( $event['data']['order_id'] ),
'refund_id' => $event['data']['refund_id'],
'amount_minor' => (int) $event['data']['amount_minor'],
'currency' => strtoupper( $event['data']['currency'] ),
) ) );
}
return array( Gateway_Event::ignored( $event['id'], $event['type'] ) );
}
// The events your processor must be told to send (shown on the gateway's settings).
public function webhook_events(): array {
return array( 'order.paid', 'order.declined', 'refund.created' );
}
// Learnomy's Refund button: an amount in the currency's minor unit.
public function refund_minor( string $transaction_id, int $amount_minor, string $currency, string $idempotency_key ): string {
return (string) acme_api_refund( $transaction_id, $amount_minor, $idempotency_key ); // '' when refused
}
public function supports_refund(): bool { return true; }
// Required by the interface for gateways written before 2.4.0; not called for this one.
public function create_checkout( array $args ): array { return $this->create_purchase_session( $args ); }
public function create_subscription( array $args ): array { return array(); } // one-time only
public function refund( string $transaction_id, float $amount ): string { return ''; }
public function cancel_subscription( string $provider_sub_id ): bool { return false; }
public function process_webhook( \WP_REST_Request $request ): void {}
}

The acme_api_*() calls stand for your processor’s SDK or HTTP calls; replace them.

With that, Learnomy offers Acme Pay at checkout, writes the pending row, routes POST /wp-json/learnomy/v1/webhooks/acme through verify_webhook() and parse_webhook(), books paid, declined and refunded payments through its applier, asks capture() on the thank-you page and in the hourly reconcile, shows a Refund button that calls refund_minor(), and renders the API key field on its Payments settings. tests/payments/fixtures/fake-gateway-module/ is a complete module written only against this contract (payments, refunds, disputes and every recurring step); the gateway contract test (tests/payments/gateway-contract.php) runs Learnomy with it as the only gateway.

A gateway written before 2.4.0 (registered on the learnomy_register_payment_adapters action, with its own process_webhook() calling Purchase_Provisioner::provision()) keeps working unchanged: a gateway that does not implement parse_webhook() is handed its webhook as before. Move it to the contract above when you next touch it.

When WooCommerce is the site’s payment route, it owns checkout for every purchase type: the owner chooses WooCommerce or Learnomy’s own payment methods, one flow for the whole site. A registered gateway is then not offered at checkout until WooCommerce is switched off as the payment method. Surfaces that show a single Pay button pick the first active gateway from learnomy_default_gateway_order (default woocommerce, stripe, paypal, test, then any other registered gateway); filter it to put yours first.

parse_webhook() returns a list of events built with Gateway_Event::make( $type, $event_id, $fields ), or Gateway_Event::ignored() for anything Learnomy does not act on.

Type Fields Learnomy does
payment status (paid, failed, cancelled, pending), references (your checkout and payment ids, most specific first), amount_minor, currency, transaction_id (the id the sale is stored under, when it differs), data.failure_reason paid: confirms with capture() and books the sale on the pending row. failed: marks the row failed with the reason. cancelled: closes an unpaid checkout; with data.revoke_access it ends what the named paid sales gave, without a refund (a store’s “cancel removes access” setting).
refund references, refund_id, amount_minor (or cumulative with the running total), currency, line_references (lines of a multi-line order) books the refund under the refund rule; emails the buyer and each instructor whose earning it takes back
dispute status (opened, won, lost), references, refund_id (the dispute id), amount_minor, currency, data.reason, data.respond_by (UTC) opened: flags the sale and emails the owner; won: clears it; lost: a full refund under the refund rule
subscription.* subscription_reference, period_end_utc, amounts and plan terms renewals, failures, recovery, changes, pause, resume and cancel (see Recurring billing below)

Every event also carries site_marker (and site_address) from the processor object it is about, and payment events carry opened_at.

Method Contract
create_purchase_session( $args ) redirect_url (hosted page) or client_secret (on-page fields), and session_id, or an empty array on failure. $args: purchase_type, item_id, item_label, amount, currency, mode (one_time or subscription), user_id (or guest_email), return_url, cancel_url, optional coupon_id, extra. Run it through Adapter_Registry::normalize_purchase_args() first.
capture( $id ) status (paid, failed, pending), transaction_id, amount_minor, currency, site_marker, opened_at; metadata with the purchase args when core wrote no row for it.
verify_webhook( $request ) true, or a WP_Error (answered 400, the processor stops retrying). Fail closed.
parse_webhook( $request ) A list of normalized events (above).
webhook_events() The processor event names the owner must subscribe to.
refund_minor( $id, $amount_minor, $currency, $key ) The processor’s refund id, or '' when refused. Called by the Refund button when supports_refund() is true.
verify_payment_status( $id ) paid, pending, failed or unknown.

Optional capabilities (override only when the default is wrong)

Section titled “Optional capabilities (override only when the default is wrong)”
Method Default Override when
supports_refund() false You refund through refund_minor(); Learnomy then shows a Refund button for your sales. A gateway refunded only in its own dashboard reports it as a refund event.
session_reference( $session ) session_id Your checkout row should be keyed on another id from the session.
cancel_unpaid_checkout( $reference ) true Your gateway opens a chargeable object before the buyer approves (a card PaymentIntent, an incomplete subscription). When the checkout page opens a new checkout for a new price (a coupon), Learnomy closes the buyer’s old one only after this cancels it: return true once it is cancelled or was already closed, false while it is paid or being paid. A hosted order nobody approved expires by itself, so the default is right for it.
reconcile_order( $reference ) asks capture() and books The thank-you page needs something other than capture() (an order that must be captured first).
has_unguessable_session_ids() false Return-URL ids cannot be guessed, so a signed-out buyer may see their receipt.
render_checkout_panel( $context ), script_handles(), client_config( $context ) none Your gateway collects payment details on the checkout page. See How a gateway renders checkout.
is_configured() is_available() Acting on an old order needs less than taking a new one.
supports_purchase( $args ) true The gateway refuses a product (for example recurring). Hides it at checkout for that product.
supports_first_payment_discount() false The gateway can bill a discounted first payment, then the full price.
handles_tax() false The gateway taxes the sale itself; it is then given the net price.
manage_subscription_link( $sub ) Learnomy’s billing page The gateway hosts its own subscription management page.
transaction_url( $transaction ) ‘’ The processor has a dashboard page for the sale; admin screens link to it.
webhook_event_url( $event_id, $payload ) ‘’ The processor has a dashboard page for one delivery; the Payment Log offers “Resend from ” on a delivery that was rejected or errored.
minimum_amount( $currency ) 0 Your processor refuses payments below an amount in a currency (Stripe: JPY 50, USD 0.50). Return it in currency units. Learnomy then refuses a smaller checkout before opening a session, tells the owner which item and why, and warns on the price field. Keep your processor’s table in your gateway; core never holds one.
dispute_url( $dispute_id ) ‘’ The processor has a dashboard page where the owner answers a dispute; the owner’s dispute email’s button opens it. Return ‘’ for an id that is not your dispute’s shape.
renewal_terms( $payload ) the payload’s own period Your renewal payload names the period and the amount charged.
render_settings(), settings_order() nothing, 25 Your gateway has a card on the Payments settings screen. Echo its fields inside the screen’s one form; the screen shows the cards in settings_order() (below 30 before its Checkout options card, from 30 after). Name a text field’s only values as choices in settings_fields() and Learnomy stores anything else as the field’s default.
test_credentials( $input ) refused Your card has a Test connection button (declare test_connection). Check the typed secret / client_id for mode, else the saved ones, and return mode_detected, account and name, or a WP_Error with a status. On the button, data-mode-field, data-secret-field and data-client-field name your inputs ({mode} is the picked mode).
live_without_keys() false Your gateway has a live mode; return true while it is set to Live with the live key missing, and the owner is told.
open_payment_method_update( $sub ) update_payment_method_url() or a 503 You declare payment_method_update: the Billing page’s Manage payment method button opens your page, and your own reason (with its status) is shown when it cannot.
paid_return_may_be_unbooked() true Your return page already books every paid order of the buyer’s, so a paid order with no sale here is someone else’s (PayPal).

The thank-you page asks reconcile_order() about the id on the return URL before it renders anything, then reads the sale. So that a guest buyer is signed in on that first page load, the return URL must carry the reference your checkout row was written under (the session_id you return), or a provider order id recorded on the sale. Book the payment through core so the checkout row core wrote is completed in place (it carries the paying browser’s login binding); never insert a second row and delete the first.

Recurring billing: plan changes, retries, pause

Section titled “Recurring billing: plan changes, retries, pause”

Recurring requests go to the gateway through the same contract. Declare what your gateway can do by returning the flags from features(), and Learnomy asks supports( $flag ) before it calls the method. A gateway that declares nothing keeps the defaults, which answer not_supported.

Flag Method Called when
subscription_plan_change change_plan( $sub, $new_plan, $mode, $idempotency_key ) A member (Pro) moves to another plan. $mode is credit when fair credit is on, none when it is off.
deferred_start start_at in the subscription’s purchase args (UTC Y-m-d H:i:s) Your gateway has no in-place switch but can open a subscription whose first charge is on a later date. A member then changes plan at the period end: a new checkout with nothing due today and start_at set to the old period end; Learnomy keeps the new membership scheduled (no access) until that date or its first payment, and ends the old one at its period end with cancel( $sub, 'period_end' ). A gateway that declares subscription_plan_change is switched in place instead.
proration_preview preview_change( $sub, $new_plan, $mode ) The Change plan window shows what is due today and next. Without it, Learnomy shows its own figures.
subscription_retry retry( $sub, $idempotency_key ) Pro retries a failed renewal. Leave it out when your processor retries on its own schedule.
subscription_pause pause( $sub, $until_utc ) and resume( $sub ) A member pauses or resumes.
subscription_cancel cancel( $sub, $when ) and resume( $sub ) $when is now or period_end. resume() takes back a period-end cancel the member changes their mind about; answer Gateway_Result::ended() when the processor already ended the subscription.

Each method returns a Gateway_Result: applied, pending_action (with the action_url the buyer must visit), scheduled (with effective_at_utc), failed or not_supported (each with a message the buyer can read).

A processor with no period-end cancel (PayPal) pauses billing instead and answers a period-end cancel() with scheduled plus 'held' => true. Learnomy then keeps the member’s access to effective_at_utc, does not record billing as stopped, and at that date calls cancel( $sub, 'now' ) itself (Action Scheduler hook learnomy_end_held_billing, with the hourly cancel sweep as backstop once the subscription has expired). Your resume() restarts the paused billing. Without held, scheduled means the processor ends it on that date by itself (Stripe’s cancel_at_period_end). Learnomy changes the plan, the amount, the dates or access only on applied, or later when your gateway reports the matching event (for example subscription.action_completed after an approval).

Plans and prices belong to Learnomy. Send the amount, currency and billing interval from the plan inline (Stripe’s price_data, for example); never create, store or look up a processor plan or price id. Before it asks your gateway, Learnomy records the price the change will bill, so when your processor reports the new price back it is recognised as Learnomy’s own change by amount, currency and interval, and is not refused as an outside change.

Pro’s learnomy_pro_proration_provider filter is deprecated since 2.4.0. It is still asked, for one release, for a gateway that does not declare subscription_plan_change. Declare the flags above instead.

A buyer can pay for several courses at once (the cart, Settings > Payments > Cart). Your gateway needs no cart code for this. Learnomy owns the order: the checkout prices the cart, writes the quoted lines onto a pending row in its own ledger, and calls your create_purchase_session() with ONE amount (already taxed, tax_applied true), item_id 0, a label such as “3 courses”, and an order_ref. Your gateway only has to bring that reference back with the payment.

That is one mapping, done once, the same way you already carry the buyer’s user id:

  1. Outbound, in create_purchase_session(): add $this->order_ref_metadata( $args ) to the metadata your provider round-trips. It returns array( 'learnomy_order_ref' => '<ref>' ) for a cart and an empty array for every other purchase, so nothing extra lands on a single sale.
  2. Inbound, in process_webhook(): pass 'order_ref' => $this->order_ref_from( $metadata ) in the normalized payment you hand to Purchase_Provisioner::provision().
// create_purchase_session()
$metadata = array_merge( array( 'learnomy_user_id' => $args['user_id'] ), $this->order_ref_metadata( $args ) );
// process_webhook(), after verifying the signature
Purchase_Provisioner::provision( array(
'user_id' => (int) $payment->metadata['learnomy_user_id'],
'gateway' => 'acme',
'provider_id' => $payment->id,
'amount' => $payment->amount,
'currency' => $payment->currency,
'order_ref' => $this->order_ref_from( $payment->metadata ),
// course_id, coupon_id and the rest exactly as for a single sale
) );

Amount paid. Pass amount as the money that actually moved and quoted_amount as the total Learnomy asked your gateway to charge (gross, coupon applied: the amount your create_purchase_session() received, as your provider reports it back). The provisioner compares them in the currency’s minor unit and, when the payment is short by one cent or more, records nothing, enrols nobody and tells the site owner (an admin notice and a row in the Payment log). Leave quoted_amount out only if your gateway prices the order itself, as a store does. A cart is always checked against its own order total, whatever you pass. The Test gateway’s rehearsal (meta.test_mode, amount 0) is never checked. Subscription activations that do not pass through the provisioner use the same rule through Purchase_Provisioner::short_of( $paid, $quoted, $currency ); PayPal holds the activated subscription’s billing cycles to the plan’s price, period and trial.

Renewals are not re-checked: a renewal can only follow a first payment that passed, and its price is the one the gateway subscription was created with (Stripe invoice.paid renewals and PayPal PAYMENT.SALE.COMPLETED record the payment and extend the period; WooCommerce renewals do the same through the store).

If your provider’s metadata is not a key/value map (PayPal packs it into one custom_id string), store the pair in whatever field you have and read it back into an array before calling order_ref_from().

The provisioner decides “cart or single” in one place. A reference that names an open cart order books one transaction row and one enrolment per course: line 1 under your payment id, the others as {payment id}:course:{course id}, all sharing payment_ref. The charged amount is spread over the lines so the rows add up to the money that moved, and the coupon is redeemed once. Each line is idempotent on its own key, so a repeated webhook, or a run that died halfway, is finished by the next delivery and nothing is booked twice. A payment with no reference takes the single-sale path unchanged.

Refunds need nothing new either. Hand your refund event to Refund_Service::apply_payment_refund( $row, $amount, $is_cumulative, 'acme', $refund_id ) with the row your payment id finds. For a one-row sale it is the plain refund. For a cart it shares the refund out: the whole remainder refunds every course and ends access; an amount equal to exactly one untouched course’s charge refunds that course; any other amount is spread over the courses as partial refunds with no change to access. Pass $is_cumulative = true when your provider reports the running refunded total; it is then measured against everything already refunded on the payment, so an admin refund or a manual refund recorded in Learnomy is not counted twice.

Transaction::rows_for_payment( Transaction::payment_ref_of( $row ), $row->payment_provider, (int) $row->user_id ) returns every row of a payment. The gateway and the buyer are part of it: a reference alone can be shared by an unrelated sale (an incoming-webhook sale keyed on another system’s order id). A store that runs its own cart (WooCommerce, handles_tax() true) is not offered Learnomy’s cart; its own order lines are the cart.

The checkout page and its script name no gateway. Learnomy lists the methods offered for the purchase (Adapter_Registry::offered(), narrowed by supports_purchase()), renders a radio and an empty panel for each, and hands the rest to the gateway. A gateway that overrides nothing below is offered as a redirect: the pay button asks create_purchase_session() for its redirect_url and sends the buyer there.

Method Default What it gives checkout
checkout_choice() your label, “Continue to {label}” label (the radio), submit_label (the pay button), submit_help (what the button does, read by screen readers), panel_class (your panel’s class), own_button (true when your script renders its own pay button, which hides Learnomy’s).
render_checkout_panel( $context ) nothing Echo your fields inside the panel Learnomy renders for you, id lrn-{id}-container. Escape your own output. $context: currency, course_id, plan_id.
script_handles() none Script handles Learnomy enqueues before its own checkout.js when your method is offered. Register them yourself from boot() through $this->when_scripts_can_register( $callback ), which runs your wp_register_script() calls on init (Learnomy’s pages enqueue before wp_enqueue_scripts fires).
client_config( $context ) empty Public values your script reads, such as a publishable key, a return URL and your own words under i18n. Printed into the page, so never a secret. $context: course_id, plan_id, purchase_type, currency.
is_rehearsal() false True only for a practice gateway that takes no money. It is listed first and preselected.

Only the chosen method’s panel is shown. The others are hidden, aria-hidden, and every button inside them is disabled, so nothing in an unchosen panel can be clicked or reached by keyboard.

Your script registers a factory on window.learnomyGateways, keyed by your gateway id. Learnomy calls it once, the first time your method is chosen, with an api object, and dispatches to what it returns:

( function () {
window.learnomyGateways = window.learnomyGateways || {};
window.learnomyGateways.acme = function ( api ) {
var words = ( api.gatewayConfig && api.gatewayConfig.i18n ) || {};
return {
mount: function () {}, // the buyer chose your method: show your fields
unmount: function () {}, // the buyer chose another one: tear them down
refresh: function () {}, // the price (a coupon) or the colour scheme changed
submit: function () { // Learnomy's pay button was pressed
api.setProcessing( true );
api.postJSON( api.config.restUrl + api.checkoutPath(), api.withPlanTerms( { gateway: api.gatewayId } ) )
.then( function ( res ) { window.location.href = res.data.redirect_url; } )
.catch( function ( err ) {
api.showRequestError( err, words.failed );
api.setProcessing( false );
} );
},
};
};
}() );

The api object:

Key What it is
config, i18n, state The page’s settings (restUrl, nonce, buyer details), Learnomy’s own words, and the live state (processing, couponCode).
gatewayId, gatewayConfig Your id, and your client_config().
postJSON( url, body ) A POST with the REST nonce. Rejects with an Error carrying the server’s code and fields.
checkoutPath(), withPlanTerms( body ) The endpoint for this purchase (checkout or checkout/subscribe), and the body with the course, plan, purchase type, billing cycle and coupon added.
setProcessing( on ) Disables the page while a payment is in flight.
showError( message ), showRequestError( err, fallback ), hideError() The page’s error box. showRequestError() also marks the billing fields the server named.
flagMissingBilling(), showBillingNeeded( announce ), guestEmailMissing() The billing form: mark empty required fields, say billing is needed (an error only when announce), and check a guest’s email.
isFreeOrder(), syncFreeOrderUI( free ), onPaymentSuccess() A coupon that zeroes the total retires every gateway: check before mounting anything that charges.
redirectTo( id ) The plain redirect, for a gateway that only needs one.

Two optional hooks help a card form: billingNeeded() (say it in your panel and return true; otherwise Learnomy’s error box says it) and billingComplete() (every required billing field is filled in; mount now). A gateway that declares exclusive, such as a store with its own checkout, takes the whole page over: its mount() runs when the page opens and returns false when there is nothing for it to take over (a free order).

A theme that copied Learnomy’s checkout template before 2.4.0 keeps working: $stripe_enabled, $paypal_enabled, $test_enabled, $wc_active and $extra_gateways are still passed, derived from the same list, and the built-in gateways’ scripts mount into the element ids that template writes. New templates loop over $gateways and check $exclusive_gateway.

Only this site’s payments: the site marker

Section titled “Only this site’s payments: the site marker”

Site owners often connect a staging copy and the live site, or two products, to one payment account, and the processor sends every site every event. A staging site is usually a copy of the live database at another address, so it holds the live site’s checkouts, sales and subscriptions too. Neither “the event carries Learnomy metadata” nor “this site holds a row for it” proves the payment is this site’s own.

Learnomy proves it with a site marker: lrn_ plus a short hash of the site’s address. It is computed, never stored. The address is normalised first (scheme, a leading www. and trailing slashes are dropped), so moving from http to https or adding www never changes it. Get it from Learnomy\Services\Site_Marker:

Call Answers
Site_Marker::metadata() What to write into the processor’s metadata: learnomy_site (the marker) and learnomy_site_url (the address, shown to the owner only).
Site_Marker::current() This site’s marker.
Site_Marker::verdict( $marker ) own, moved (the owner accepted it), refused (the owner said it is a copy), foreign or unmarked.
  1. Write the marker wherever it opens something at the processor: every checkout session, payment, order and subscription. Merge Site_Marker::metadata() into the metadata your processor round-trips (Stripe metadata[...], a PayPal custom_id, a WooCommerce order’s meta). The marker is 20 characters; the address is optional when space is short.
  2. Report it back on every normalized event as site_marker (and site_address when you have it). Read it from the object the event is about: the payment’s metadata, or for a renewal invoice its subscription’s.
  3. Report it from capture() as site_marker and site_address, so the hourly reconcile of a pending row books only this site’s payment.
  4. Report opened_at on payment events and from capture(): the unix time the processor opened the checkout or payment. A checkout opened on 2.3.x just before the update carries no marker and has no row; it is booked only when it was opened within the abandoned-checkout window (72 hours, learnomy_abandon_pending_after) before this site’s first request on 2.4.0.
  5. Stamp subscriptions by implementing stamp_site_marker( $subscription_reference, $replace ): read the processor subscription, and write Site_Marker::metadata() only while it still holds one of the markers in $replace ('' meaning none). Return true when it now holds this site’s marker. Learnomy calls it on the first renewal of a subscription sold before markers existed, and when the owner confirms a move. The default does nothing.
  6. An event that happens on this site carries this site’s marker: a test payment settled in the request carries Site_Marker::current(); a host shop’s order (WooCommerce) stores Site_Marker::metadata() on the order when it is created and reports Site_Marker::of_local_record( $stored ), which for an order made before markers is the marker of the address the database first ran at (so a staging copy holds it instead of booking it).

PayPal, as the worked example of a short metadata field. PayPal round-trips one custom_id of at most 127 characters, and cuts anything longer. The built-in PayPal gateway writes the marker as the first chunk, s:lrn_...|u:12|c:34|..., so the cut can never drop it, and leaves the address out. It reads it back from the order’s purchase unit, a capture’s or subscription’s custom_id, or a renewal sale’s custom (falling back to the subscription’s own custom_id), and stamp_site_marker() rewrites only that chunk with a PATCH, keeping the rest.

A refund or dispute usually reports only the charge. You need not find the checkout’s metadata for it: Learnomy records the marker on every sale it books (site_marker in the sale’s metadata) and judges the refund by the sale it names.

The first payment after a trial: data.cycle

Section titled “The first payment after a trial: data.cycle”

On a subscription.renewed event, set data['cycle'] to true when the payment bills a whole billing cycle (Stripe: billing_reason is subscription_cycle; PayPal: every sale of a subscription), and state its start in data['period_start_utc']. Learnomy ends a trial itself, hourly, so its own period may already reach past your first paid one. A payment marked this way, starting within a day of the trial’s end and not yet on the ledger, is booked and the period left as it is. Without the flag such a payment reads as “nothing renewed”, as a proration or a charge inside the period does.

Finding a renewal whose webhook was lost: missed_renewals()

Section titled “Finding a renewal whose webhook was lost: missed_renewals()”

missed_renewals( $subscription_reference, $after_utc ) answers, read-only, which renewals the processor took for a subscription beyond the period end this site holds. Learnomy calls it just before it would end access for want of a renewal, and at most once a day per subscription. Learnomy Pro also calls it right after a failed renewal it retried was paid, so the retried payment is booked with its own invoice and period. Return the subscription.renewed events parse_webhook() would have returned for those payments, oldest first, each with its own payment id, amount, period and site marker; an empty array when nothing newer was paid (still retrying, unpaid, refunded in full, disputed, or ended at the processor); a WP_Error when the processor did not answer. Learnomy books them on the webhook’s own path, so a webhook that arrives later books nothing again. While it gets a WP_Error, the subscription is kept for 7 days past the grace period, the owner is told, and then it ends. The default answers null (cannot say), and the subscription ends after the grace period without being asked about. Stripe and PayPal implement it.

Reporting what the processor holds: subscription_state()

Section titled “Reporting what the processor holds: subscription_state()”

subscription_state( $sub ) answers, read-only, what the processor holds for a subscription now: array( 'state' => 'active' | 'held' | 'ended' | 'unknown', 'site_marker' => ... ). held is paused or suspended. A subscription the processor cannot find is unknown, never ended: it may belong to the other mode or another account. The 2.4.0 upgrade repair calls it once for every live subscription (Services\Billing_End_Repair, Action Scheduler hook learnomy_repair_ended_billing) to end here what 2.3.x had already ended at the processor. It writes nothing to the processor: a subscription still billing is stamped only by its first renewal delivered to this site, so a staging copy updated before live never claims live’s subscriptions. The default answers unknown, so a gateway that does not implement it is left alone.

The event’s marker This site holds a row for it Result
this site’s, or one the owner accepted any applied
another site’s no 200, logged as ignored, ignored:not_this_site. No users, sales, refunds, access or notices.
another site’s yes 200, logged as held. Nothing is applied. The owner is asked once whether this site moved from that address.
refused by the owner any 200, ignored:not_this_site
none (sold before 2.4.0, or a gateway that sends none) no ignored:not_this_site, except a payment opened just before this site’s update to 2.4.0 (opened_at, above), which is applied
none yes, and this database is at the address it first ran at applied; on a renewal, the subscription is stamped
none yes, but this database first ran at another address (a copy) held, as above

“This site holds a row” means a checkout or sale with the event’s reference, or a subscription with its subscription_reference. A product that keeps its own processor subscriptions (Pro spaces) answers the learnomy_site_holds_reference filter.

The owner’s answer is the one option learnomy_site_markers: the accepted and refused markers and the address this database first ran at. Yes, this site moved accepts the old marker, applies every held delivery exactly once (each Payment Log row is claimed held to replaying before it is applied; more than 25 continue on the learnomy_replay_held_payments job) and stamps their subscriptions. No, this is a copy refuses it and closes the held rows as ignored.

A listener on a gateway’s raw events (learnomy_gateway_raw_event, learnomy_stripe_webhook_event) is not called for another site’s delivery; a held one is passed on when the owner accepts it.

A product type is something other than a course or a membership plan: a gift, a seat pack, a bundle. Declare it on learnomy_checkout_purchase_types; Learnomy’s checkout then handles coupons, tax, billing details, zero-total orders and every gateway for it. You fulfil it in a listener.

add_filter( 'learnomy_checkout_purchase_types', function ( array $types ) {
$types['bundle'] = array(
'label' => __( 'Bundle', 'acme' ),
// What this request buys: amount, currency, item_id, optional extra.
'resolve' => function ( \WP_REST_Request $request, int $user_id ) {
$bundle = acme_get_bundle( (int) $request->get_param( 'item_id' ) );
return $bundle
? array( 'amount' => $bundle->price, 'currency' => \Learnomy\charge_currency(), 'item_id' => $bundle->id, 'extra' => array( 'courses' => implode( ',', $bundle->course_ids ) ) )
: new \WP_Error( 'acme_no_bundle', 'Bundle not found', array( 'status' => 404 ) );
},
// What a full refund takes back.
'revoke' => function ( object $transaction ) {
acme_revoke_bundle( (int) $transaction->user_id, (int) $transaction->item_id );
return array( 'revoked' => true, 'notice' => '' );
},
);
return $types;
} );
// Fulfil it when the payment is recorded, whichever gateway took it.
add_action( 'learnomy_purchase_completed', function ( $txn_id, $user_id, $type, $item_id, $ext, $gateway ) {
if ( 'bundle' === $type ) {
acme_grant_bundle( (int) $user_id, (int) $item_id, $ext );
}
}, 10, 6 );

A type with a revoke handler that deliberately takes nothing back must still register one that returns a notice, so “nothing to undo” and “nobody implemented this” stay distinguishable.

When a sale happens in another system and that system notifies Learnomy, it posts to the signed endpoint POST /wp-json/learnomy/v1/webhooks/enrollment. The built-in source reads a JSON or form body signed with HMAC-SHA256; the Incoming Access Webhook page documents the fields and the Make and Zapier recipes.

For a system with its own wire format, implement Learnomy\Adapters\Inbound_Purchase_Source:

class Gumroad_Source implements \Learnomy\Adapters\Inbound_Purchase_Source {
public function get_id(): string { return 'gumroad'; }
public function matches( \WP_REST_Request $r ): bool { return 'gumroad' === $r->get_param( 'source' ); }
// Gumroad's ping is not signed, so the ping URL carries a long random token:
// .../webhooks/enrollment?source=gumroad&token=<secret saved in your settings>
public function verify( \WP_REST_Request $r, string $raw_body ) {
$secret = (string) get_option( 'acme_gumroad_token', '' );
return '' !== $secret && hash_equals( $secret, (string) $r->get_param( 'token' ) )
? true
: new \WP_Error( 'gumroad_bad_token', 'Unknown sender', array( 'status' => 403 ) );
}
public function normalise( \WP_REST_Request $r ) {
return array(
'op' => $r->get_param( 'refunded' ) ? 'refund' : 'purchase',
'user_email' => (string) $r->get_param( 'email' ),
'full_name' => (string) $r->get_param( 'full_name' ),
'purchase_type'=> 'course',
'item_id' => (int) acme_course_for_product( (string) $r->get_param( 'product_id' ) ),
'external_ref' => (string) $r->get_param( 'sale_id' ),
'amount' => (float) $r->get_param( 'price' ) / 100,
'tax' => 0,
'currency' => strtoupper( (string) $r->get_param( 'currency' ) ),
'access_days' => 0,
'coupon' => '',
'refund_ref' => '',
'provider' => 'gumroad',
);
}
}
add_filter( 'learnomy_incoming_purchase_sources', function ( array $sources ) {
$sources['gumroad'] = new Gumroad_Source();
return $sources;
} );

The source only verifies and maps field names. Learnomy validates the result the same way for every source (Incoming_Purchase_Service::validate(): email, a positive item id, external_ref, amounts of 0 or more, the site currency), then carries it out (op: grant / op: revoke through Access Grants; the deprecated op: purchase / op: refund through the provisioner and refund funnel), logs the call in Payment log > Incoming webhook, and answers the sender.

tests/payments/cross-adapter-conformance.php runs the same purchase scenarios through every inlet (Test, Stripe, PayPal, WooCommerce and the incoming sales endpoint) and asserts the same database outcome: the transaction, the fired actions, commission rows, enrolment, refunds, and that nothing is left behind afterwards. Scenarios cover one-time and recurring courses, memberships, coupons, tax, access days, multi-course orders, guest buyers, and the Pro types (learning path, Space, seats, gift). Run it after any change to payment code:

wp eval-file wp-content/plugins/learnomy/tests/payments/cross-adapter-conformance.php
wp eval-file wp-content/plugins/learnomy/tests/payments/cross-adapter-conformance.php strict

It prints a matrix per scenario. A cell is PASS, FAIL, N/A with a written reason (for example, the Test gateway records a free sale, so it has no commission), or SKIP with an owner and an expiry date. Any FAIL exits 1. An expired skip counts as a failure. In strict mode (or with LEARNOMY_CONFORMANCE_STRICT=1), any remaining skip exits 2.

tests/payments/gateway-capability-contract.php registers a sample third-party adapter (tests/payments/fixtures/qa-sample-adapter.php) and proves it gets its configured state, a manage link and proration without any edit outside its own file, and that no Learnomy Refund button is offered for it. Use that fixture as a second worked example.

Hook Type Use
learnomy_register_gateways filter ( $gateways ) add your gateway instance to the list (later registration of the same id wins).
learnomy_register_payment_adapters action The pre-2.4.0 way to register a gateway with Adapter_Registry::register(); still works.
learnomy_offered_gateways filter ( $offered, $currency ) which gateways checkout offers for a currency.
learnomy_gateway_raw_event action ( $gateway_id, $event_type, $payload ) a verified delivery, before it is applied; for payout rails that keep their own records only.
learnomy_checkout_purchase_types filter Declare a product type (label, resolve, validate, supports, revoke).
learnomy_purchase_completed action ( $txn_id, $user_id, $type, $item_id, $ext, $gateway, $payment_ref ) after any sale is recorded. Fulfil your product type here. Every row of a cart shares $payment_ref.
learnomy_payment_completed action ( $txn_id, $user_id, $gateway, $payment_ref ) after money is recorded; commissions run here.
learnomy_cart_enabled filter ( $enabled ) whether the multi-course cart is available.
learnomy_cart_max_lines filter ( $max ) most courses one cart may hold (default 20).
learnomy_incoming_purchase_sources filter Add an inbound source.
learnomy_incoming_webhook_payload filter Change a normalised incoming operation before it runs.
learnomy_site_holds_reference filter ( $holds, $event, $gateway_id ) true when your product holds a row for a payment event’s reference (only this site’s payments).
learnomy_site_marker_address filter ( $address ) the address the site marker is made from; for one site served at several addresses, return the one they share.
learnomy_plans_url filter ( $url, $sub ) where a member whose subscription ended is sent to start a new one (the refusal’s See plans link); default the membership plans page while memberships are on sale, otherwise the course catalog.
learnomy_site_marker_accepted filter ( $accepted, $marker ) accept another address’s marker as this site’s own.
learnomy_pro_proration_provider filter Deprecated since 2.4.0. Pro: a proration provider for a gateway that does not declare subscription_plan_change. Declare the recurring flags instead.

Every hook with its full argument list is on the Hooks Reference.