LifterLMS Payment Gateway Development: Extending LLMS_Payment_Gateway

How to build a custom LifterLMS payment gateway: the order lifecycle, the LLMS_Payment_Gateway methods you implement, a hosted-checkout skeleton with signed webhooks and refunds, and how to approach recurring billing.

  • Add as a preferred source on Google
Illustration for “LifterLMS Payment Gateway Development: Extending LLMS_Payment_Gateway”

LifterLMS payment gateway development is the job of connecting LifterLMS checkout to a payment provider it does not support out of the box. Typical reasons are a regional processor, a bank's hosted payment page, an invoicing system for business buyers, or a provider your finance team already uses.

This guide is for WordPress developers. It explains how gateways plug into LifterLMS, which methods of the LLMS_Payment_Gateway abstract class you must implement, and shows a working skeleton for a hosted-checkout gateway with webhooks and refunds. Everything was checked against the LifterLMS 10.3 source.

Before writing one, check that you need it. LifterLMS sells Stripe, PayPal and Authorize.Net gateways as add-ons, and the WooCommerce integration add-on lets LifterLMS products use any WooCommerce gateway. LifterLMS keeps a list of supported payment gateways. If your provider has a solid WooCommerce plugin, that route is often cheaper to build and maintain. Our LifterLMS with WooCommerce article covers the trade-offs.

How payment gateways work in LifterLMS

A gateway is a PHP class that extends LLMS_Payment_Gateway. LifterLMS builds its list of gateways from the lifterlms_payment_gateways filter, which returns an array of class names, and instantiates each one. The core plugin registers only LLMS_Payment_Gateway_Manual, which handles offline payments and free orders.

The lifecycle of an order looks like this:

  1. Checkout. The student submits the checkout form. LifterLMS validates it, creates a pending llms_order and calls your gateway's handle_pending_order( $order, $plan, $person, $coupon ).
  2. Payment. Your gateway charges the student, inline or on a hosted page.
  3. Recording. When the money is confirmed, you call $order->record_transaction() with a status of llms-txn-succeeded. LifterLMS then sets the order to llms-completed (one-time) or llms-active (recurring), enrolls the student and schedules the next payment.
  4. Redirect. You call complete_transaction( $order ), which sends the student to the configured thank-you destination with the order key.
  5. Renewals. For recurring plans, Action Scheduler fires llms_charge_recurring_payment, and LifterLMS calls your handle_recurring_transaction( $order ).
  6. Refunds. When an admin refunds a transaction through your gateway, LifterLMS calls process_refund( $transaction, $amount, $note ).

The LifterLMS Developer Hub has the code reference for these classes. The data behind each step, orders, transactions and their meta, is described in our article on how LifterLMS stores its data.

The methods and properties you implement

MemberRequired?Purpose
$id, $title, $admin_titleYesInternal ID and the names shown at checkout and in the admin
$supportsYesFeature flags: checkout_fields, refunds, single_payments, recurring_payments, recurring_retry, test_mode, cc_save, modify_recurring_payments
handle_pending_order()Yes (abstract)Starts payment for a new order
handle_recurring_transaction()If recurringCharges a renewal
process_refund()If refundsReturns a refund ID string, or a WP_Error
get_fields() or the llms_get_gateway_fields filterIf inline fieldsHTML for card fields on the checkout form
is_external_payment_entry()OptionalReturn true when payment details are entered on an external page
handle_payment_source_switch()OptionalLets students change the payment method on a subscription
confirm_pending_order()OptionalFor flows with a separate confirmation step

Settings come for free. Every gateway gets its own section under LifterLMS > Settings > Checkout, with Enable / Disable, Title, Description, a test mode checkbox when test_mode is supported, and Debug Log. Options are stored with the prefix llms_gateway_{id}_. You add your own fields through the llms_get_gateway_settings_fields filter.

Step 1: Register the gateway

Put the gateway in its own small plugin. Requiring the class file inside the filter guarantees the abstract class has loaded.

<?php
/**
 * Plugin Name: LLMSX Example Pay for LifterLMS
 * Description: Hosted-checkout payment gateway for LifterLMS.
 */

defined( 'ABSPATH' ) || exit;

// Register the gateway class. The abstract class is loaded by the time this filter runs.
add_filter(
	'lifterlms_payment_gateways',
	function ( $gateways ) {
		require_once __DIR__ . '/class-llmsx-gateway-example.php';
		$gateways[] = 'LLMSX_Gateway_Example';
		return $gateways;
	}
);

Step 2: Build the gateway class

This skeleton is a hosted-checkout gateway for an imaginary provider, "Example Pay". The student is redirected to the provider, pays there, and the provider confirms the payment with a webhook. Replace the API calls with your provider's real endpoints and fields.

<?php
defined( 'ABSPATH' ) || exit;

class LLMSX_Gateway_Example extends LLMS_Payment_Gateway {

	public function __construct() {
		$this->id                    = 'llmsx_example';
		$this->admin_title           = 'Example Pay';
		$this->admin_description     = 'Redirects students to Example Pay to pay.';
		$this->title                 = 'Example Pay';
		$this->description           = 'You will be sent to Example Pay to complete payment.';
		$this->test_mode_title       = 'Sandbox mode';
		$this->test_mode_description = 'Send payments to the Example Pay sandbox.';

		$this->supports = array(
			'checkout_fields'    => false,
			'refunds'            => true,
			'single_payments'    => true,
			'recurring_payments' => false,
			'test_mode'          => true,
		);

		add_filter( 'llms_get_gateway_settings_fields', array( $this, 'settings_fields' ), 10, 2 );
	}

	public function is_external_payment_entry() {
		return true;
	}

	public function settings_fields( $fields, $gateway_id ) {
		if ( $this->id !== $gateway_id ) {
			return $fields;
		}
		$fields[] = array(
			'id'            => $this->get_option_name( 'api_key' ),
			'title'         => 'API key',
			'type'          => 'password',
			'secure_option' => 'LLMSX_EXAMPLE_API_KEY',
		);
		$fields[] = array(
			'id'            => $this->get_option_name( 'webhook_secret' ),
			'title'         => 'Webhook signing secret',
			'type'          => 'password',
			'secure_option' => 'LLMSX_EXAMPLE_WEBHOOK_SECRET',
		);
		return $fields;
	}

	public function get_api_base() {
		return $this->is_test_mode_enabled()
			? 'https://sandbox.example-pay.test/v1'
			: 'https://api.example-pay.test/v1';
	}

	public function handle_pending_order( $order, $plan, $person, $coupon = false ) {

		$this->log( 'Example Pay handle_pending_order() started', $order->get( 'id' ) );

		$response = wp_remote_post(
			$this->get_api_base() . '/checkout-sessions',
			array(
				'timeout' => 30,
				'headers' => array(
					'Authorization' => 'Bearer ' . $this->get_option( 'api_key', 'LLMSX_EXAMPLE_API_KEY' ),
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode(
					array(
						'amount'     => (int) round( $order->get_initial_price( array(), 'float' ) * 100 ),
						'currency'   => $order->get( 'currency' ),
						'email'      => $order->get( 'billing_email' ),
						'reference'  => $order->get( 'order_key' ),
						'return_url' => add_query_arg( 'llmsx_example_return', $order->get( 'order_key' ), home_url( '/' ) ),
					)
				),
			)
		);

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( is_wp_error( $response ) || empty( $body['checkout_url'] ) ) {
			$this->log( 'Example Pay session failed', $response );
			llms_add_notice( 'We could not start your payment. Please try again.', 'error' );
			return;
		}

		$order->add_note( 'Example Pay session created: ' . sanitize_text_field( $body['id'] ) );

		// Send the student to the hosted payment page (an external URL).
		llms_redirect_and_exit( esc_url_raw( $body['checkout_url'] ), array( 'safe' => false ) );
	}

	public function process_refund( $transaction, $amount = 0, $note = '' ) {

		$response = wp_remote_post(
			$this->get_api_base() . '/refunds',
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $this->get_option( 'api_key', 'LLMSX_EXAMPLE_API_KEY' ),
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode(
					array(
						'payment_id' => $transaction->get( 'gateway_transaction_id' ),
						'amount'     => (int) round( $amount * 100 ),
						'reason'     => $note,
					)
				),
			)
		);

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( is_wp_error( $response ) || empty( $body['refund_id'] ) ) {
			return new WP_Error( 'llmsx-refund-failed', 'Example Pay did not accept the refund.' );
		}

		// LifterLMS records the refund when a string ID is returned.
		return sanitize_text_field( $body['refund_id'] );
	}
}

A few details are worth pointing out:

  • Secrets. Each field declares a secure_option. get_option( 'api_key', 'LLMSX_EXAMPLE_API_KEY' ) reads an environment variable or constant with that name first and only falls back to the database. That keeps live keys out of database copies and staging sites. Secure values are also masked in the gateway's debug log.
  • Errors. On the standard form checkout, adding an error notice with llms_add_notice() and returning shows the checkout again with the message, and the pending order is reused when the student retries.
  • Redirects. llms_redirect_and_exit() with 'safe' => false is needed to send the student to an external domain.
  • Amounts. get_initial_price( array(), 'float' ) includes coupons and trials, so use it rather than the plan price.

Step 3: Confirm payment with a webhook

Never enroll a student on the strength of a browser redirect alone; anyone can visit a return URL. Let the provider tell your server that money moved, verify the message, then record the transaction.

<?php
// Example Pay calls this URL when a payment succeeds.
add_action(
	'rest_api_init',
	function () {
		register_rest_route(
			'llmsx-example/v1',
			'/webhook',
			array(
				'methods'             => 'POST',
				'permission_callback' => '__return_true', // Authenticity is checked by signature below.
				'callback'            => 'llmsx_example_webhook',
			)
		);
	}
);

function llmsx_example_webhook( WP_REST_Request $request ) {

	$gateway = llms()->payment_gateways()->get_gateway_by_id( 'llmsx_example' );
	$secret  = $gateway->get_option( 'webhook_secret', 'LLMSX_EXAMPLE_WEBHOOK_SECRET' );
	$sig     = hash_hmac( 'sha256', $request->get_body(), $secret );

	if ( ! hash_equals( $sig, (string) $request->get_header( 'x-example-signature' ) ) ) {
		return new WP_REST_Response( array( 'error' => 'bad signature' ), 401 );
	}

	$event = $request->get_json_params();
	$order = llms_get_order_by_key( sanitize_text_field( $event['reference'] ?? '' ) );

	if ( ! $order || 'llmsx_example' !== $order->get( 'payment_gateway' ) ) {
		return new WP_REST_Response( array( 'error' => 'unknown order' ), 404 );
	}

	// Webhooks can arrive more than once: only record the first success.
	if ( 'payment.succeeded' === ( $event['type'] ?? '' ) && 'llms-pending' === $order->get( 'status' ) ) {
		$order->record_transaction(
			array(
				'amount'             => floatval( $event['amount'] ) / 100,
				'transaction_id'     => sanitize_text_field( $event['payment_id'] ),
				'status'             => 'llms-txn-succeeded',
				'payment_type'       => 'single',
				'source_description' => 'Example Pay',
			)
		);
	}

	return new WP_REST_Response( array( 'received' => true ), 200 );
}

// The student comes back from the hosted page.
add_action(
	'template_redirect',
	function () {
		if ( empty( $_GET['llmsx_example_return'] ) ) {
			return;
		}

		$order = llms_get_order_by_key( sanitize_text_field( wp_unslash( $_GET['llmsx_example_return'] ) ) );
		if ( ! $order ) {
			return;
		}

		if ( in_array( $order->get( 'status' ), array( 'llms-completed', 'llms-active' ), true ) ) {
			// Paid: use the standard LifterLMS completion redirect.
			llms()->payment_gateways()->get_gateway_by_id( 'llmsx_example' )->complete_transaction( $order );
		}

		// Webhook not processed yet: show the order while it is pending.
		llms_redirect_and_exit( $order->get_view_link() );
	}
);

Recording the transaction is what grants access. The lifterlms_transaction_status_succeeded handler moves the order to completed, which enrolls the student, sends the receipt and fires engagements. The status check makes the webhook idempotent, because most providers retry deliveries.

If your provider confirms payment synchronously, for example with an API call that returns a captured payment, you can skip the webhook: record the transaction in handle_pending_order() and call $this->complete_transaction( $order ) straight away.

Adding recurring payments

Recurring support is where most of the effort goes. There are two models, and you must choose one.

  • LifterLMS schedules, your gateway charges. Set recurring_payments to true, store the provider's customer and payment method references on the order (gateway_customer_id and gateway_source_id), and implement handle_recurring_transaction() to charge the saved method and record a transaction with a payment_type of recurring. Record failures as llms-txn-failed so LifterLMS can put the order on hold and, if you declare recurring_retry, schedule retries. This keeps LifterLMS as the single source of truth for billing dates.
  • The provider runs the subscription. The provider bills on its own schedule and sends webhooks. You then have to stop LifterLMS from also charging, and map every provider event (renewal, failure, cancellation) to transactions and order statuses yourself. It is workable, but two schedules drift, so we only use it when the provider gives no other option.

Either way, test with the provider's sandbox across a full cycle: trial, first renewal, failed renewal, retry, cancellation and refund. Remember that LifterLMS skips recurring charges on staging copies whose URL does not match the stored site lock, which protects real customers but can confuse testing. Our article on staging sites and recurring payments explains that behaviour.

Testing and common mistakes

Testing checklist

  • One-time purchase, with and without a coupon, in test mode.
  • Failed payment and a payment the student abandons on the hosted page.
  • Duplicate webhook delivery and a webhook with a bad signature.
  • Full and partial refund from the order screen.
  • Free access plan and a 100% coupon, which LifterLMS normally routes through the manual gateway rather than yours.
  • Debug log enabled: confirm keys are masked.
  • Student, admin and receipt emails all fire once.

Common mistakes

  • Enrolling in the return handler. Grant access only from a verified server-side confirmation.
  • Ignoring idempotency. Without a status check, a retried webhook records a second transaction.
  • Hard-coding prices. Always charge the order's own amounts and currency.
  • Storing live keys in the database. Use the secure_option constants so cloned databases cannot charge cards.
  • Forgetting the admin side. Set $admin_order_fields and the URL helper methods so admins can jump from an order to the provider's dashboard.

Frequently asked questions

Can I use any WooCommerce gateway with LifterLMS instead?

Yes, through the paid WooCommerce integration add-on, which sells LifterLMS access through WooCommerce products and checkout. You then manage two order systems, so weigh that against building a native gateway.

Where are gateway settings stored?

In the options table, prefixed llms_gateway_{id}_, unless you supply a value with an environment variable or constant named in the field's secure_option.

Does a custom gateway work with the LifterLMS REST API and webhooks?

Yes. Orders and transactions it records are normal LifterLMS data, so order.* and transaction.* webhooks fire and the REST API returns them.

Next steps

Start with the provider's sandbox and the one-time payment flow. Add refunds next, and recurring billing only once single payments are solid and tested.

Payment code handles real money, so it deserves review. If you want a gateway built, audited or extended with subscriptions, our LifterLMS plugin development team builds and maintains gateways, and our hooks and filters guide is a good companion for your own work. Tell us about your provider and we will scope it.

Add LifterLMS Expert to your preferred sources

Add lifterlmsexpert.com as a preferred source on Google, or open this article in your AI assistant to use it as a source.

  • Add as a preferred source on Google
Free consultation

Prefer expert help over DIY?

Skip the trial and error. Get specialist LifterLMS help and ship faster.

Talk to a LifterLMS Expert Explore our services

Replies within one business day