Plugin common to WordPress and Moodle Platforms

Sometimes you may want to have a plugin that works in both a WordPress and Moodle environments. I had a requirement for a plugin that implemented the client for a payment gateway API. In WordPress I needed this as a plugin to enhance WooCommerce for reconciling bank transfer payments against orders. In Moodle I needed same API to create payment accounts for students.

Since both platforms use PHP a majority of code is reusable. It is convenient to partition the plugin code into Moodle Only, WordPress Only and Common type code.

The Common code must recognize which environment the calling program is and react accordingly. Moodle uses configuration settings in plugins to store information such as API key, secret, etc. WordPress uses something similar called options. So, based on environment our common code gets the stored configuration. For example, just before the class definition for the API the following code will ensure that the page cannot be directly accessed:

if (!defined( "ABSPATH" ) && !defined( "MOODLE_INTERNAL" ) )
{
die( 'No script kiddies please!' );
}

The following shows the constructor that detects the calling environment and builds the class object accordingly:

public function __construct( $site_name = null )
{
if ( defined("ABSPATH") )
{
// we are in wordpress environment, don't care about argument since get_option is site dependendent
$api_key = $this->getoption("sritoni_settings", "razorpay_key");
$api_secret = $this->getoption("sritoni_settings", "razorpay_secret");
}

if ( defined("MOODLE_INTERNAL") )
{
// we are in MOODLE environment
// based on passed in $site_name change the strings for config select. $site must be passed correctly for this to work
if (stripos($site_name, 'hset') !== false)
{
$key_string = 'razorpay_api_key_hset';
$secret_string = 'razorpay_api_secret_hset';
}
if (stripos($site_name, 'llp') !== false)
{
$key_string = 'razorpay_api_key_llp';
$secret_string = 'razorpay_api_secret_llp';
}

$api_key = get_config('block_configurable_reports', $key_string);
$api_secret = get_config('block_configurable_reports', $secret_string);
}
$this->password = $api_key . ":" . $api_secret;

Here, since I had to manage 2 sites, Moodle had to be coded differently from WordPress. In WordPress each site is managed separately for option data and so it is easy. In Moodle we have to manage this ourselves. So we pass an argument for the constructor that depends on site and based on that we get corresponding API.

Posted in Uncategorized.