LMS & eLearning

Building a Custom Payment Gateway for LearnDash

How LearnDash payment gateways are structured: the abstract Learndash_Payment_Gateway class, the learndash_payment_gateways filter, the methods you implement, the access and transaction helpers, and a skeleton.

Building a Custom Payment Gateway for LearnDash

LearnDash ships PayPal, Stripe Connect and Razorpay, and since the 4.5 payments rewrite all three sit on one abstract class. That class is the extension point for a regional processor, a bank transfer flow, or an internal credits system: implement its abstract methods, return an instance from one filter, and your gateway appears in the payment settings, renders a button on priced courses and groups, grants access and records transactions exactly as the built-in gateways do. This guide walks through the class as LearnDash 4.18.0.1 defines it and gives a skeleton you can complete. It assumes familiarity with how transactions are recorded, covered in our payment and transaction hooks reference.

How gateways are loaded

includes/payments/gateways/init.php requires the base class and the four built-in gateway classes, including an Unknown gateway used as a fallback, then on init runs apply_filters( 'learndash_payment_gateways', array( ...instances ) ) and calls init() on every element that is an instance of Learndash_Payment_Gateway. Registration is therefore one filter callback that appends your instance. The base init() stores the gateway in a static registry by name, calls your configure(), and stops if is_ready() is false, which is how an unconfigured gateway stays dormant. When ready it marks the gateway active, calls add_extra_hooks(), hooks enqueue_scripts() to learndash_payment_button_added, adds add_payment_button() to the learndash_payment_buttons filter at priority 11, registers the AJAX setup action for logged-in and logged-out users, and attaches process_webhook() to wp_loaded.

The methods you implement

MethodPurpose
get_name(): string (static)Machine name, used as the registry key, in transaction meta and in settings keys.
get_label(): string (static)Human label shown in settings and on transactions.
configure(): voidLoad your settings, typically with LearnDash_Settings_Section::get_section_settings_all().
is_ready(): boolTrue when credentials exist. False keeps the gateway inactive.
is_test_mode(): boolWhether sandbox credentials are in use; LearnDash shows a test mode notice.
add_extra_hooks(): voidAny additional hooks; Razorpay registers none.
enqueue_scripts(): voidFront-end script for your checkout, loaded when a button is rendered.
map_payment_button_markup( array $params, WP_Post $post ): stringReturn the button HTML for a course or group.
setup_payment(): voidAJAX handler that prepares a session or order and returns what the script needs.
process_webhook(): voidHandle the processor's server-to-server notification.
map_transaction_meta( $data, Product $product ): Learndash_Transaction_Meta_DTOTranslate processor data into LearnDash's transaction meta.

Optional overrides include supports_logger(), true by default, which creates a transaction logger for you; supports_transactions_management() and cancel_subscription( string $subscription_id ) for gateways that can cancel from the admin; get_checkout_label(), get_checkout_meta_html() and get_checkout_info_text() for the checkout box; and get_settings_url().

Helpers the base class gives you

  • add_access_to_products( array $products, WP_User $user ) and remove_access_to_products() enrol or unenrol the user in every purchased course or group product, returning the results.
  • record_transaction( array $meta, WP_Post $post, WP_User $user ): int creates the transaction post and fires the transaction hooks.
  • find_or_create_user( int $user_id, string $email, string $customer_id ) resolves or creates the WordPress account for a guest checkout, firing learndash_payment_gateway_user_created.
  • get_price_in_subunits( float $price ): int converts to cents or paise according to the currency.
  • log_info() and log_error() write to the gateway's transaction log with a per-request prefix.
  • maybe_ignore_event( array $event ), filterable through learndash_payment_gateway_event_ignore, and finish_webhook_processing( array $event, bool $processed ), which fires learndash_payment_gateway_event_processed and sends the response.
  • Success and failure return URLs are resolved for you and pass through learndash_payment_option_url_success and learndash_payment_option_url_fail.

Settings

Each built-in gateway has a settings section class extending LearnDash_Settings_Section with settings_page_id set to learndash_lms_payments, its own setting_option_key such as learndash_settings_razorpay, a settings_section_key and a label. Create one for your gateway with fields for credentials, a test mode toggle and a read-only webhook URL, then read it in configure(). Our settings API guide explains the section class.

A skeleton

<?php
class Acme_Pay_Gateway extends Learndash_Payment_Gateway {
    private $settings = array();

    public static function get_name(): string {
        return 'acme_pay';
    }

    public static function get_label(): string {
        return 'Acme Pay';
    }

    protected function configure(): void {
        $this->settings = (array) LearnDash_Settings_Section::get_section_settings_all( 'Acme_Settings_Section_Pay' );
    }

    public function is_ready(): bool {
        return ! empty( $this->settings['api_key'] );
    }

    protected function is_test_mode(): bool {
        return ! empty( $this->settings['test_mode'] ) && 'yes' === $this->settings['test_mode'];
    }

    public function add_extra_hooks(): void {}

    public function enqueue_scripts(): void {
        wp_enqueue_script( 'acme-pay', plugins_url( 'js/acme-pay.js', __FILE__ ), array( 'learndash-payments' ), '1.0.0', true );
    }

    protected function map_payment_button_markup( array $params, WP_Post $post ): string {
        $label = $this->map_payment_button_label( 'Pay with Acme', $post );
        return '<button type="button" class="' . esc_attr( $this->get_form_class_name( 'acme-pay-button' ) ) . '" data-post-id="' . absint( $post->ID ) . '">' . esc_html( $label ) . '</button>';
    }

    public function setup_payment(): void {
        // Verify the nonce from get_nonce_name(), create an order with the processor,
        // store the post ID and user ID in the order metadata, then wp_send_json_success()
        // with whatever the front-end script needs to redirect or open the checkout.
    }

    public function process_webhook(): void {
        if ( ! isset( $_GET['learndash-integration'] ) || static::get_name() !== $_GET['learndash-integration'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return;
        }
        $event = json_decode( (string) file_get_contents( 'php://input' ), true );
        if ( ! is_array( $event ) ) {
            $this->finish_webhook_processing( array(), false );
            return;
        }
        $this->log_info( 'Webhook received: ' . sanitize_text_field( (string) ( $event['type'] ?? '' ) ) );
        // 1. Verify the event with the processor (signature or re-fetch by ID).
        // 2. Load products from the stored post IDs: Product::find( $post_id ).
        // 3. $user = $this->find_or_create_user( $user_id, $email, $customer_id );
        // 4. $this->add_access_to_products( $products, $user );
        // 5. foreach product: $this->record_transaction( $this->map_transaction_meta( $event, $product )->to_array(), $product->get_post(), $user );
        $this->finish_webhook_processing( $event, true );
    }

    protected function map_transaction_meta( $data, Product $product ): Learndash_Transaction_Meta_DTO {
        return Learndash_Transaction_Meta_DTO::create(
            array(
                Transaction::$meta_key_gateway_name        => static::get_name(),
                Transaction::$meta_key_price_type          => $product->get_pricing_type(),
                Transaction::$meta_key_pricing_info        => $product->get_pricing()->to_array(),
                Transaction::$meta_key_gateway_transaction => Learndash_Transaction_Gateway_Transaction_DTO::create(
                    array(
                        'id'    => (string) ( $data['id'] ?? '' ),
                        'event' => $data,
                    )
                ),
            )
        );
    }
}

add_filter(
    'learndash_payment_gateways',
    function ( array $gateways ): array {
        $gateways[] = new Acme_Pay_Gateway();
        return $gateways;
    }
);

The webhook convention follows the built-in gateways: they all listen on wp_loaded for a learndash-integration query argument naming the gateway, so your processor's notification URL is the site URL with learndash-integration=acme_pay. The transaction meta keys are static properties of the Transaction model, and the pricing DTO comes from the product model, both described in our models reference.

Testing checklist

  1. Settings saved and is_ready() true: the gateway appears in LearnDash, Settings, Payments and the button renders on a Buy Now course.
  2. Setup AJAX returns success for logged-in and guest users, and the nonce from get_nonce_name() is checked.
  3. A webhook with a forged body is rejected before access is granted.
  4. A valid webhook enrols the user, creates a transaction visible under LearnDash, Transactions with your gateway label, and writes to the gateway log.
  5. Repeated delivery of the same event does not create a second transaction.
  6. Subscriptions, if supported, handle renewal, failure and cancellation, as the Stripe gateway does in our Stripe webhook guide.

When to get help

A one-time payment gateway is a few days of focused work with the skeleton above. Subscriptions, refunds that revoke access, coupons, invoices and PCI considerations turn it into a project; our LearnDash services team and API integration practice have built gateways for regional processors, and a LearnDash developer can also review a gateway for webhook security before launch.

Frequently asked questions

How do I register a custom gateway with LearnDash?

Extend Learndash_Payment_Gateway, implement its abstract methods, and return an instance from the learndash_payment_gateways filter. LearnDash calls init() for you.

Why does my gateway not show a button?

is_ready() returned false, so init() stopped before registering the button filter. Check that configure() loads your credentials.

How do I grant course access after payment?

Resolve the user with find_or_create_user(), then call add_access_to_products() with the purchased products and record_transaction() for each.

Where should my webhook URL point?

Follow the built-in convention: the site URL with learndash-integration set to your gateway name, handled in process_webhook() on wp_loaded.

Add WorldWin Coder to your preferred sources

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

· Developers and project managers

Articles written and reviewed by the developers and project managers at WorldWin Coder, who build and maintain websites, web applications and mobile apps on WordPress, Moodle, PHP, Laravel, CodeIgniter and Flutter.

Free consultation

Need help with LearnDash?

Tell us what you are working on. A developer who does this every week reads your message and replies within one business day with next steps and a free quote.

  • Free consultation and quote
  • NDA on request
  • You own the source code
  • Reply within one business day

Tell us about your project

Add budget and timeline optional, helps us quote faster

This form is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Keep reading

Have something to build, fix or move?

Tell us where you are. A developer reads every inquiry, and you get next steps and a free quote within one business day.